使用占位符值重构张量

时间:2016-02-13 01:21:42

标签: tensorflow

我想使用[int,-1]表示法重新形成张量(例如,展平图像)。但我不提前知道第一个维度。一个用例是大批量训练,然后在较小批次上进行评估。

为什么会出现以下错误:got list containing Tensors of type '_Message'

import tensorflow as tf
import numpy as np

x = tf.placeholder(tf.float32, shape=[None, 28, 28])
batch_size = tf.placeholder(tf.int32)

def reshape(_batch_size):
    return tf.reshape(x, [_batch_size, -1])

reshaped = reshape(batch_size)


with tf.Session() as sess:
    sess.run([reshaped], feed_dict={x: np.random.rand(100, 28, 28), batch_size: 100})

    # Evaluate
    sess.run([reshaped], feed_dict={x: np.random.rand(8, 28, 28), batch_size: 8})

注意:当我在函数外部重塑它似乎工作,但我有很多次使用的非常大的模型,所以我需要将它们保存在一个函数中并使用参数传递dim。

2 个答案:

答案 0 :(得分:10)

要使其工作,请替换功能:

def reshape(_batch_size):
    return tf.reshape(x, [_batch_size, -1])

......功能:

def reshape(_batch_size):
    return tf.reshape(x, tf.pack([_batch_size, -1]))

错误的原因是tf.reshape()期望一个可转换为tf.Tensor的值作为其第二个参数。 TensorFlow会自动将Python数字列表转换为tf.Tensor,但不会自动转换数字和张量的混合列表(例如tf.placeholder()) - 而是提出您看到的有些不直观的错误消息。 / p>

tf.pack() op获取可转换为张量的对象的列表,并单独转换每个元素,因此它可以处理占位符和整数的组合。

答案 1 :(得分:0)

嗨,所有问题都归因于Keras版本。我首先尝试过没有任何成功。卸载Keras并通过pip安装。它对我有用。

我在Keras 1.0.2&解决了Keras 1.2.0

希望这会有所帮助。谢谢

相关问题