LSTM神经网络和普通神经网络的使用

注意,numpy需要低于1.20.1

pip install -U numpy==1.19.2
#!/usr/bin/env python
# coding: utf-8

# In[1]:
# 版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
# 本文链接:https://blog.csdn.net/tMb8Z9Vdm66wH68VX1/article/details/90423649

import pandas as pd
import numpy as np
#matplotlib inline
import tensorflow as tf
import matplotlib.pyplot as plt

from sklearn.preprocessing import MinMaxScaler

from sklearn.metrics import r2_score

from tensorflow.keras.models import Sequential

from tensorflow.keras.layers import Dense

from tensorflow.keras.callbacks import EarlyStopping

from tensorflow.keras.optimizers import Adam

from tensorflow.keras.layers import LSTM

pd.set_option('display.max_columns', None)
#显示所有行
pd.set_option('display.max_rows', None)



# ————————————————
# 版权声明:本文为CSDN博主「数据派THU」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
# 原文链接:https://blog.csdn.net/tMb8Z9Vdm66wH68VX1/article/details/90423649

# In[2]:


df = pd.read_csv("测试股票数据.csv")
print(df.head())


# In[3]:


df.drop(['Open', 'High', 'Low', 'Close', 'Volume'], axis=1, inplace=True)

df['Date'] = pd.to_datetime(df['Date'])

#df = df.set_index(['Date'], drop=True)
df = df.set_index(['Date'], drop=True)
df.head(10)


# In[4]:


plt.figure(figsize=(10, 6))

df['Adj Close'].plot();


# In[5]:


split_date = pd.Timestamp('2019-01-01')

df =  df['Adj Close']

train = df.loc[:split_date]

test = df.loc[split_date:]

plt.figure(figsize=(10, 6))

ax = train.plot()

test.plot(ax=ax)

plt.legend(['train', 'test']);


# In[6]:


train = np.array(train).reshape(-1,1)
test = np.array(test).reshape(-1,1)


# In[7]:


scaler = MinMaxScaler(feature_range=(-1, 1))

train_sc = scaler.fit_transform(train)

test_sc = scaler.transform(test)


# In[8]:


train


# In[9]:


X_train = train_sc[:-1]

y_train = train_sc[1:]



X_test = test_sc[:-1]

y_test = test_sc[1:]


# In[10]:


nn_model = Sequential()

nn_model.add(Dense(12, input_dim=1, activation='relu'))

nn_model.add(Dense(1))

nn_model.compile(loss='mean_squared_error', optimizer='adam')

early_stop = EarlyStopping(monitor='loss', patience=2, verbose=1)

history = nn_model.fit(X_train, y_train, epochs=100, batch_size=1, verbose=1, callbacks=[early_stop], shuffle=False)


# In[11]:


y_pred_test_nn = nn_model.predict(X_test)

y_train_pred_nn = nn_model.predict(X_train)

print("The R2 score on the Train set is:\t{:0.3f}".format(r2_score(y_train, y_train_pred_nn)))

print("The R2 score on the Test set is:\t{:0.3f}".format(r2_score(y_test, y_pred_test_nn)))


# In[12]:


plt.figure(figsize=(10, 6))

plt.plot(y_test, label='True')

plt.plot(y_pred_test_nn, label='NN')

plt.title("NN's Prediction")

plt.xlabel('Observation')

plt.ylabel('Adj Close Scaled')

plt.legend()

plt.show();


# In[13]:


#lmse
X_train_lmse = tf.convert_to_tensor(train_sc[:-1])
# y_train = tf.convert_to_tensor(train_sc[1:])
X_train_lmse = X_train.reshape(X_train.shape[0],1, X_train.shape[1])
X_test_lmse = X_test.reshape(X_test.shape[0],1, X_test.shape[1])

#X_train_lmse = tf.convert_to_tensor( X_train.reshape(X_train.shape[0],1, X_train.shape[1]))


lstm_model = Sequential()

lstm_model.add(LSTM(7, input_shape=(1, X_train_lmse.shape[1]), activation='relu', kernel_initializer='lecun_uniform', return_sequences=False))

lstm_model.add(Dense(1))

lstm_model.compile(loss='mean_squared_error', optimizer='adam')

early_stop = EarlyStopping(monitor='loss', patience=2, verbose=1)

history_lstm_model = lstm_model.fit(X_train_lmse, y_train, epochs=100, batch_size=1, verbose=1, shuffle=False, callbacks=[early_stop])


# In[14]:


y_pred_test_lstm = lstm_model.predict(X_test_lmse)

y_train_pred_lstm = lstm_model.predict(X_train_lmse)

print("The R2 score on the Train set is:\t{:0.3f}".format(r2_score(y_train, y_train_pred_lstm)))

print("The R2 score on the Test set is:\t{:0.3f}".format(r2_score(y_test, y_pred_test_lstm)))


# In[15]:


nn_test_mse = nn_model.evaluate(X_test, y_test, batch_size=1)

lstm_test_mse = lstm_model.evaluate(X_test_lmse, y_test, batch_size=1)

print('NN: %f'%nn_test_mse)

print('LSTM: %f'%lstm_test_mse)


# In[16]:


plt.figure(figsize=(10, 6))

plt.plot(y_test, label='True')

plt.plot(y_pred_test_lstm, label='LSTM')

plt.title("LSTM's Prediction")

plt.xlabel('Observation')

plt.ylabel('Adj Close scaled')

plt.legend()

plt.show()


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小蜗笔记

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值