‘’’
版本:python3.5+tensorflow1.15
功能:运用tensorflow预测y=0.1x+0.3,输出每一次训练的参数
‘’’
import tensorflow as tf
import numpy as np
x_data = np.random.rand(100).astype(np.float32)
y_data = x_data*0.1+0.3
####### create tensorflow structure start
Weights = tf.Variable(tf.random_uniform([1], -1.0, 1.0))
biases = tf.Variable(tf.zeros([1]))
y = Weights*x_data+biases
loss = tf.reduce_mean(tf.square(y-y_data))
optimizer = tf.train.GradientDescentOptimizer(0.5)
train = optimizer.minimize(loss)
init = tf.global_variables_initializer()
####### create tensorflow structure end
sess=tf.Session()
sess.run(init) #Very important
for step in range(201):
sess.run(train)
if step % 20 == 0:
print(step, sess.run(Weights), sess.run(biases))
输出结果:
0 [-0.02865237] [0.49359453]
20 [0.04218084] [0.32985395]
40 [0.08147815] [0.30956346]
60 [0.09406669] [0.30306357]
80 [0.09809934] [0.3009814]
100 [0.09939113] [0.3003144]
120 [0.09980498] [0.3001007]
140 [0.09993753] [0.30003226]
160 [0.09997998] [0.30001035]
180 [0.09999362] [0.30000332]
200 [0.09999795] [0.30000108]