Code:
import tensorflow as tf import numpy as np #Use numpy to generate 100 random points #sample x_data = np.random.rand(100) y_data = x_data * 0.1 + 0.2 #Construct a linear model b = tf.Variable(0.3) k = tf.Variable(1.0) y = k * x_data + b #Secondary cost function #The square of the error takes the average loss = tf.reduce_mean(tf.square(y_data-y)) #define a gradient descent optimizer for training optimizaer = tf.train.GradientDescentOptimizer(0.2) #define a minimization cost function train = optimizaer.minimize(loss) #Initialize variables init = tf.global_variables_initializer() with tf.Session() as sess: sess.run(init) for step in range(201): sess.run (train) #Print the value of k and b every 20 times if step%20 == 0: print(step, sess.run([k, b]))
operation result:
0 [0.84287709, 0.061396986] 20 [0.49860233, -0.032348074] 40 [0.35844025, 0.049353316] 60 [0.26756388, 0.1023258] 80 [0.20864277, 0.13667135] 100 [0.1704403, 0.15893984] 120 [0.14567113, 0.17337798] 140 [0.12961161, 0.18273918] 160 [0.11919918, 0.18880866] 180 [0.1124481, 0.19274391] 200 [0.10807092, 0.19529541]