bp神经网络回归模型tensorflow代码
时间: 2023-09-18 17:05:44 浏览: 50
以下是一个简单的基于 TensorFlow 的 BP 神经网络回归模型代码:
```python
import tensorflow as tf
import numpy as np
# 定义超参数
learning_rate = 0.01
training_epochs = 1000
display_step = 50
# 定义训练数据
train_X = np.array([[0.2, 0.3], [0.4, 0.5], [0.6, 0.7], [0.8, 0.9], [1.0, 1.1]])
train_Y = np.array([0.5, 0.7, 0.9, 1.1, 1.3])
# 定义输入和输出的占位符
X = tf.placeholder(tf.float32, [None, 2])
Y = tf.placeholder(tf.float32, [None])
# 定义模型权重和偏置
W = tf.Variable(tf.zeros([2, 1]))
b = tf.Variable(tf.zeros([1]))
# 构建模型
pred = tf.matmul(X, W) + b
# 定义损失函数(均方误差)
cost = tf.reduce_mean(tf.square(pred - Y))
# 定义优化器
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)
# 初始化所有的变量
init = tf.global_variables_initializer()
# 训练模型
with tf.Session() as sess:
sess.run(init)
for epoch in range(training_epochs):
_, c = sess.run([optimizer, cost], feed_dict={X: train_X, Y: train_Y})
if (epoch + 1) % display_step == 0:
print("Epoch:", '%04d' % (epoch + 1), "cost=", "{:.9f}".format(c))
print("Optimization Finished!")
training_cost = sess.run(cost, feed_dict={X: train_X, Y: train_Y})
print("Training cost=", training_cost, "W=", sess.run(W), "b=", sess.run(b))
# 预测
test_X = np.array([[1.2, 1.3], [1.4, 1.5]])
test_Y = sess.run(pred, feed_dict={X: test_X})
print("Predictions:", test_Y)
```
这个模型使用了一个简单的梯度下降优化器,通过迭代训练数据来最小化均方误差损失函数。在训练完成后,我们可以使用训练好的模型进行预测。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)