【问题标题】:Tensorflow: how should I reshape a row placeholder to a column placeholderTensorflow:我应该如何将行占位符重塑为列占位符
【发布时间】:2017-12-11 21:51:16
【问题描述】:

我想将行占位符(例如 [1, 2])转换为列占位符,例如 [[1], [2]]

y = tf.placeholder(tf.int32, shape=[None], name='target')
y = tf.reshape(y, (y.shape[0], 1))

init = tf.global_variables_initializer()
with tf.Session() as sess:
    init.run()
    print(sess.run(y, feed_dict={y:[1,2]}))

但我得到一个错误:

TypeError: Failed to convert object of type <class 'tuple'> to Tensor. Contents: (Dimension(None), 1). Consider casting elements to a supported type.

问题在于y.shape[0] 的使用。 y 的维度定义为None。我也尝试过tf.shape(y),但效果不佳。

【问题讨论】:

    标签: python multidimensional-array tensorflow


    【解决方案1】:

    我不确定您是不是这个意思,但是您不能在运行时更改 tensorflow 中节点的形状。因此,target 被定义为 [?] 占位符,它将保持不变。

    您可以做的是使用tf.expand_dims 函数将其转换为新张量(不会是占位符!),正如已经建议的那样。这意味着您仍然需要输入 [?] 数组,但您可以在计算中使用重新整形的张量。

    y = tf.placeholder(tf.int32, shape=[None], name='target')
    z = tf.expand_dims(y, axis=1)  # another tensor
    
    with tf.Session() as sess:
      tf.global_variables_initializer().run()
      print(sess.run(z, feed_dict={y:[1, 2]}))
    

    【讨论】:

      【解决方案2】:

      使用 tf.expand_dims() 简单地将行转换为列

      y = tf.placeholder(tf.int32, shape=[None], name='target')
      y = tf.expand_dims(y,axis=1)
      

      但是,您在提供数据时遇到了另一个问题,因为简单地向张量添加维度并不会定义其形状,它只是添加一个额外的索引。这是您可以独立发布的另一个问题。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-10-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多