tf.train.get_global_step() 方法返回的是的 global_step作为name的tensor, 如
tensorflow中不少方法是存在global_step 参数的,比如optimizer.minimize(loss, global_step= tf.train.get_global_step() ) 这个参数可以传入tf.train.get_global_step()方法,也可以传入普通的Variable,即name任意。每次打开tf.Session()并运行该方法时,系统会自动为传入的global_step参数+1。
在这里你可能会问,既然能传入普通Variable,为什么还要有global_step 作为name的tensor? 个人认为这是为了使代码清晰吧,毕竟global_step是比较常用的变量,如果和普通Variable混在一起就降低了代码的可读性。
以下给出代码示例:
x = tf.placeholder(tf.float32, shape=[None], name='x')
y = tf.placeholder(tf.float32, shape=[None], name='y')
w = tf.Variable(tf.truncated_normal(shape=[2], mean=0, stddev=0.1))
# gl_v = tf.Variable(0, trainable=False)
gl = tf.train.get_global_step()
learning_rate = tf.train.exponential_decay(0.1, gl, 10, 2, staircase=False)
loss = tf.square(w*x+y)
train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss, global_step=gl)
with tf.Session() as sess:
sess.run(tf.initialize_all_variables())
for i in range(10):
print ('gl before run:',sess.run(gl))
sess.run(train_step, feed_dict={x:np.array([10,10]),
y:np.array([10,10])})
print (sess.run(learning_rate))
print ('gl after run:',sess.run(gl))
print('\n')
输出:
gl before run: 0
0.10717734
gl after run: 1
gl before run: 1
0.11486983
gl after run: 2
gl before run: 2
0.123114444
gl after run: 3
gl before run: 3
0.1319508
gl after run: 4
gl before run: 4
0.14142136
gl after run: 5
gl before run: 5
0.15157166
gl after run: 6
gl before run: 6
0.16245048
gl after run: 7
gl before run: 7
0.17411011
gl after run: 8
gl before run: 8
0.1866066
gl after run: 9
gl before run: 9
0.2
gl after run: 10
若把以上的变量gl替换成gl_v,输出完全一致,但不推荐这样使用。