利用tensorflow搭建神经网络
获取数据
def get_data(code='000001.SZ',start='20180101',end='20191201',window_len=12):
ts_pro = ts.pro_api('xx')
df = ts_pro.daily(ts_code=code, start_date=start, end_date=end)
df = df.reindex(index=df.index[::-1])
# 转换为二维数组
arr = df['close'].values
#归一化处理
arr=np.reshape(arr,newshape=(-1,1))
mm=MinMaxScaler()
arr=mm.fit_transform(arr)
arr=np.reshape(arr,newshape=-1)
# 列表[]
X = []
Label = []
for i in range(len(arr) - window_len - 1):
X.append(arr[i:i + window_len])
Label.append(arr[i + window_len])
X=np.array(X)
Label=np.array(Label)
train_len = int(len(X) / 3) * 2
# 划分测试和训练数据集
X_train = X[:train_len]
Label_train = Label[:train_len]
X_test = X[train_len:]
X_Label = X[train_len:]
return X_train, Label_train, X_test, X_Label
搭建循环神经网络
indows_len=12
hidden_units=64
model_layers=[
tf.keras.layers.Reshape((windows_len,1),input_shape=(windows_len, )),
tf.keras.layers.SimpleRNN(units=hidden_units,return_sequences=False),
tf.keras.layers.Dense(units=hidden_units, activation='sigmoid'),
tf.keras.layers.Dense(1, activation='sigmoid'),
]
model=tf.keras.models.Sequential(model_layers)
# print(model.summary())
循环神经网络的预测和评估
def plot_loss(loss):
fig=plt.figure()
ax=fig.add_subplot(111)
ax.plot(range(len(loss)),loss)
plt.grid(True)
plt.show()
def plot_result(prediction,true):
fig=plt.figure()
ax=fig.add_subplot(111)
ax.plot(range(len(prediction)),prediction)
ax.plot(range(len(true)),true)
plt.legend(['prediction','true'])
plt.show()
if __name__ == '__main__':
X_train, Label_train, X_test, X_Label = get_data()
model.compile(optimizer='adam',loss='mean_squared_error')
history=model.fit(X_train, Label_train,epochs=100)
plot_loss(history.history['loss'])
prediction=model.predict(X_test)
plot_result(prediction,Lable_test)