'''
Created on 2017年5月21日 @author: weizhen
'''
# 以下程序为预测离散化之后的sin函数
import numpy as np
import tensorflow as tf
from tensorflow.contrib import rnn # 加载matplotlib工具包,使用该工具包可以对预测的sin函数曲线进行绘图
import matplotlib as mpl
from tensorflow.contrib.learn.python.learn.estimators.estimator import SKCompat
mpl.use('Agg')
from matplotlib import pyplot as plt
learn = tf.contrib.learn
HIDDEN_SIZE = 30 # Lstm中隐藏节点的个数
NUM_LAYERS = 2 # LSTM的层数
TIMESTEPS = 10 # 循环神经网络的截断长度
TRAINING_STEPS = 10000 # 训练轮数
BATCH_SIZE = 32 # batch大小 TRAINING_EXAMPLES = 10000 # 训练数据个数
TESTING_EXAMPLES = 1000 # 测试数据个数
SAMPLE_GAP = 0.01 # 采样间隔
# 定义生成正弦数据的函数
def generate_data(seq):
X = []
Y = []
# 序列的第i项和后面的TIMESTEPS-1项合在一起作为输入;第i+TIMESTEPS项作为输出
# 即用sin函数前面的TIMESTPES个点的信息,预测第i+TIMESTEPS个点的函数值
for i in range(len(seq) - TIMESTEPS - 1):
X.append([seq[i:i + TIMESTEPS]])
Y.append([seq[i + TIMESTEPS]])
return np.array(X, dtype=np.float32), np.array(Y, dtype=np.float32) def LstmCell():
lstm_cell = rnn.BasicLSTMCell(HIDDEN_SIZE,state_is_tuple=True)
return lstm_cell # 定义lstm模型
def lstm_model(X, y):
cell = rnn.MultiRNNCell([LstmCell() for _ in range(NUM_LAYERS)])
output, _ = tf.nn.dynamic_rnn(cell, X, dtype=tf.float32)
output = tf.reshape(output, [-1, HIDDEN_SIZE])
# 通过无激活函数的全连接层计算线性回归,并将数据压缩成一维数组结构
predictions = tf.contrib.layers.fully_connected(output, 1, None) # 将predictions和labels调整统一的shape
labels = tf.reshape(y, [-1])
predictions = tf.reshape(predictions, [-1]) loss = tf.losses.mean_squared_error(predictions, labels)
train_op = tf.contrib.layers.optimize_loss(loss, tf.contrib.framework.get_global_step(),
optimizer="Adagrad",
learning_rate=0.1)
return predictions, loss, train_op # 进行训练
# 封装之前定义的lstm
regressor = SKCompat(learn.Estimator(model_fn=lstm_model, model_dir="Models/model_2"))
# 生成数据
test_start = TRAINING_EXAMPLES * SAMPLE_GAP
test_end = (TRAINING_EXAMPLES + TESTING_EXAMPLES) * SAMPLE_GAP
train_X, train_y = generate_data(np.sin(np.linspace(0, test_start, TRAINING_EXAMPLES, dtype=np.float32)))
test_X, test_y = generate_data(np.sin(np.linspace(test_start, test_end, TESTING_EXAMPLES, dtype=np.float32)))
# 拟合数据
regressor.fit(train_X, train_y, batch_size=BATCH_SIZE, steps=TRAINING_STEPS)
# 计算预测值
predicted = [[pred] for pred in regressor.predict(test_X)] # 计算MSE
rmse = np.sqrt(((predicted - test_y) ** 2).mean(axis=0))
print("Mean Square Error is:%f" % rmse[0]) plot_predicted, = plt.plot(predicted, label='predicted')
plot_test, = plt.plot(test_y, label='real_sin')
plt.legend([plot_predicted, plot_test],['predicted', 'real_sin'])
plt.show()

预测的结果如下所示

2017-05-21 17:43:49.057377: W c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE instructions, but these are available on your machine and could speed up CPU computations.
2017-05-21 17:43:49.057871: W c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE2 instructions, but these are available on your machine and could speed up CPU computations.
2017-05-21 17:43:49.058284: W c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE3 instructions, but these are available on your machine and could speed up CPU computations.
2017-05-21 17:43:49.058626: W c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.1 instructions, but these are available on your machine and could speed up CPU computations.
2017-05-21 17:43:49.058981: W c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.2 instructions, but these are available on your machine and could speed up CPU computations.
2017-05-21 17:43:49.059897: W c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use AVX instructions, but these are available on your machine and could speed up CPU computations.
2017-05-21 17:43:49.060207: W c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use AVX2 instructions, but these are available on your machine and could speed up CPU computations.
2017-05-21 17:43:49.060843: W c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use FMA instructions, but these are available on your machine and could speed up CPU computations.
Mean Square Error is:0.001686

