TensorFlow - 梯度下降优化



梯度下降优化被认为是数据科学中一个重要的概念。

考虑以下所示步骤来了解梯度下降优化 −

步骤 1

通过我们用来定义梯度下降优化的变量 X 和 Y 包含必要模块和声明。

import tensorflow as tf

x = tf.Variable(2, name = 'x', dtype = tf.float32)
log_x = tf.log(x)
log_x_squared = tf.square(log_x)

optimizer = tf.train.GradientDescentOptimizer(0.5)
train = optimizer.minimize(log_x_squared)

步骤 2

初始化必要变量,并调用优化器用相应函数进行定义和调用。

init = tf.initialize_all_variables()

def optimize():
   with tf.Session() as session:
      session.run(init)
      print("starting at", "x:", session.run(x), "log(x)^2:", session.run(log_x_squared))
      
      for step in range(10):
         session.run(train)
         print("step", step, "x:", session.run(x), "log(x)^2:", session.run(log_x_squared))
optimize()

上面这行代码生成的结果如以下屏幕截图所示 −

Initialize Variables

我们可以看到,必要时段和迭代次数按输出所示计算出来。

广告
© . All rights reserved.