bp神经网络tensorflow代码 股价
时间: 2023-07-08 12:38:15 浏览: 197
BP神经网络预测股票,bp神经网络预测股票价格python代码,matlab
5星 · 资源好评率100%
以下是使用 TensorFlow 实现 BP 神经网络预测股价的示例代码:
```python
import tensorflow as tf
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# 读取数据
data = pd.read_csv('stock_price.csv')
# 数据预处理
data = data[::-1] # 倒序
data = data.reset_index(drop=True) # 重设索引
data['Date'] = pd.to_datetime(data['Date']) # 转换为时间格式
data = data.set_index('Date') # 将日期列作为索引
data = data.drop(['Open', 'High', 'Low', 'Adj Close', 'Volume'], axis=1) # 只保留收盘价列
data = data.dropna() # 删除缺失值
# 划分训练集和测试集
train_size = int(len(data) * 0.8)
train_data = data.iloc[:train_size]
test_data = data.iloc[train_size:]
# 归一化
train_min = np.min(train_data)
train_max = np.max(train_data)
train_data = (train_data - train_min) / (train_max - train_min)
test_data = (test_data - train_min) / (train_max - train_min)
# 构建数据集
def create_dataset(data, window_size):
X, y = [], []
for i in range(len(data) - window_size):
X.append(data.iloc[i:i+window_size])
y.append(data.iloc[i+window_size])
return np.array(X), np.array(y)
window_size = 30
train_X, train_y = create_dataset(train_data, window_size)
test_X, test_y = create_dataset(test_data, window_size)
# 构建模型
model = tf.keras.Sequential([
tf.keras.layers.Dense(128, input_shape=(window_size,), activation='relu'),
tf.keras.layers.Dense(64, activation='relu'),
tf.keras.layers.Dense(1)
])
model.compile(optimizer='adam', loss='mse')
# 训练模型
model.fit(train_X, train_y, epochs=100)
# 预测
train_predict = model.predict(train_X)
test_predict = model.predict(test_X)
# 反归一化
train_predict = train_predict * (train_max - train_min) + train_min
train_y = train_y * (train_max - train_min) + train_min
test_predict = test_predict * (train_max - train_min) + train_min
test_y = test_y * (train_max - train_min) + train_min
# 可视化
plt.plot(train_y, label='train')
plt.plot(train_predict, label='train_predict')
plt.plot(test_y, label='test')
plt.plot(test_predict, label='test_predict')
plt.legend()
plt.show()
```
此代码将股价的收盘价作为输入,采用 BP 神经网络进行预测。输入数据经过归一化后,使用窗口大小为 30 的滑动窗口构建数据集,模型采用 3 层全连接层,输出预测值。训练过程中使用均方误差作为损失函数,使用 Adam 优化器进行优化。最后将预测结果反归一化后进行可视化。
阅读全文