首页 文章

tensorflow如何重塑尺寸为None的张量,如[None,2,2,1]?

提问于
浏览
1

错误是:

TypeError:无法将类型对象转换为Tensor . 内容:[无,4] . 考虑将元素转换为支持的类型 .

import tensorflow as tf
xs=tf.placeholder(tf.float32,[None,2,2,1],name='x-input')
reshaped_xs=tf.reshape(xs,[None,4])

with tf.Session() as sess:
    print sess.run(reshaped_xs)

tensorflow版本是:1.4.0

docker run -d  --restart=always -p 8888:8888 tensorflow/tensorflow:1.4.0

那么如何解决这个问题呢? TKS!

3 回答

  • 0

    要重塑占位符,只需使用 -1 作为未知维度 . 使用 sess.run 时,还必须向占位符提供值 . 这将有效:

    import tensorflow as tf
    
    xs = tf.placeholder(tf.float32, [None, 2, 2, 1], name='x-input')
    
    reshaped_xs = tf.reshape(xs, [-1, 4])
    
    with tf.Session() as sess:
        x = [[[[0.], [0.]], [[0.], [0.]]]]
        print(sess.run(reshaped_xs, feed_dict={xs: x}))
    
  • 0

    你不能重塑一个占位符,它为在feed dict中传递的对象保留一个内存空间,None表示内存将被动态分配,在你的情况下,你正在将一个未分配的内存重新整形为另一个固定大小的内存,它可能是语法正确但我怀疑你是否在ipython中运行它会工作 .

  • 2

    我认为这是问题和答案的评论意味着什么 . 不得不首先为自己澄清 . 相似的东西 .

    import tensorflow as tf
    import numpy as np
    
    x = tf.placeholder(dtype=tf.float32, shape=(None))
    x_reshaped = tf.reshape(x, shape=[tf.shape(x)[0], 2,2,1])
    
    with tf.Session() as sess:
        init = tf.global_variables_initializer()
        sess.run(init)
        _, x_reshaped_result = sess.run([x, x_reshaped], feed_dict={x: np.random.random(16).reshape(4, 2, 2, 1)})
        print (x_reshaped_result.shape)
    

相关问题