什么是tf.placeholder()之间的区别,并直接将数据分配给变量?

时间:2017-10-24 09:36:31

标签: tensorflow

这是我的代码和输出结果

import tensorflow as tf
batch_size = 128
sequence_length = 100

batch_size2 = tf.placeholder(tf.int32, [])
sequence_length2 = tf.placeholder(tf.int32, [])

_sequence_length1 = tf.convert_to_tensor(batch_size * [sequence_length], dtype=tf.int32)
_sequence_length2 = tf.convert_to_tensor(batch_size2 * [sequence_length2], dtype=tf.int32)

with tf.Session() as session:
    session.run(tf.global_variables_initializer())
    print('_sequence_length1', session.run(_sequence_length1))
    print('shape of sequence1', _sequence_length1)

    print('_sequence_length2', session.run(_sequence_length2, feed_dict={batch_size2: 128, sequence_length2: 100}))
    print('shape of sequence2', _sequence_length2)

结果如下:

('_sequence_length1', array([100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100,
   100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100,
   100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100,
   100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100,
   100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100,
   100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100,
   100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100,
   100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100,
   100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100,
   100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100], dtype=int32))
('shape of sequence1', <tf.Tensor 'Const:0' shape=(128,) dtype=int32>)
('_sequence_length2', array([12800], dtype=int32))
('shape of sequence2', <tf.Tensor 'mul:0' shape=(1,) dtype=int32>)

我想使用tf.placeholder()将不同的变量提供给batch_size和sequence_length,但我希望结果像_sequence_length1,我不知道为什么_sequence_length2的形状是(1,),我认为形状_sequence_length2与_sequence_length1相同。所以你能告诉我为什么吗?非常感谢......

2 个答案:

答案 0 :(得分:0)

  1. _sequence_length1 - 您使用128个元素从pythons列表中创建Tensor[100, ..., 100]
  2. _sequence_length2 - 是两个张量的乘法运算,batch_size2,秩= 0,第二个[sequence_length2],秩= 1。
  3. 如果您想要与_sequence_length1中的结果相同,则可以使用:

    _sequence_length2 = tf.tile([sequence_length2], [batch_size2])
    

    而不是

    _sequence_length2 = tf.convert_to_tensor(batch_size2 * [sequence_length2], dtype=tf.int32)
    

答案 1 :(得分:0)

它也可以使用

_sequence_length2 = tf.constant(np.full(batch_size, sequence_length2, dtype=np.int32))