import tensorflow as tf import numpy as np x_data = np.random.rand(100) y_data = x_data*0.6 + 0.8 # 定义变量 k = tf.Variable(tf.zeros([1, 1])) b = tf.Variable(tf.zeros([1, 1])) y = k * x_data + b # 定义二次代价函数 loss = tf.reduce_mean(tf.square(y - y_data)) # 定义梯度下降优化器 optimizer = tf.train.GradientDescentOptimizer(0.2) # 最小化训练 train_step = optimizer.minimize(loss) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) for i in range(201): sess.run(train_step) if i % 10 == 0: print("step: "+str(i)) print(sess.run([k, b]))
运行结果图如下:
文章来源: https://blog.csdn.net/any1234567890/article/details/92635591