写一个lstm股票预测代码
时间: 2023-10-27 10:07:19 浏览: 89
LSTM预测股价代码
好的,以下是一个简单的LSTM股票预测代码:
首先,我们需要准备一些必要的库和数据集:
```python
import pandas as pd
import numpy as np
from keras.models import Sequential
from keras.layers import LSTM, Dense
from sklearn.preprocessing import MinMaxScaler
# 读取股票数据集
df = pd.read_csv('stock_prices.csv')
# 选择我们要预测的股票价格列
data = df.filter(['Close'])
# 将数据集转换为numpy数组
dataset = data.values
# 将数据集划分为训练集和测试集
train_size = int(len(dataset) * 0.8)
train_data = dataset[0:train_size, :]
test_data = dataset[train_size:, :]
# 对数据进行缩放
scaler = MinMaxScaler(feature_range=(0, 1))
train_data = scaler.fit_transform(train_data)
test_data = scaler.transform(test_data)
```
接下来,我们需要定义一些辅助函数:
```python
# 将数据集划分为X和Y
def create_dataset(dataset, time_step=1):
X, Y = [], []
for i in range(len(dataset) - time_step - 1):
a = dataset[i:(i + time_step), 0]
X.append(a)
Y.append(dataset[i + time_step, 0])
return np.array(X), np.array(Y)
# 定义时间步长
time_step = 100
# 创建训练集和测试集
X_train, Y_train = create_dataset(train_data, time_step)
X_test, Y_test = create_dataset(test_data, time_step)
# 将训练集和测试集重塑为LSTM的输入格式
X_train = np.reshape(X_train, (X_train.shape[0], X_train.shape[1], 1))
X_test = np.reshape(X_test, (X_test.shape[0], X_test.shape[1], 1))
```
现在,我们可以定义我们的LSTM模型:
```python
# 定义模型
model = Sequential()
model.add(LSTM(50, return_sequences=True, input_shape=(time_step, 1)))
model.add(LSTM(50, return_sequences=True))
model.add(LSTM(50))
model.add(Dense(1))
# 编译模型
model.compile(loss='mean_squared_error', optimizer='adam')
# 训练模型
model.fit(X_train, Y_train, validation_data=(X_test, Y_test), epochs=100, batch_size=64, verbose=1)
```
最后,我们使用训练好的模型进行预测:
```python
# 使用模型进行预测
train_predict = model.predict(X_train)
test_predict = model.predict(X_test)
# 对预测结果进行反缩放
train_predict = scaler.inverse_transform(train_predict)
Y_train = scaler.inverse_transform([Y_train])
test_predict = scaler.inverse_transform(test_predict)
Y_test = scaler.inverse_transform([Y_test])
# 计算模型的RMSE
train_rmse = np.sqrt(np.mean((train_predict - Y_train) ** 2))
test_rmse = np.sqrt(np.mean((test_predict - Y_test) ** 2))
print('Train RMSE:', train_rmse)
print('Test RMSE:', test_rmse)
```
完整代码如下所示:
```python
import pandas as pd
import numpy as np
from keras.models import Sequential
from keras.layers import LSTM, Dense
from sklearn.preprocessing import MinMaxScaler
# 读取股票数据集
df = pd.read_csv('stock_prices.csv')
# 选择我们要预测的股票价格列
data = df.filter(['Close'])
# 将数据集转换为numpy数组
dataset = data.values
# 将数据集划分为训练集和测试集
train_size = int(len(dataset) * 0.8)
train_data = dataset[0:train_size, :]
test_data = dataset[train_size:, :]
# 对数据进行缩放
scaler = MinMaxScaler(feature_range=(0, 1))
train_data = scaler.fit_transform(train_data)
test_data = scaler.transform(test_data)
# 将数据集划分为X和Y
def create_dataset(dataset, time_step=1):
X, Y = [], []
for i in range(len(dataset) - time_step - 1):
a = dataset[i:(i + time_step), 0]
X.append(a)
Y.append(dataset[i + time_step, 0])
return np.array(X), np.array(Y)
# 定义时间步长
time_step = 100
# 创建训练集和测试集
X_train, Y_train = create_dataset(train_data, time_step)
X_test, Y_test = create_dataset(test_data, time_step)
# 将训练集和测试集重塑为LSTM的输入格式
X_train = np.reshape(X_train, (X_train.shape[0], X_train.shape[1], 1))
X_test = np.reshape(X_test, (X_test.shape[0], X_test.shape[1], 1))
# 定义模型
model = Sequential()
model.add(LSTM(50, return_sequences=True, input_shape=(time_step, 1)))
model.add(LSTM(50, return_sequences=True))
model.add(LSTM(50))
model.add(Dense(1))
# 编译模型
model.compile(loss='mean_squared_error', optimizer='adam')
# 训练模型
model.fit(X_train, Y_train, validation_data=(X_test, Y_test), epochs=100, batch_size=64, verbose=1)
# 使用模型进行预测
train_predict = model.predict(X_train)
test_predict = model.predict(X_test)
# 对预测结果进行反缩放
train_predict = scaler.inverse_transform(train_predict)
Y_train = scaler.inverse_transform([Y_train])
test_predict = scaler.inverse_transform(test_predict)
Y_test = scaler.inverse_transform([Y_test])
# 计算模型的RMSE
train_rmse = np.sqrt(np.mean((train_predict - Y_train) ** 2))
test_rmse = np.sqrt(np.mean((test_predict - Y_test) ** 2))
print('Train RMSE:', train_rmse)
print('Test RMSE:', test_rmse)
```
阅读全文