Tensorflow如何将张量数组转换为单个张量

3
我正在使用Tensorflow构建一个LSTM RNN,用于像素级分类(或者更好的说法是像素级预测?)。
请耐心听我解释标题。
网络如下图所示...

enter image description here

这个想法是...一个尺寸为(200,200)的输入图像被输入到大小为(200,200,200)的LSTM RNN中。LSTM RNN中每个序列输出的张量向量(LSTM RNN中的粉色框)都被馈送到MLP,然后MLP进行单个输出预测--因此是逐像素预测(您可以看到一个输入像素生成一个输出“像素”)。
代码如下所示(不是所有代码,只有需要的部分):
...
n_input_x = 200
n_input_y = 200

x = tf.placeholder("float", [None, n_input_x, n_input_y])
y = tf.placeholder("float", [None, n_input_x, n_input_y])

def RNN(x):
    x = tf.transpose(x, [1, 0, 2])
    x = tf.reshape(x, [-1, n_input_x])
    x = tf.split(0, n_steps, x)

    lstm_cell = rnn_cell.BasicLSTMCell(n_hidden, forget_bias=1.0, state_is_tuple=True)
    outputs, states = rnn.rnn(lstm_cell, x, dtype=tf.float32)

    output_matrix = []
    for i in xrange(200):
        temp_vector = []
        for j in xrange(200):
            lstm_vector = outputs[j]
            pixel_pred = multilayer_perceptron(lstm_vector, mlp_weights, mlp_biases)
            temp_vector.append(pixel_pred)
        output_matrix.append(temp_vector)
        print i

    return output_matrix

temp = RNN(x)
pred = tf.placeholder(temp, [None, n_input_x, n_input_y])
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(pred, y))
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)
...

我确认 RNN 的输出,即存储在 temp 中的是一个 200x200 的数组,数据类型为 <tf.Tensor 'Softmax_39999:0' shape=(?, 1) dtype=float32>
如您所见,我将 temp 放置在一个相同形状的 tf.placeholder 中(对于批量大小使用 None...或者我需要吗?)……然后程序就像完成运行一样退出了。理想情况下,当我调试并打印 pred 时,我希望看到的是类似于 <tf.Tensor shape=(200,200)> 的东西。
当我调试时,第一次执行 pred = tf.placeholder(temp, [None, n_input_x, n_input_y]),我会得到 TypeError: TypeErro...32>]]." 然后它 返回,我再尝试一次,它会说 Exception AttributeError: "'NoneType' object has no attribute 'path'" in <function _remove at 0x7f1ab77c26e0> ignored

编辑 我现在意识到我需要放置行

lstm_cell = rnn_cell.BasicLSTMCell(n_hidden, forget_bias=1.0, state_is_tuple=True)
outputs, states = rnn.rnn(lstm_cell, x, dtype=tf.float32)

在第一个循环内生成新的2D LSTM RNN,但是我遇到了有关变量重用的错误。 ValueError: Variable RNN/BasicLSTMCell/Linear/Matrix does not exist, disallowed. Did you mean to set reuse=None in VarScope? 换句话说,它没有自动递增RNN张量名称吗?
1个回答

0

使用tf.shape()更方便地报告形状。在您的情况下:

size1 = tf.shape(temp)
sess = tf.Session()
size1_fetched = sess.run(size1, feed_dict = your_feed_dict)

这样,size1_fetched就像你从NumPy中获取的一样。此外,还提供了特定feed_dict的大小。例如,您的[None,200,200]张量将是[64,200,200]

另一个问题:为什么在流图中间有占位符?您是否稍后会提供预定义的图像特征映射?


当我执行 tf.shape(temp) 时,它返回一个张量 <tf.Tensor 'Shape_1:0' shape=(4,) dtype=int32>。为什么是 (4,),为什么是 int32 类型?数组本身的形状是 (200,200)。从你的代码来看,你直接将模型馈送到会话中,没有任何损失或优化器函数。我不想这样做。 - Kendall Weihe

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接