代码如下:
#coding:utf-8 import tensorflow as tf import numpy as np x = tf.Variable(tf.random_normal([1], stddev=0.35)) y = tf.constant([6.25]) predict_y = tf.pow(x, 2) loss = tf.pow(y - predict_y, 2) train = tf.train.GradientDescentOptimizer(0.01).minimize(loss) init_op = tf.initialize_all_variables() with tf.Session() as sess: sess.run(init_op) for step in range(100): sess.run(train) print("Step %2d, %f", step, x.eval())
输出如下:
Step 0, -0.472492 Step 1, -0.586396 Step 2, -0.724929 Step 3, -0.890923 Step 4, -1.085367 Step 5, -1.305565 Step 6, -1.542943 Step 7, -1.781749 Step 8, -2.000931 Step 9, -2.180716 Step 10, -2.311077 Step 11, -2.395101 Step 12, -2.444295 Step 13, -2.471224 Step 14, -2.485364 Step 15, -2.492618 Step 16, -2.496293 Step 17, -2.498142 Step 18, -2.499070 Step 19, -2.499535 Step 20, -2.499767 Step 21, -2.499884 Step 22, -2.499942 Step 23, -2.499971 Step 24, -2.499985 Step 25, -2.499993 Step 26, -2.499996 Step 27, -2.499998 Step 28, -2.499999 Step 29, -2.500000 Step 30, -2.500000 Step 31, -2.500000 Step 32, -2.500000 Step 33, -2.500000 Step 34, -2.500000 Step 35, -2.500000 Step 36, -2.500000 Step 37, -2.500000 Step 38, -2.500000 Step 39, -2.500000 Step 40, -2.500000 Step 41, -2.500000 Step 42, -2.500000 Step 43, -2.500000 Step 44, -2.500000 Step 45, -2.500000 Step 46, -2.500000 Step 47, -2.500000 Step 48, -2.500000 Step 49, -2.500000 Step 50, -2.500000 Step 51, -2.500000 Step 52, -2.500000 Step 53, -2.500000 Step 54, -2.500000 Step 55, -2.500000 Step 56, -2.500000 Step 57, -2.500000 Step 58, -2.500000 Step 59, -2.500000 Step 60, -2.500000 Step 61, -2.500000 Step 62, -2.500000 Step 63, -2.500000 Step 64, -2.500000 Step 65, -2.500000 Step 66, -2.500000 Step 67, -2.500000 Step 68, -2.500000 Step 69, -2.500000 Step 70, -2.500000 Step 71, -2.500000 Step 72, -2.500000 Step 73, -2.500000 Step 74, -2.500000 Step 75, -2.500000 Step 76, -2.500000 Step 77, -2.500000 Step 78, -2.500000 Step 79, -2.500000 Step 80, -2.500000 Step 81, -2.500000 Step 82, -2.500000 Step 83, -2.500000 Step 84, -2.500000 Step 85, -2.500000 Step 86, -2.500000 Step 87, -2.500000 Step 88, -2.500000 Step 89, -2.500000 Step 90, -2.500000 Step 91, -2.500000 Step 92, -2.500000 Step 93, -2.500000 Step 94, -2.500000 Step 95, -2.500000 Step 96, -2.500000 Step 97, -2.500000 Step 98, -2.500000 Step 99, -2.500000