Variable 变量、Placeholder 传入值

1. Variable 变量

在 Tensorflow 中,定义了某字符串是变量,它才是变量,这一点是与 Python 所不同的。

定义语法: state = tf.Variable()

import tensorflow as tf

state = tf.Variable(0, name='counter')

# 定义常量 one
one = tf.constant(1)

# 定义加法步骤 (注: 此步并没有直接计算)
new_value = tf.add(state, one)

# 将 State 更新成 new_value
update = tf.assign(state, new_value)

如果你在 Tensorflow 中设定了变量,那么初始化变量是最重要的!!所以定义了变量以后, 一定要定义 init = tf.initialize_all_variables() .

到这里变量还是没有被激活,需要再在 sess 里, sess.run(init) , 激活 init 这一步.

# 如果定义 Variable, 就一定要 initialize
# init = tf.initialize_all_variables() # tf 马上就要废弃这种写法
init = tf.global_variables_initializer()  # 替换成这样就好
 
# 使用 Session
with tf.Session() as sess:
    sess.run(init)
    for _ in range(3):
        sess.run(update)
        print(sess.run(state))

注意:直接 print(state) 不起作用!!

一定要把 sess 的指针指向 state 再进行 print 才能得到想要的结果!

2.Placeholder 传入值

这一次我们会讲到 Tensorflow 中的 placeholder , placeholder 是 Tensorflow 中的占位符暂时储存变量.

Tensorflow 如果想要从外部传入data, 那就需要用到 tf.placeholder(), 然后以这种形式传输数据 sess.run(*, feed_dict={input: }).

在 Tensorflow 中需要定义 placeholder 的 type ,一般为 float32 形式

import tensorflow as tf

#在 Tensorflow 中需要定义 placeholder 的 type ,一般为 float32 形式
input1 = tf.placeholder(tf.float32)
input2 = tf.placeholder(tf.float32)

# mul = multiply 是将input1和input2 做乘法运算,并输出为 output 
ouput = tf.multiply(input1, input2)

接下来, 传值的工作交给了 sess.run() , 需要传入的值放在了feed_dict={} 并一一对应每一个 input. placeholder 与 feed_dict={} 是绑定在一起出现的。

with tf.Session() as sess:
    print(sess.run(ouput, feed_dict={input1: [7.], input2: [2.]}))

总的来说

就是一开始初始化好placeholder,还有其他一些的运算例如ouput = tf.multiply(input1, input2),
然后下面一行代码:print(sess.run(ouput, feed_dict={input1: [7.], input2: [2.]}))
表示你运行sess.run的时候再用字典传入初始的值

扫描二维码关注公众号,回复: 4698899 查看本文章

猜你喜欢

转载自blog.csdn.net/qq_42016781/article/details/85330306