基于tensorflow的一元线性回归详细讲解
官方代码: https://github.com/MorvanZhou/Tensorflow-Tutorial/blob/master/tutorial-contents/301_simple_regression.py
根据例子,代码详解请查看代码后面的注释 训练之前自己的数据 训练之后的曲线 “”” Know more, visit my Python tutorial page: https://morvanzhou.github.io/tutorials/ My Youtube Channel: https://www.youtube.com/user/MorvanZhou Dependencies: tensorflow: 1.1.0 matplotlib numpy “”” import tensorflow as tf import matplotlib.pyplot as plt import numpy as np
tf.set_random_seed(1) #设置图形级随机seed没看太懂
np.random.seed(1)
# fake data
x = np.linspace(-1, 1, 100)[:, np.newaxis] # shape (100, 1)
noise = np.random.normal(0, 0.1, size=x.shape)
y = np.power(x, 2) + noise # shape (100, 1) + some noise
# plot data
plt.scatter(x, y)
plt.show()
#出现占位符,下面运行时必须要有sess.run(ys,feed={'xs':input,'ys':output})
tf_x = tf.placeholder(tf.float32, x.shape) # input x
tf_y = tf.placeholder(tf.float32, y.shape) # input y
# neural network layers
#相当于添加一个层,即初学的add_layer()函数
l1 = tf.layers.dense(tf_x, 10, tf.nn.relu) # hidden layer
output = tf.layers.dense(l1, 1) # output layer
#ValueError:如果predictions与labels的形状不匹配,或者形状weights是无效,亦或,如果labels或是predictions为None,则会引发此类异常.
loss = tf.losses.mean_squared_error(tf_y, output) # compute cost
optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.5) #优化器或者叫传播误差
train_op = optimizer.minimize(loss)
sess = tf.Session() # control training and others
sess.run(tf.global_variables_initializer()) # initialize var in graph
plt.ion() # something about plotting 打开交互式界面
for step in range(100):
# train and net output
_, l, pred = sess.run([train_op, loss, output], {tf_x: x, tf_y: y})
if step % 5 == 0:
# plot and show learning process
# cla() # Clear axis即清除当前图形中的当前活动轴。其他轴不受影响。
# clf() # Clear figure清除所有轴,但是窗口打开,这样它可以被重复使用。
# close() # Close a figure window
plt.cla() #清除活动轴的信息
plt.scatter(x, y) #绘制散点图 plt.scatter(x, y,s)
plt.plot(x, pred, 'r-', lw=5) #显示连接线
plt.text(0.5, 0, 'Loss=%.4f' % l, fontdict={'size': 20, 'color': 'red'}) #在plot上显示文字
plt.pause(0.1) #暂停0.1s
# 在plt.show()之前一定不要忘了加plt.ioff(),如果不加,界面会一闪而过,并不会停留
plt.ioff()
plt.show()