RNN.LSTM异步预测股价

import pandas as pd
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
%matplotlib inline
from sklearn.preprocessing import MinMaxScaler
import time

data = pd.read_csv('data_stocks.csv')
data.drop('DATE', axis=1, inplace=True)
data_train = data.iloc[:int(data.shape[0] * 0.8), :]
data_test = data.iloc[int(data.shape[0] * 0.8):, :]
print("data_train.shape, data_test.shape")
print(data_train.shape, data_test.shape)

scaler = MinMaxScaler(feature_range=(-1, 1))
scaler.fit(data_train)

# data_train和data_test为np.ndarray类型
data_train = scaler.transform(data_train)
data_test = scaler.transform(data_test)

output_dim = 1
batch_size = 256
epochs = 10
seq_len = 5
hidden_size = 128

X_train = np.array([data_train[i : i + seq_len, 0] 
                    for i in range(data_train.shape[0] - seq_len)])[:, :, np.newaxis]
y_train = np.array([data_train[i + seq_len, 0] 
                    for i in range(data_train.shape[0] - seq_len)])[:, np.newaxis]

X_test = np.array([data_test[i : i + seq_len, 0] 
                   for i in range(data_test.shape[0] - seq_len)])[:, :, np.newaxis]
y_test = np.array([data_test[i + seq_len, 0] 
                   for i in range(data_test.shape[0] - seq_len)])

print(X_train.shape, y_train.shape, X_test.shape, y_test.shape)

tf.reset_default_graph()

x = tf.placeholder(tf.float32, [None, 5, 1], name='x-input')
y_ = tf.placeholder(tf.float32, [None, 1], name='y-input')

lstm_cell = tf.nn.rnn_cell.BasicLSTMCell(num_units=128)
lstm_model = tf.cell = tf.nn.rnn_cell.MultiRNNCell([lstm_cell])
outputs, _ = tf.nn.dynamic_rnn(lstm_model, x, dtype=tf.float32)
# 下标为-1表示取出列表的最后一行数据值
output = outputs[:, -1, :]
y = tf.contrib.layers.fully_connected(output, 1, activation_fn=None)
loss = tf.losses.mean_squared_error(labels=y_, predictions=y)
train_op = tf.train.AdamOptimizer(0.01).minimize(loss)

writer = tf.summary.FileWriter("/path/to/lstm/log", tf.get_default_graph())
writer.close()


with tf.Session() as sess :
    # tf.reset_default_graph()
    tf.global_variables_initializer().run()
    j = 0
    for i in range(10000) :
        j = j + 1
        if(batch_size * j > 30000) :
            j = 0
        _loss, _ = sess.run([loss, train_op], 
                    feed_dict={x: X_train[j*batch_size:(j+1)*batch_size], 
                    y_: y_train[j*batch_size:(j+1)*batch_size]})
        if i % 100 == 0 :
            _prediction = sess.run(y, feed_dict={x : X_test})
            plt.plot(y_test, label='test')
            plt.plot(_prediction, label='pred')
            plt.legend()
            plt.show()


    



训练数据留下邮箱我发给你

你可能感兴趣的:(tensorflow学习笔记,深度学习)