## 导入所需的包

import pandas as pd

import numpy as np

import matplotlib.pyplot as plt

import tensorflow as tf

tf.reset_default_graph()

plt.rcParams['font.sans-serif'] = 'SimHei' ##设置字体为SimHei显示中文

plt.rcParams['axes.unicode_minus'] = False ##设置正常显示符号

## 导入所需数据

df = pd.read_csv('日元-人民币.csv',encoding='gbk',engine='python')

df['时间'] = pd.to_datetime(df['时间'],format='%Y/%m/%d')

df = df.sort_values(by='时间')

df.head()

## 用折线图展示数据

plt.figure(figsize=(12,8))

plt.title('1999年1月1日到2018年8月21日最高价数据曲线')

plt.plot(df['time'],df['高'])

plt.show()

### 提取测试数据

data = df.loc[:,['time','高']]

## 标准化数据

data['高'] = (data['高']-np.mean(data['高']))/np.std(data['高'])

data['高(预)'] = data['高'].shift(-1)

data = data.iloc[:data.shape[0]-1]

data.columns = ['时间','x','y']

data.head()

#获取最高价序列

data=np.array(df['高'])

normalize_data=(data-np.mean(data))/np.std(data) #标准化

normalize_data=normalize_data[:,np.newaxis] #增加维度

#———————————————形成训练集——————————————————

#设置常量

time_step=20 #时间步

rnn_unit=10 #hidden layer units

batch_size=60 #每一批次训练多少个样例

input_size=1 #输入层维度

output_size=1 #输出层维度

lr=0.0006 #学习率

train_x,train_y=[],[] #训练集

for i in range(len(normalize_data)-time_step-1):

x=normalize_data[i:i+time_step]

y=normalize_data[i+1:i+time_step+1]

train_x.append(x.tolist())

train_y.append(y.tolist())

test_x = train_x[len(train_x)-31:len(train_x)-1]

test_y = train_y[len(train_y)-31:len(train_y)-1]

X=tf.placeholder(tf.float32, [None,time_step,input_size]) #每批次输入网络的tensor

Y=tf.placeholder(tf.float32, [None,time_step,output_size]) #每批次tensor对应的标签

#输入层、输出层权重、偏置

weights={

'in':tf.Variable(tf.random_normal([input_size,rnn_unit])),

'out':tf.Variable(tf.random_normal([rnn_unit,1]))

}

biases={

'in':tf.Variable(tf.constant(0.1,shape=[rnn_unit,])),

'out':tf.Variable(tf.constant(0.1,shape=[1,]))

}

def lstm(batch): #参数:输入网络批次数目

w_in=weights['in']

b_in=biases['in']

input=tf.reshape(X,[-1,input_size]) #需要将tensor转成2维进行计算,计算后的结果作为隐藏层的输入

input_rnn=tf.matmul(input,w_in)+b_in

input_rnn=tf.reshape(input_rnn,[-1,time_step,rnn_unit]) #将tensor转成3维,作为lstm cell的输入

cell=tf.nn.rnn_cell.BasicLSTMCell(rnn_unit)

init_state=cell.zero_state(batch,dtype=tf.float32)

output_rnn,final_states=tf.nn.dynamic_rnn(cell,input_rnn,initial_state=init_state, dtype=tf.float32) #output_rnn是记录lstm每个输出节点的结果,final_states是最后一个cell的结果

output=tf.reshape(output_rnn,[-1,rnn_unit]) #作为输出层的输入

w_out=weights['out']

b_out=biases['out']

pred=tf.matmul(output,w_out)+b_out

return pred,final_states

def train_lstm():

global batch_size

pred,_=lstm(batch_size)

#损失函数
loss=tf.reduce_mean(tf.square(tf.reshape(pred,[-1])-tf.reshape(Y, [-1])))

train_op=tf.train.AdamOptimizer(lr).minimize(loss)

saver=tf.train.Saver(tf.global_variables())

with tf.Session() as sess:

sess.run(tf.global_variables_initializer())

#重复训练100次

for i in range(100):

step=0

start=0

end=start+batch_size

while(end<len(train_x)): _,loss_=sess.run([train_op,loss],feed_dict={X:train_x[start:end],Y:train_y[start:end]})

start+=batch_size

end=start+batch_size

#每10步保存一次参数

if step%10==0:

print(i,step,loss_)

print("保存模型:",saver.save(sess,'.\stock.model'))

step+=1

def prediction():

pred,_=lstm(1) #预测时只输入[1,time_step,input_size]的测试数据

saver=tf.train.Saver(tf.global_variables())

with tf.Session() as sess:

#参数恢复

module_file = tf.train.latest_checkpoint('./')

saver.restore(sess, module_file)

#取训练集最后一行为测试样本。shape=[1,time_step,input_size]

prev_seq=train_x[-31]

predict=[]

#得到之后100个预测结果

for i in range(100):

next_seq=sess.run(pred,feed_dict={X:[prev_seq]})

predict.append(next_seq[-1])

#每次得到最后一个时间步的预测结果,与之前的数据加在一起,形成新的测试样本

prev_seq=np.vstack((prev_seq[1:],next_seq[-1]))

#以折线图表示结果

plt.figure()

plt.plot(list(range(len(normalize_data))), normalize_data, color='b')

plt.plot(list(range(len(normalize_data), len(normalize_data) + len(predict))), predict, color='r')

