bp神经网络tensorflow代码 股价
时间: 2023-07-08 13:48:19 浏览: 89
以下是使用 TensorFlow 实现 BP 神经网络预测股价的一个示例代码:
```python
import tensorflow as tf
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# 读取股票数据
stock_data = pd.read_csv('stock_data.csv')
# 股票数据归一化
stock_data = (stock_data - stock_data.min()) / (stock_data.max() - stock_data.min())
# 将数据划分为训练集和测试集
train_data = stock_data[:2000]
test_data = stock_data[2000:]
# 定义神经网络的输入和输出
x_train = train_data.iloc[:, :-1].values
y_train = train_data.iloc[:, -1:].values
x_test = test_data.iloc[:, :-1].values
y_test = test_data.iloc[:, -1:].values
# 定义神经网络的参数
input_size = 4
hidden_size = 10
output_size = 1
learning_rate = 0.01
epochs = 1000
# 定义神经网络的输入和输出
x = tf.placeholder(tf.float32, [None, input_size])
y = tf.placeholder(tf.float32, [None, output_size])
# 定义神经网络的隐藏层和输出层
w1 = tf.Variable(tf.random_normal([input_size, hidden_size]))
b1 = tf.Variable(tf.random_normal([hidden_size]))
w2 = tf.Variable(tf.random_normal([hidden_size, output_size]))
b2 = tf.Variable(tf.random_normal([output_size]))
hidden_output = tf.nn.relu(tf.matmul(x, w1) + b1)
model_output = tf.matmul(hidden_output, w2) + b2
# 定义误差函数和优化器
loss = tf.reduce_mean(tf.square(y - model_output))
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss)
# 训练神经网络
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
for i in range(epochs):
sess.run(optimizer, feed_dict={x: x_train, y: y_train})
if i % 100 == 0:
print('Epoch:', i, 'Loss:', sess.run(loss, feed_dict={x: x_train, y: y_train}))
# 在测试集上进行预测
predicted_stock_price = sess.run(model_output, feed_dict={x: x_test})
# 将预测结果和真实结果可视化
plt.plot(y_test, color='red', label='Real Stock Price')
plt.plot(predicted_stock_price, color='blue', label='Predicted Stock Price')
plt.title('Stock Price Prediction')
plt.xlabel('Time')
plt.ylabel('Stock Price')
plt.legend()
plt.show()
```
需要注意的是,这只是一个简单的示例代码,实际使用中还需要进行更多的优化和调整。
阅读全文