TensorFlow笔记--求解二次函数最小值对应的值

TensorFlow笔记--求解二次函数最小值对应的值

  • 问题:
  • 代码段:
  • 运行结果如下:

最近学习在 TensorFlow,看了两行代码后觉得TensorFlow真是一个不错的工具。然后,作为工科男我就想着解决一些有趣的问题;解决什么好呢?想来想去还是决定对我们熟悉的二次方程求解。我想大家对如何解二次方程早就成竹在胸,下面看一下TensorFlow如何做的吧。

问题:

我们先来看一下需要求解的方程:y = (x+1)^2
然后给出我们的要求:求解在 y 最小时 x 的值。
那么如何求解呢?OK,不卖关子啦,直接上代码喽!

代码段:

# coding:utf-8
# 设函数 y = (x+1)^2, 令 x 初始值为5
# 反向传播就是求最优 x,即求最小y值对应的x值
import tensorflow as tf

# 定义待优化参数 x 初值为 5
x = tf.Variable(tf.constant(5, dtype=tf.float32))
# y = (x+1)^2
y = tf.square(x+1)
# 定义反向传播方法
train_step = tf.train.GradientDescentOptimizer(0.2).minimize(y)

# 生成会话,训练40轮
with tf.Session() as sess:
    init_op = tf.global_variables_initializer()
    sess.run(init_op)
    for i in range(40):
        sess.run(train_step)
        x_val = sess.run(x)
        y_val = sess.run(y)
        print("After %s steps: x is %f,  y is %f."%(i, x_val, y_val))

运行结果如下:

After 0 steps: x is 2.600000, y is 12.959999.
After 1 steps: x is 1.160000, y is 4.665599.
After 2 steps: x is 0.296000, y is 1.679616.
After 3 steps: x is -0.222400, y is 0.604662.
After 4 steps: x is -0.533440, y is 0.217678.
After 5 steps: x is -0.720064, y is 0.078364.
After 6 steps: x is -0.832038, y is 0.028211.
After 7 steps: x is -0.899223, y is 0.010156.
After 8 steps: x is -0.939534, y is 0.003656.
After 9 steps: x is -0.963720, y is 0.001316.
After 10 steps: x is -0.978232, y is 0.000474.
After 11 steps: x is -0.986939, y is 0.000171.
After 12 steps: x is -0.992164, y is 0.000061.
After 13 steps: x is -0.995298, y is 0.000022.
After 14 steps: x is -0.997179, y is 0.000008.
After 15 steps: x is -0.998307, y is 0.000003.
After 16 steps: x is -0.998984, y is 0.000001.
After 17 steps: x is -0.999391, y is 0.000000.
After 18 steps: x is -0.999634, y is 0.000000.
After 19 steps: x is -0.999781, y is 0.000000.
After 20 steps: x is -0.999868, y is 0.000000.
After 21 steps: x is -0.999921, y is 0.000000.
After 22 steps: x is -0.999953, y is 0.000000.
After 23 steps: x is -0.999972, y is 0.000000.
After 24 steps: x is -0.999983, y is 0.000000.
After 25 steps: x is -0.999990, y is 0.000000.
After 26 steps: x is -0.999994, y is 0.000000.
After 27 steps: x is -0.999996, y is 0.000000.
After 28 steps: x is -0.999998, y is 0.000000.
After 29 steps: x is -0.999999, y is 0.000000.
After 30 steps: x is -0.999999, y is 0.000000.
After 31 steps: x is -1.000000, y is 0.000000.
After 32 steps: x is -1.000000, y is 0.000000.
After 33 steps: x is -1.000000, y is 0.000000.
After 34 steps: x is -1.000000, y is 0.000000.
After 35 steps: x is -1.000000, y is 0.000000.
After 36 steps: x is -1.000000, y is 0.000000.
After 37 steps: x is -1.000000, y is 0.000000.
After 38 steps: x is -1.000000, y is 0.000000.
After 39 steps: x is -1.000000, y is 0.000000.

就这样利用 TensorFlow 刷了一题二次函数,是不是很开心呢?
或许看了这些你觉得TensorFlow被大材小用了,但是作为TensorFlow的入门例子已经不简单喽。后面将会持续更新TensorFlow的使用,若你喜欢请添加关注哦!同时也欢迎您的留言,让我们一起交流TensorFlow学习心得!

你可能感兴趣的:(Python,TensorFlow,ML)