占位符形状的[],[None],None和()之间有什么区别?

时间:2017-10-25 19:43:09

标签: tensorflow

我看到使用[][None]None()作为placeholder的形状的代码片段,即

x = tf.placeholder(..., shape=[], ...)
y = tf.placeholder(..., shape=[None], ...)
z = tf.placeholder(..., shape=None, ...) 
w = tf.placeholder(..., shape=(), ...)

这些之间有什么区别?

1 个答案:

答案 0 :(得分:17)

TensorFlow使用数组而不是元组。它将元组转换为数组。因此[]()是等效的。

现在,请考虑以下代码示例:

x = tf.placeholder(dtype=tf.int32, shape=[], name="foo1")
y = tf.placeholder(dtype=tf.int32, shape=[None], name="foo2")
z = tf.placeholder(dtype=tf.int32, shape=None, name="foo3")

val1 = np.array((1, 2, 3))
val2 = 45

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())

    #print(sess.run(x, feed_dict = {x: val1}))  # Fails
    print(sess.run(y, feed_dict = {y: val1}))
    print(sess.run(z, feed_dict = {z: val1}))

    print(sess.run(x, feed_dict = {x: val2}))
    #print(sess.run(y, feed_dict = {y: val2}))  # Fails
    print(sess.run(z, feed_dict = {z: val2}))

可以看出,[]形状的占位符直接获取单个标量值。 [None]形状的占位符采用一维数组,None形状的占位符可以在计算过程中接收任何值。