Tensorflow RNN 形状不匹配 - logits_size=[5,2] labels_size=[50,2] - 批量大小为 10

Tensorflow RNN shape mismatch- logits_size=[5,2] labels_size=[50,2] - Batch size is 10

我正在 Tensorflow 中进行简单的 LSTM 实现,但在维度方面遇到了一些问题。所以,我的

batch size = 10
time_steps = 5
num_classes = 2 
input_size = 4

占位符是

x = tf.placeholder('float',[None,time_steps,input_size])

y = tf.placeholder('float',[None,None,num_classes])

我运行它通过从csv文件提供数据

_, c = sess.run([optimizer, cost], feed_dict={x: _x, y: _y}) 我设置 _x.shape = (10, 5, 4)_y.shape = (10, 5, 2) 的地方 按照TF的(batch,time_steps, input_size)要求

我已经在互联网和博客文章中完成了一些实现(主要是在 MNIST 数据集上),我想我已经理解它是如何工作的。 TF 期望 logits 和 labels 参数是具有 batch_size 行和 num_classes 列的二维张量。现在,我对每个条目都有一个分类标签。我已将它们转换为单热格式。如果我从数据中提供总共 50 个条目,我也应该提供 50 个标签,对吗?

将 y 占位符更改为 [None,num_classes],因此其他一些东西也给出了错误。

但是如果我将 batch_size 更改为 1,我可以将代码设为 运行,直到行

correct = tf.equal(tf.argmax(prediction, 1), tf.argmax(y, 1)) 我在哪里出错 ValueError: Dimensions must be equal, but are 5 and 2 for 'Equal' (op: 'Equal') with input shapes: [5], [?,2]. 因为预测形状是 (5, 2) 而 y 是 (?, ?, 2)

我对它应该如何工作的理解是否存在根本性错误?

完整代码可以在Simple RNN Gist

查看

谢谢

代码的第 30 行对 RNN 的输出做了一些奇怪的事情。 RNN 输出通常是 3D 张量 (batch_size、time_steps、cell_output_dim),它通过切片操作变成 2D 张量 (outputs[-1])。显然,损失函数不期望这种张量,所以你得到了一个错误。如果你想在多维张量上应用前馈神经网络,我建议你使用 tf.contrib.layers.fully_connected 函数,它会自动为你的网络创建权重并对输入张量应用正确的操作。

您的代码中还有一个错误。您正在尝试将 softmax_cross_entropy_with_logits 应用于 3D 张量。很遗憾,您不能这样做,因此您需要执行以下操作:

  1. 将张量重塑为维度 (batch_size * time_steps, num_classes);
  2. 使用 softmax_cross_entropy_with_logits 为 batch_size * time_steps 示例中的每一个应用损失函数(现在可以正确应用);
  3. 平均损失值(这只是一种可能性,您可以根据需要汇总损失值)。

我无法在这里提供完整的解决方案,因为我没有您的数据,所以我无法准确执行您的代码。但是,我将报告以下简化片段:

import tensorflow as tf
import numpy as np
from tensorflow.contrib import rnn 

num_classes = 2
batch_size  = 10
time_steps = 5

#input has 4 features
input_size = 4
num_hidden = 6

x = tf.placeholder('float',[None,time_steps,input_size])
y = tf.placeholder('float',[None,None,num_classes])

def neural_net_model(data):
    lstmCell = rnn.BasicLSTMCell(num_hidden)

    outputs, state = tf.nn.dynamic_rnn(lstmCell,x, dtype=tf.float32)
    print(outputs)

    output = tf.contrib.layers.fully_connected(
        outputs,
        num_classes,
        weights_initializer=tf.random_normal_initializer()
    )
    return output

def train_neural_net(x):
    num_epochs = 2
    num_examples = 1000 #np_df.shape[0] - reduced to 1000 for debugging 
    with tf.Session() as sess:
        predictions = neural_net_model(x)
        reshaped_predictions = tf.reshape(predictions, (-1, num_classes))
        reshaped_targets = tf.reshape(y, (-1, num_classes))
        cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=reshaped_predictions,labels=reshaped_targets))