[신경망] RNN을 이용한 주식가격 예측 알고리즘 코드
2020. 5. 7. 09:53ㆍ노트/Python : 프로그래밍
데이터
코드
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
def MinMaxScaler(data):
denom=np.max(data,0)-np.min(data,0)
nume=data-np.min(data,0)
return nume/denom
#정규화
path = "C:\\Users\\student\\Desktop\\DY\\★ 데이터\\105. deep-learning-dataset\\"
xy=np.loadtxt(path+"data-02-stock_daily.csv", delimiter=",", skiprows=0+1+1)
xy=xy[::-1] #역순으로 저장
# skip multiple rows 여러 줄 skip하는 방법: +로 int 를 더해준다
seqLength=7 #window size
dataDim=5 #시가,종가,...거래량 5개 컬럼
hiddenDim=10
outputDim=1
lr=0.01
iterations=500
trainSize=int(len(xy)*0.7)
trainSet=xy[0:trainSize] #0:499
testSet=xy[trainSize-seqLength:]#493:499->500
trainSet=MinMaxScaler(trainSet)
testSet=MinMaxScaler(testSet)
def buildDataSet(timeSeries, seqLength):
xdata=[]
ydata=[]
for i in range(0, len(timeSeries)-seqLength):
tx=timeSeries[i:i+seqLength,:]
ty=timeSeries[i+seqLength,[-1]]
xdata.append(tx)
ydata.append(ty)
return np.array(xdata), np.array(ydata)
trainX, trainY=buildDataSet(trainSet, seqLength)
testX, testY=buildDataSet(testSet, seqLength)
학습
loss= tf.reduce_mean(tf.square(yhat-y))
opt=tf.train.AdamOptimizer(lr)
train=opt.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)))
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
for i in range(iterations):
_,cv=sess.run([train, loss], feed_dict={
x:trainX, y:trainY
})
print("step:{} loss:{}".format(i, cv))
testPredict=sess.run(yhat, feed_dict={x:testX})
rmsev=sess.run(rmse, feed_dict={
targets:testY,
predictions:testPredict
})
print("rmse value: {}".format(rmsev))
테스트
trainX.shape #(505,7,5)
#505개 샘플, 7(일주일), 5(5개 컬럼)
testX.shape #(220, 7, 5)
x=tf.placeholder(tf.float32, [None, seqLength, dataDim])
y=tf.placeholder(tf.float32, [None, 1])
cell=tf.contrib.rnn.BasicLSTMCell(
num_units=hiddenDim,
state_is_tuple=True,
activation=tf.tanh
#([1,2],[3,4])
#is_Tuple=True => 튜플 = ([1,2],[3,4])
# False => 텐서 = [1,2,3,4]
)
outputs, _states=tf.nn.dynamic_rnn(cell, x, dtype=tf.float32)
yhat=tf.contrib.layers.fully_connected(outputs[:,-1], outputDim, activation_fn=None)
%matplotlib notebook
plt.plot(testY)
plt.plot(testPredict)
plt.show()
유사 상세 포스팅 참고
'노트 > Python : 프로그래밍' 카테고리의 다른 글
[자연어처리] 케라스로 단어사전 만들기 (0) | 2020.05.08 |
---|---|
[신경망] LSTM을 이용한 "나비야" 작곡하기 코드 (0) | 2020.05.08 |
[신경망] RNN을 이용한 단어 번역 알고리즘 코드 (0) | 2020.05.01 |
[신경망] RNN을 이용한 다음 단어 완성 알고리즘 코드 (0) | 2020.05.01 |
[텐서플로우] MNIST 데이터를 이용한 RNN 모델 (0) | 2020.04.30 |