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

arm*_*dle 22 tensorflow

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

x = tf.placeholder(..., shape=[], ...)
y = tf.placeholder(..., shape=[None], ...)
z = tf.placeholder(..., shape=None, ...) 
w = tf.placeholder(..., shape=(), ...)
Run Code Online (Sandbox Code Playgroud)

这些有什么区别?

use*_*882 21

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}))
Run Code Online (Sandbox Code Playgroud)

可以看出,具有[]形状的占位符直接采用单个量值.具有[None]形状的占位符采用一维数组,具有None形状的占位符可以在计算发生时采用任何值.