如何动态更新tf.ones_like()的形状?

时间:2018-02-01 12:01:18

标签: python tensorflow machine-learning reshape

我在张量流中遇到了我的权重矩阵的维数问题。

#outputs = tf.reshape(outputs, [batch_size, seq_length, num_classes])

outputs = tf.reshape(outputs, [-1, seq_length, num_classes])

output_dim = outputs.get_shape().as_list()

weights = tf.ones([output_dim[0], seq_length], tf.int32) #TODO: change the dimension

sequence_loss = tf.contrib.seq2seq.sequence_loss(logits=outputs, targets=Y, weights=weights)

所以,我有一个在最后一个时期发生变化的batch_size,并且权重的维度在上一个纪元时会引起麻烦。

的     weights = tf.ones([output_dim[0], seq_length], tf.int32) 导致以下错误:

"Cannot convert a partially known TensorShape to a Tensor: %s" % s)
ValueError: Cannot convert a partially known TensorShape to a Tensor: (?, 25)

你会如何解决这个问题?我尝试使用tf.ones_like(outputs),但似乎不起作用,tf.ones似乎需要一个固定值作为其维度。

1 个答案:

答案 0 :(得分:0)

使用支持动态形状的tf.fill

a = tf.placeholder(tf.float32, shape=[None, 25, 10])
b = tf.fill(tf.shape(a)[:-1], 1)  # shape=[None, 25]

with tf.Session() as sess:
  print(sess.run(b, feed_dict={a: np.zeros([10, 25, 10])}))

# Prints:
# [[1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1]
#  [1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1]
#  [1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1]
#  [1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1]
#  [1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1]
#  [1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1]
#  [1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1]
#  [1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1]
#  [1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1]
#  [1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1]]