forked from hunkim/DeepLearningZeroToAll
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lab-12-6-rnn_softmax_stock_prediction.py
83 lines (67 loc) · 2.43 KB
/
lab-12-6-rnn_softmax_stock_prediction.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
tf.set_random_seed(777) # reproducibility
def MinMaxScaler(data):
num_row = np.shape(data)[0]
num_col = np.shape(data)[1]
array = np.zeros((num_row, num_col))
for i in range(num_col):
input = data[:, i]
array[:, i] = (input - np.min(input)) / (np.max(input) - np.min(input))
return array
timesteps = seq_length = 7
data_dim = 5
output_dim = 3
# Open,High,Low,Close,Volume
xy = np.loadtxt('data-02-stock_daily.csv', delimiter=',')
xy = xy[::-1] # reverse order (chronically ordered)
xy = MinMaxScaler(xy)
x = xy
y = xy[:, [-1]] # Close as label
dataX = []
dataY = []
for i in range(0, len(y) - seq_length):
_x = x[i:i + seq_length]
_y = y[i + seq_length] # Next close price as target
print(_x, "->", _y)
dataX.append(_x)
dataY.append(_y)
# split to train and testing
train_size = int(len(dataY) * 0.7)
test_size = len(dataY) - train_size
trainX, testX = np.array(dataX[0:train_size]), np.array(
dataX[train_size:len(dataX)])
trainY, testY = np.array(dataY[0:train_size]), np.array(
dataY[train_size:len(dataY)])
# input place holders
X = tf.placeholder(tf.float32, [None, seq_length, data_dim])
Y = tf.placeholder(tf.float32, [None, 1])
cell = tf.contrib.rnn.BasicLSTMCell(num_units=output_dim, state_is_tuple=True)
cell = tf.contrib.rnn.MultiRNNCell([cell] * 2, state_is_tuple=True)
outputs, _states = tf.nn.dynamic_rnn(cell, X, dtype=tf.float32)
last_output = outputs[:, -1] # We use the last cell's output
# Softmax layer (rnn_hidden_size -> num_classes)
softmax_w = tf.get_variable("softmax_w", [output_dim, 1])
softmax_b = tf.get_variable("softmax_b", [1])
Y_pred = tf.matmul(last_output, softmax_w) + softmax_b
# cost/loss
loss = tf.reduce_sum(tf.square(Y_pred - Y)) # sum of the squares
# optimizer
optimizer = tf.train.GradientDescentOptimizer(0.001)
train = optimizer.minimize(loss)
# RMSE
targets = tf.placeholder(tf.float32, [None, 1])
predictions = tf.placeholder(tf.float32, [None, 1])
rmse = tf.sqrt(tf.reduce_mean(tf.square(targets - predictions)))
sess = tf.Session()
sess.run(tf.global_variables_initializer())
for i in range(1000):
_, l = sess.run([train, loss], feed_dict={X: trainX, Y: trainY})
print(i, l)
testPredict = sess.run(Y_pred, feed_dict={X: testX})
print("RMSE", sess.run(rmse, feed_dict={
targets: testY, predictions: testPredict}))
plt.plot(testY)
plt.plot(testPredict)
plt.show()