TensorFlow入门教程(三):线性回归,曲线拟合
本节通过一个简单的线性回归来理解神经网络是如何工作的。
定义了一个两层网络,采用梯度下降法,通过对权值的训练,对曲线进行拟合
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
# 定义变量
x_data = np.linspace(-0.5, 0.5, 200)[:, np.newaxis] # 从-0.5到0.5均匀分布生成200个点,形成200行一列矩阵
noise = np.random.normal(0, 0.02, x_data.shape) # 产生随机噪声
y_data = np.square(x_data) + noise # y = x^2 + noise
x = tf.placeholder(tf.float32, [None, 1]) # 定义占位符
y = tf.placeholder(tf.float32, [None, 1])
# 定义输入层
weight_1 = tf.Variable(tf.random_normal([1, 10])) # 权重矩阵为1*10,即1个输入,10个中间层
biase_1 = tf.Variable(tf.zeros([1, 10])) # 偏置值
wx_plus_1 = tf.matmul(x, weight_1) + biase_1 # 输入数据与权值相乘
L1 = tf.nn.tanh(wx_plus_1) # **函数
# 定义输出层
weight_2 = tf.Variable(tf.random_normal([10, 1])) # 10个中间层,1个输出层
biase_2 = tf.Variable(tf.zeros([1, 1]))
wx_plus_2 = tf.matmul(L1, weight_2) + biase_2
prediction = tf.nn.tanh(wx_plus_2)
loss = tf.reduce_mean(tf.square(y - prediction)) # 求每一个数据误差的平方,再求均值
train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss) # 梯度下降法优化器,学习率为0.1,使得误差最小
with tf.Session() as sees:
sees.run(tf.global_variables_initializer()) # 变量初始化
for i in range(2000):
sees.run(train_step, feed_dict={x: x_data, y: y_data}) # 进行2000次训练
prediction_value = sees.run(prediction, feed_dict={x: x_data}) # 预测
plt.figure() # 画图
plt.scatter(x_data, y_data) # 画输入点
plt.plot(x_data, prediction_value, 'r-', lw=5) # 画预测曲线
plt.show()
运行结果: