tensorflow中的变量和占位符

来源:互联网 发布:淘宝美工可以用素材网 编辑:程序博客网 时间:2024/05/29 05:02
import tensorflow as tfa = tf.constant(2, tf.int16)b = tf.constant(4, tf.float32)graph = tf.Graph()with graph.as_default():    a = tf.Variable(8, tf.float32)    b = tf.Variable(tf.zeros([2, 2], tf.float32))with tf.Session(graph=graph) as session:    tf.global_variables_initializer().run()    print(session.run(a))    print(session.run(b))

实验结果:

8[[ 0.  0.] [ 0.  0.]]

tensorflow在图graph中定义了a,b两个变量,在启动graph时候,必须把变量加载到内存中(通过方法global_variables_initializer())
,这样才能在session中run(a),run(b)
session只能启动graph=graph中的变量,如果变量不在graph中就会报错。

import tensorflow as tfgraph = tf.Graph()with graph.as_default():    a = tf.Variable(8, tf.float32)    b = tf.Variable(tf.zeros([2, 2], tf.float32))a = tf.constant(2, tf.int16)b = tf.constant(4, tf.float32)with tf.Session(graph=graph) as session:    tf.global_variables_initializer().run()    print(session.run(a))    print(session.run(b))

报错

ValueError: Fetch argument <tf.Tensor 'Const:0' shape=() dtype=int16> cannot be interpreted as a Tensor. (Tensor Tensor("Const:0", shape=(), dtype=int16) is not an element of this graph.)

变量必须初始化才会有具体的值global_variables_initializer()进行初始化,而常量就不用初始化。
占位符
占位符是定义一个可变的常量,占位符赋值后不用初始化就可以获取值。

import tensorflow as tfx = tf.placeholder(tf.string)y = tf.placeholder(tf.int32)z = tf.placeholder(tf.float32)with tf.Session() as sess:    output = sess.run(x, feed_dict={x: 'Test String', y: 123, z: 45.67})print(output)

实验结果:

Test String