import os
os.environ['CUDA_VISIBLE_DEVICES']='-1'
import numpy as np
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Activation,LSTM,Dense
from sklearn.preprocessing import MinMaxScaler
from tensorflow.keras import optimizers,layers,losses,activations
import matplotlib.pyplot as plt
time_steps = seq_length = 7
data_dim = 5
# Open,High,Low,Close,Volume
xy = np.loadtxt("./data-02-stock_daily.csv",delimiter=",")
xy = xy[::-1] # 数据倒序,数据的顺序是从前到现在,用以前预测现在
scaler = MinMaxScaler(feature_range=(0,1))
xy = scaler.fit_transform(xy)
# x包含所有特征,y只取最后一列收盘价
x = xy
y = xy[:,-1:]
dataX = []
dataY = []
# 分组 7天的数据为一组x,对应第八天的收盘价 y
for i in range(0,len(y)-seq_length):
_x = x[i:i+seq_length]
_y = y[i+seq_length]
print(_x, "->", _y)
dataX.append(_x)
dataY.append(_y)
dataX = np.array(dataX)
dataY = np.array(dataY)
from sklearn.model_selection import train_test_split
trainX, testX, trainY, testY = train_test_split(dataX,dataY,train_size=0.7, shuffle=False)
# 创建模型
model = Sequential()
# 5->10->1
# 多对一LSTM模型保证最后一层的lstm的return_sequences=False,即可
model.add(LSTM(10,input_shape=(seq_length,data_dim),return_sequences=True))
model.add(LSTM(8,return_sequences=False))
# 股票预测本质是带有时间性质的回归问题,所以激活函数使用线性激活,损失使用mse
model.add(Dense(1,activation="linear"))
model.compile(optimizer=optimizers.Adam(),loss=losses.mean_squared_error)
model.summary()
print("train_data_size=",trainX.shape,trainY.shape)
model.fit(trainX,trainY,epochs=200)
# 预测值
test_predict = model.predict(testX)
# 预测的收盘价与真实收盘价的绘图对比
plt.plot(testY)
plt.plot(test_predict)
plt.show()
tensorflow2.x股票预测
最新推荐文章于 2024-10-19 15:55:38 发布
1427

被折叠的 条评论
为什么被折叠?



