TensorFlow语法--Variable与placeholder的区别

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/newchenxf/article/details/79503057

1. Variable

定义可以从如下代码看。

import tensorflow as tf

# Create a variable. 注意Variable(...)是一个类,下面的placeholder(...)是一个函数
w = tf.Variable(<initial-value>, name=<optional-name>)

# Use the variable in the graph like any Tensor.
y = tf.matmul(w, ...another variable or tensor...)

# The overloaded operators are available too.
z = tf.sigmoid(w + y)

# Assign a new value to the variable with `assign()` or a related method.
w.assign(w + 1.0)
w.assign_add(1.0)

本质也是一个tensor张量,但variable主要用于数据存储(当作C语言的全局变量也不是不可以^^)
Variable 用于构建一个变量,在计算图的运算过程中,其值会一直保存到程序运行结束,而一般的tensor张量在tensorflow运行过程中只是在计算图中流过,并不会保存下来。
因此Varibale主要用来保存tensorflow构建的一些结构中的参数,这些参数才不会随着运算的消失而消失,才能最终得到一个模型。
比如神经网络中的权重和bias等,在训练过后,总是希望这些参数能够保存下来,而不是直接就消失了,所以这个时候要用到Variable。
注意,所有和varible有关的操作在计算的时候都要使用session会话来控制,包括计算,打印等等。

import tensorflow as tf
a=tf.Variable(1)
b=tf.constant(1)  #定义变量a=0和常量1,并且定义a的自加运算aplus1和更新a的值得操作update"""
aplus1=tf.add(a,b)
update=tf.assign(a,aplus1)

#设置完变量之后,必须要对变量进行初始化工作,变量才能使用
init=tf.initialize_all_variables()
with tf.Session() as sess:
    sess.run(init) #运行初始化变量的计算
    for i in range(10): #循环10次,查看a逐渐自加1的结果
        sess.run(update) #执行变量a的自加运算
        print(sess.run(a)) #打印变量a也需要用session.run

placeholder

定义

tf.placeholder(
    dtype,
    shape=None,
    name=None
)

参数:
dtype: 被填充的张量的元素类型。比如最常见的float32。
shape: 可选参数。比如要1024x1024矩阵,可以这么定义:x = tf.placeholder(tf.float32, shape=(1024, 1024))。
name: 可选参数。A name for the operation。

placeholder也是一个tenser,只能在图计算时,Session.run(), Tensor.eval(), or Operation.run(),用feed_dict的字典喂数据。
Important: This tensor will produce an error if evaluated. Its value must be fed using the feed_dict optional argument to Session.run(), Tensor.eval(), or Operation.run().
举例:

import tensorflow as tf
x = tf.placeholder(tf.float32, shape=(1024, 1024))
y = tf.matmul(x, x)

with tf.Session() as sess:
    print(sess.run(y))  # ERROR: will fail because x was not fed.

    rand_array = np.random.rand(1024, 1024)
    print(sess.run(y, feed_dict={x: rand_array}))  # Will succeed.

再举个同时使用2个placeholder的例子。

import tensorflow as tf

#placeholder测试
input1 = tf.placeholder(tf.float32)
input2 = tf.placeholder(tf.float32)
# output = tf.multiply(input1,input2)#乘法
# output = tf.add(input1,input2)#加法
# output = tf.mod(input1,input2)#余数
# output = tf.sub(input1,input2)#减发
output = tf.div(input1,input2)#除法

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

总结

如果上面扯淡那么久还是不明白,可以这么想。假设我们要找到一个线性函数
y = w0 * x + w1,有一堆样本数据(X, Y), 训练的目标是(w0, w1),则样本数据,需要创建placeholder,然后喂数据给placeholder,需要创建variable,来更新迭代(w0, w1)。
variable必须初始化,主要用于存训练变量,如模型的权重,偏差。placeholder不用初始化,在session.run(xx, feed_dict)时指定,主要用于输入样本。

参考

http://blog.csdn.net/u014546828/article/details/77962104

猜你喜欢

转载自blog.csdn.net/newchenxf/article/details/79503057
今日推荐