86、使用Tensorflow实现,LSTM的时间序列预测,预测正弦函数的更多相关文章

  1. 使用tensorflow的lstm网络进行时间序列预测

    https://blog.csdn.net/flying_sfeng/article/details/78852816 版权声明:本文为博主原创文章,未经博主允许不得转载. https://blog. ...

  2. (数据科学学习手札40)tensorflow实现LSTM时间序列预测

    一.简介 上一篇中我们较为详细地铺垫了关于RNN及其变种LSTM的一些基本知识,也提到了LSTM在时间序列预测上优越的性能,本篇就将对如何利用tensorflow,在实际时间序列预测任务中搭建模型来完 ...

  3. 盘它!!一步到位,Tensorflow 2的实战 !!LSTM下的股票预测(附详尽代码及数据集)

    关键词:tensorflow2.LSTM.时间序列.股票预测 Tensorflow 2.0发布已经有一段时间了,各种新API的确简单易用,除了官方文档以外能够找到的学习资料也很多,但是大都没有给出实战 ...

  4. 用 LSTM 做时间序列预测的一个小例子(转自简书)

    问题:航班乘客预测 数据:1949 到 1960 一共 12 年,每年 12 个月的数据,一共 144 个数据,单位是 1000 下载地址 目标:预测国际航班未来 1 个月的乘客数 import nu ...

  5. 使用TensorFlow的递归神经网络(LSTM)进行序列预测

    本篇文章介绍使用TensorFlow的递归神经网络(LSTM)进行序列预测.作者在网上找到的使用LSTM模型的案例都是解决自然语言处理的问题,而没有一个是来预测连续值的. 所以呢,这里是基于历史观察数 ...

  6. 【原创】基于SVM作短期时间序列的预测

    [面试思路拓展] 对时间序列进行预测的方法有很多, 但如果只有几周的数据,而没有很多线性的趋势.各种实际的背景该如何去预测时间序列? 或许可以尝试下利用SVM去预测时间序列,那么如何提取预测的特征呢? ...

  7. 学习Tensorflow的LSTM的RNN例子

    学习Tensorflow的LSTM的RNN例子 基于TensorFlow一次简单的RNN实现 极客学院-递归神经网络 如何使用TensorFlow构建.训练和改进循环神经网络

  8. 时间序列挖掘-预测算法-三次指数平滑法(Holt-Winters)——三次指数平滑算法可以很好的保存时间序列数据的趋势和季节性信息

    from:http://www.cnblogs.com/kemaswill/archive/2013/04/01/2993583.html 在时间序列中,我们需要基于该时间序列当前已有的数据来预测其在 ...

  9. 时间序列预测——Tensorflow.Keras.LSTM

    1.测试数据下载 https://datamarket.com/data/set/22w6/portland-oregon-average-monthly-bus-ridership-100-janu ...

随机推荐

  1. Linux 下查看用户组信息

    1.id 通过id 可以直接查看到当前登陆用户的uid, group id , group name 等等.. 2.groups

  2. static_cast关键字 dynamic_cast关键字

    前言 说起C++中的继承.多态.虚函数等概念,可能很多同学都有所了解,但是要说真正熟知的同学可能就不是很多了.最近在编程过程中了解到C++类型的层次转换(这就涉及到了多态和继承的相关概率),通常C语言 ...

  3. Springboot集成Mybatis+PageHelper

    1.Springboot项目引入mysql和mybatis的依赖: <dependency> <groupId>org.mybatis.spring.boot</grou ...

  4. MVC5使用SignalR进行双向通信 (1)

    @a604572782 2015-08-10 09:01 字数 2133 阅读 1245 MVC5使用SignalR进行双向通信 (1) 配置SignalR 在NuGet中通过 install-pac ...

  5. C中进制, 原码, 反码与补码的简单用法

    /** * 二进制 binary 如: 1010 * 八进制 octal 如: 070 * 十六进制 hexadecimal 如: 0x7f * * 1Byte = 8bits * 1WORD = 2 ...

  6. Angular的一些常用命令

    Angular的一些常用命令 cmd中创建项目: ng new taskmgr -si --style=scss //先不安装依赖,si 为skip install material需要scss样式的 ...

  7. 【报错】解决logstash tracking_column not found in dataset. {:tracking_column=>"updated_time"}问题

    今天用logstash同步数据库记录到elasticsearch时候出现错误,错误信息如下: [2019-10-12T23:51:00,529][WARN ][logstash.inputs.jdbc ...

  8. 分支结构case 语句语法

  9. windows下基于(QPC)实现的微秒级延时

    1.为什么会写windows下微秒级延时 在上一篇 实现memcpy()函数及过程总结 中测试memcpy的效率中,测试时间的拷贝效率在微秒级别,需要使用微秒级时间间隔计数. windows下提供Qu ...

  10. sql 摘抄

    练习题和参考解 (1)查询“001”课程比“002”课程成绩低的所有学生的学号.001学科成绩.002学科成绩                 1 SELECT 2 s1.StudentNo, 3 s ...