plt.show()

with tf.variable_scope('train'):

train_lstm()

with tf.variable_scope('train',reuse=True):

prediction()

基于python的机器学习实现日元币对人民币汇率预测的更多相关文章

  1. 基于Python的机器学习实战:KNN

    1.KNN原理: 存在一个样本数据集合,也称作训练样本集,并且样本集中每个数据都存在标签,即我们知道样本集中每一个数据与所属分类的对应关系.输入没有标签的新数据后,将新数据的每个特征与样本集中数据对应 ...

  2. 基于python的机器学习开发环境安装(最简单的初步开发环境)

    一.安装Python 1.下载安装python3.6 https://www.python.org/getit/ 2.配置环境变量(2个) 略...... 二.安装Python算法库 安装顺序:Num ...

  3. 基于Python的机器学习实战:Apriori

    目录: 1.关联分析 2. Apriori 原理 3. 使用 Apriori 算法来发现频繁集 4.从频繁集中挖掘关联规则 5. 总结 1.关联分析  返回目录 关联分析是一种在大规模数据集中寻找有趣 ...

  4. 基于Python的机器学习实战:AadBoost

    目录: 1. Boosting方法的简介 2. AdaBoost算法 3.基于单层决策树构建弱分类器 4.完整的AdaBoost的算法实现 5.总结 1. Boosting方法的简介 返回目录 Boo ...

  5. 搭建基于python +opencv+Beautifulsoup+Neurolab机器学习平台

    搭建基于python +opencv+Beautifulsoup+Neurolab机器学习平台 By 子敬叔叔 最近在学习麦好的<机器学习实践指南案例应用解析第二版>,在安装学习环境的时候 ...

  6. 初识TPOT:一个基于Python的自动化机器学习开发工具

    1. TPOT介绍 一般来讲,创建一个机器学习模型需要经历以下几步: 数据预处理 特征工程 模型选择 超参数调整 模型保存 本文介绍一个基于遗传算法的快速模型选择及调参的方法,TPOT:一种基于Pyt ...

  7. 【Machine Learning】决策树案例:基于python的商品购买能力预测系统

    决策树在商品购买能力预测案例中的算法实现 作者:白宁超 2016年12月24日22:05:42 摘要:随着机器学习和深度学习的热潮,各种图书层出不穷.然而多数是基础理论知识介绍,缺乏实现的深入理解.本 ...

  8. 从Theano到Lasagne:基于Python的深度学习的框架和库

    从Theano到Lasagne:基于Python的深度学习的框架和库 摘要:最近,深度神经网络以“Deep Dreams”形式在网站中如雨后春笋般出现,或是像谷歌研究原创论文中描述的那样:Incept ...

  9. 基于Python使用SVM识别简单的字符验证码的完整代码开源分享

    关键字:Python,SVM,字符验证码,机器学习,验证码识别 1   概述 基于Python使用SVM识别简单的验证字符串的完整代码开源分享. 因为目前有了更厉害的新技术来解决这类问题了,但是本文作 ...

随机推荐

  1. node版本查看管理工具

    1.nvm : 有点坑爹,安装完后,发现node not found ,最后卸载了,重装node 2.bower :(前端)包管理器(选用) //安装方法 npm install bower -g / ...

  2. 更改Apache默认起始(索引)页面:DirectoryIndex

    Apache默认索引页面是index.html,修改成其他文件需要修改httpd.conf文件: # # DirectoryIndex: sets the file that Apache will ...

  3. day1-课堂代码

    # # a = 1 # b = a # print(b) # # c = a + 1 # print(c) # # def add(x,y): # return x+y # # d = add(3,5 ...

  4. oracle11g dataguard 备库数据同步的检查方法

    概述: 一.环境      主库:       ip地址:192.168.122.203       oracle根目录:/data/db/oracle       SID:qyq       数据文 ...

  5. Android 在ScrollView中嵌入ViewPage后ViewPage不能很好的工作的问题解决

    解决办法:重写ScrollView,如下代码所示: public class MyScrollView extends ScrollView{ private GestureDetector mGes ...

  6. 【hdu4405】AeroplaneChess

    题目大意:问从0到n所花费时间平均时间.每次有投骰子,投到几就走几步.原题还有坐飞机 #include<iostream> #include<cmath> #include&l ...

  7. day08(补)

    今日学习内容 1.文件重写方法 2.函数基本知识 文件处理: 打开文件 读/写文件 关闭文件 文件指针移动,只有t模式下的read(n),n代表的字符个数其余都是以字节为单位 f.seek有两个参数( ...

  8. 采用PowerDesigner 设计数据库

    PowerDesigner设计数据库的教程网上都有,最好的是我一位同学写的,地址: 点击这里 我的大致流程如下: 首先要以管理员的身份打开PowerDesigner,如果没这么做,将导致后面无法创建S ...

  9. 将jar文件加到Maven的local repository中

    对于Maven项目来说,日常使用的多数第三方java库文件都可以从Maven的Central Repository中自动下载,但是如果我们需要的jar文件不在Central Repository中,那 ...

  10. 20155308 《网络攻防》 Exp2 后门原理与实践

    20155308 <网络攻防> Exp2 后门原理与实践 学习内容:使用nc实现win,mac,Linux间的后门连接 :meterpraeter的应用 :MSF POST 模块的应用 学 ...