写一段lstm股票预测代码
时间: 2023-08-06 14:04:42 浏览: 101
LSTM预测股价代码
好的,以下是一个简单的LSTM股票预测代码示例:
```python
import pandas as pd
import numpy as np
from sklearn.preprocessing import MinMaxScaler
from keras.models import Sequential
from keras.layers import Dense, Dropout, LSTM
# 加载数据
df = pd.read_csv('stock_data.csv')
# 数据预处理
scaler = MinMaxScaler(feature_range=(0, 1))
scaled_data = scaler.fit_transform(df['Close'].values.reshape(-1, 1))
# 创建训练数据集
prediction_days = 60
x_train = []
y_train = []
for i in range(prediction_days, len(scaled_data)):
x_train.append(scaled_data[i-prediction_days:i, 0])
y_train.append(scaled_data[i, 0])
x_train, y_train = np.array(x_train), np.array(y_train)
x_train = np.reshape(x_train, (x_train.shape[0], x_train.shape[1], 1))
# 创建 LSTM 模型
model = Sequential()
model.add(LSTM(units=50, return_sequences=True, input_shape=(x_train.shape[1], 1)))
model.add(Dropout(0.2))
model.add(LSTM(units=50, return_sequences=True))
model.add(Dropout(0.2))
model.add(LSTM(units=50))
model.add(Dropout(0.2))
model.add(Dense(units=1))
model.compile(optimizer='adam', loss='mean_squared_error')
model.fit(x_train, y_train, epochs=25, batch_size=32)
# 创建测试数据集
test_data = scaled_data[-prediction_days:]
x_test = []
for i in range(prediction_days, len(test_data)):
x_test.append(test_data[i-prediction_days:i, 0])
x_test = np.array(x_test)
x_test = np.reshape(x_test, (x_test.shape[0], x_test.shape[1], 1))
# 进行预测
predicted_price = model.predict(x_test)
predicted_price = scaler.inverse_transform(predicted_price)
# 输出预测结果
print(predicted_price)
```
以上代码可以根据提供的股票数据进行股票价格的预测。其中,我们使用 LSTM 神经网络来训练和预测模型,使用 MinMaxScaler 工具将数据进行归一化处理,以便 LSTM 模型更好地处理数据。最后,我们使用训练好的模型对未来的股票价格进行预测,并将预测结果输出。
阅读全文