课程链接:莫烦python
注意:np的linspace创造的数组为float64类型,而tf的Variable为float32类型,matmul需要两个相同类型的参数输入,因此可以使用tf.cast转换类型,也可以使用程序里的方法。
import numpy as np
import matplotlib.pyplot as plt
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
def add_layer(inputs, in_size, out_size, activation_function=None):#activation_function=None激活函数
WeightS = tf.Variable(tf.random_normal([in_size, out_size]))
biases =tf.Variable(tf.zeros([1, out_size]) + 0.1)
Wx_plus_b = tf.matmul(inputs, WeightS) +biases
if activation_function is None:
outputs = Wx_plus_b
else:
outputs = activation_function(Wx_plus_b)
return outputs
x_data = np.linspace(-1,1,300)[:,np.newaxis].astype(np.float32)#linspace产生-1到1之间的300个数的等差数列
noise = np.random.normal(0,0.05,x_data.shape)#均值为0 方差为0.05
y_data = np.square(x_data) - 0.5 + noise
xs = tf.placeholder(tf.float32, [None, 1])#none代表没有行数要求
ys = tf.placeholder(tf.float32, [None, 1])
l1 = add_layer(x_data, 1, 10, activation_function=tf.nn.relu)#隐藏层
prediction = add_layer(l1, 10, 1, activation_function=None)#输出层
loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys-prediction), reduction_indices=[1]))
#reduction_indices表示结果压缩的方向 ~[1]按行求和,~[0]按列求和
train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)
init = tf.initialize_all_variables()
sess = tf.Session()
sess.run(init)
#画图
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.scatter(x_data, y_data)
plt.show()
for i in range(1000):
sess.run(train_step, feed_dict={xs:x_data, ys:y_data})
if i%50==0:
print(sess.run(loss, feed_dict={xs:x_data, ys:y_data}))
#画图
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.scatter(x_data, y_data)
plt.ion()#连续画图 动态
plt.show()
for i in range(1000):
sess.run(train_step, feed_dict={xs:x_data, ys:y_data})
if i%20==0:
#to see the step improvement
#print(sess.run(loss, feed_dict={xs:x_data, ys:y_data}))
try:
ax.lines.remove(lines[0])
except Exception:
pass
prediction_value = sess.run(prediction, feed_dict={xs:x_data})
lines = ax.plot(x_data, prediction_value, 'r-', lw=5)
plt.pause(0.1)
拟合的图像
代码几乎都有注释~~ 很容易看懂