import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
# https://blog.csdn.net/juyin2015/article/details/78679707?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.nonecase&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.nonecase
# 使用numpy生成200个随机点,从-0.5到0.5生成200个点
x_data = np.linspace(-0.5, 0.5, 200)[:, np.newaxis]#转成二维数据
noise = np.random.normal(0, 0.02, x_data.shape)#生成随机噪声
y_data = np.square(x_data) + noise
# 定义placeholder,占位
x = tf.placeholder(tf.float32, [None, 1])#行不确定,只有一列
y = tf.placeholder(tf.float32, [None, 1])
# 定义神经网络中间层
Weights_L1 = tf.Variable(tf.random_normal([1, 10]))#1行10列
biases_L1 = tf.Variable(tf.zeros([1, 10]))
Wx_plus_b_L1 = tf.matmul(x, Weights_L1) + biases_L1
L1 = tf.nn.tanh(Wx_plus_b_L1)
# 定义神经网络输出层
Weights_L2 = tf.Variable(tf.random_normal([10, 1]))
biases_L2 = tf.Variable(tf.zeros([1, 1]))
Wx_plus_b_L2 = tf.matmul(L1, Weights_L2) + biases_L2
prediction = tf.nn.tanh(Wx_plus_b_L2)
#损失函数
loss = tf.reduce_mean(tf.square(y - prediction))
# 使用梯度下降法训练
train_step = tf.train.GradientDescentOptimizer(0.3).minimize(loss)
with tf.Session() as sess:
# 变量初始化
sess.run(tf.global_variables_initializer())
for _ in range(2001):
sess.run(train_step, feed_dict={x: x_data, y: y_data})
print(Weights_L1,biases_L1)
print(Weights_L2, biases_L2)
# 预测
# 使用numpy生成200个随机点,从-0.5到0.5生成200个点
x_predata = np.linspace(0, 1, 200)[:, np.newaxis] # 转成二维数据
prediction_value = sess.run(prediction, feed_dict={x: x_predata})
# 画图
plt.figure()
plt.scatter(x_data, y_data)#样本点
plt.plot(x_predata, prediction_value, 'r-', lw=5)#红色,实线,线宽5
plt.show()
BP神经网络拟合曲线、预测
最新推荐文章于 2024-11-12 22:26:47 发布
本文详细介绍了如何使用BP神经网络进行曲线拟合和预测。通过实例展示了BP网络在解决非线性问题上的能力,探讨了训练过程、误差反向传播以及参数调整对结果的影响。

1583

被折叠的 条评论
为什么被折叠?



