#coding:utf-8 import tensorflow as tf import numpy as np #使用numpy 生成100个随机点 x_data = np.random.rand(100) y_data = x_data*0.1 + 0.2 #构造一个线性模型,k 和 b是我们要求的两个值,利用100个点 #进行不断迭代 然后求出最佳的k和b b = tf.Variable(0.) k = tf.Variable(0.) y = k*x_data + b #二次代价函数 loss = tf.reduce_mean(tf.square(y_data-y)) #定义一个训练的优化器:梯度下降法 optimizer = tf.train.GradientDescentOptimizer(0.2) #学习率为0.2 #最小化代价函数 #使用前面定义好的优化器来减小loss值 train = optimizer.minimize(loss) init = tf.global_variables_initializer() with tf.Session() as sess: sess.run(init) for step in range(300): sess.run(train) if step%20 ==0: print(step,sess.run([k,b]))
结果
(0, [0.046660472, 0.097824201]) (20, [0.097689927, 0.20109874]) (40, [0.098617099, 0.20065789]) (60, [0.0991721, 0.20039386]) (80, [0.099504374, 0.20023578]) (100, [0.09970329, 0.20014116]) (120, [0.09982238, 0.20008451]) (140, [0.099893652, 0.20005059]) (160, [0.099936351, 0.20003028]) (180, [0.099961899, 0.20001812]) (200, [0.099977195, 0.20001085]) (220, [0.099986345, 0.2000065]) (240, [0.099991821, 0.20000389]) (260, [0.099995099, 0.20000234]) (280, [0.099997051, 0.2000014])
可以看到求得的k和b非常接近于我们定义的k值和b值。