【问题标题】:How do I dynamically update the shape of tf.ones_like()?如何动态更新 tf.ones_like() 的形状?
【发布时间】:2018-02-01 12:01:17
【问题描述】:

我在 tensorflow 中的权重矩阵维度遇到问题。

#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)

所以,我有一个在最后一个 epoch 发生变化的 batch_size,而权重的维度在最后一个 epoch 时会引起麻烦。

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 似乎需要一个固定值作为其维度。

【问题讨论】:

    标签: python tensorflow machine-learning reshape


    【解决方案1】:

    使用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]]
    

    【讨论】:

    • 我不知道我做错了什么,但它说 sequence_loss 行中有错误。它说它试图从 dtype float32 转换为 dtype int32 并且它是无效的。我以前从未遇到过此类问题。
    • 如果需要浮点类型,请填写1.0
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-06
    • 1970-01-01
    • 2022-11-29
    相关资源
    最近更新 更多