#!/usr/bin/env python
# -*- coding: utf-8 -*-
#source: "https://github.com/xiaohu2015/tensorflow/
"""LSTM 模型:用于时间序列预测/回归"""
import sys
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
def batch_iterate(num_batchs, batch_size, num_steps):
"""根据 sin cos 函数生成用于 mini batch 的样本"""
start = 0
# 有 num_batchs 个 batch;
for i in range(num_batchs):
# xo: 生成的序列变量:维度[batch_size, num_steps];
xo = np.arange(start, start+batch_size*num_steps).reshape(
[batch_size, num_steps])/(10.0*np.pi)
# 生成序列值 x;
x = np.sin(xo)
# 生成序列值 y;
y = np.cos(xo)
# 更新步数;
start += num_steps
# 返回当前 batch 的样本;
# yield 是一个类似 return 的关键字,迭代一次遇到 yield 时就返回 yield 后面(右边)
的值;
yield (x[:, :, np.newaxis], y[:, :, np.newaxis], xo)
class LstmRegression(object):
"""lstm 类:时间序列预测"""
def __init__(self, in_size, out_size, num_steps=20, cell_size=20, batch_size=50,
num_lstm_layers=2, keep_prob=0.5, is_training=True):
"""
-----------变量说明-----------------
:参数 in_size : int, 输入维度;
:参数 out_size : int, 输出维度;
:参数 num_steps : int, 时间步数;
:参数 cell_size : int, lstm cell 数量;
:参数 batch_size : int, mini bacth 数量;
:参数 num_lstm_layers: int, lstm layers 数量;
:参数 keep_prob : float, 设置神经元被选中的概率;
:参数 is_training : bool, True:training model/False:test model;