用python搭建一个cnn-lstm神经网络用于预测股价的具体代码
时间: 2024-01-26 19:01:52 浏览: 83
以下是一个简单的用 Python 搭建 CNN-LSTM 神经网络预测股价的代码。
```
import numpy as np
import pandas as pd
from keras.models import Sequential
from keras.layers import Dense, Dropout, Conv1D, LSTM, MaxPooling1D
from sklearn.preprocessing import MinMaxScaler
# 读取股价数据
data = pd.read_csv('stock_price.csv', date_parser=True)
data.head()
# 将日期设置为索引
data = data.set_index('date')
# 标准化股价数据
scaler = MinMaxScaler()
data = scaler.fit_transform(data)
# 定义 CNN-LSTM 模型
model = Sequential()
model.add(Conv1D(filters=64, kernel_size=3, activation='relu', input_shape=(n_steps, n_features)))
model.add(Conv1D(filters=64, kernel_size=3, activation='relu'))
model.add(Dropout(0.5))
model.add(MaxPooling1D(pool_size=2))
model.add(LSTM(50))
model.add(Dense(1))
model.compile(optimizer='adam', loss='mse')
# 定义训练集和测试集
train_size = int(len(data) * 0.8)
train, test = data[0:train_size,:], data[train_size:len(data),:]
# 划分输入和输出
def split_sequences(sequence, n_steps):
X, y = [], []
for i in range(len(sequence)):
end_ix = i + n_steps
if end_ix > len(sequence)-1:
break
seq_x, seq_y = sequence[i:end_ix, :], sequence[end_ix, :]
X.append(seq_x)
y.append(seq_y)
return np.array(X), np.array(y)
# 设置步长
n_steps = 3
# 划分训练集和测试集的输入和输出
train_x, train_y = split_sequences(train, n_steps)
test_x, test_y = split_sequences(test, n_steps)
# 训练模型
model.fit(train_x, train_y, epochs=200, batch_size=16, validation_data=(test_x, test_y), verbose=2, shuffle=False)
# 预测股价
yhat = model.predict(test_x)
# 反归一化数据
yhat = scaler.inverse_transform(yhat)
test_y = scaler.inverse_transform(test_y)
# 计算均方根误差(RMSE)
rmse = np.sqrt(np.mean((yhat - test_y)**2))
print('Test RMSE: %.3f' % rmse)
```
需要注意的是,此代码只是一个简单的示例,真实的股价预测可能需要更复杂的模型和数据处理。此外,这个代码需要加入股价数据,这里没有提供,你需要找到一个股价数据并进行整合。
阅读全文