我正在研究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和标签参数为二-D张量,带有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)
我对如何工作的理解有根本的错误吗?
可以通过简单的RNN GIST查看完整代码
谢谢
代码的第30行对您的RNN输出会产生一些奇怪的作用。RNN通常输出其3D张量(batch_size,time_steps,cell_output_dim),它变成带有切片操作的2D(输出[-1])。显然,损耗函数不会期望这种张量,因此您会出现错误。如果要在多维张量上应用馈电神经网络,我建议您使用tf.contrib.layers.uly_connected函数,该函数将自动为您的网络创建权重,并将在输入张量上应用正确的操作。
>您的代码中还有另一个错误。您正在尝试将SoftMax_Cross_entropy_with_logits应用于3D张量。不幸的是,您无法执行此操作,因此您需要执行以下操作:
- 将张量重塑为尺寸(batch_size * time_steps,num_classes);
- 使用softmax_cross_entropy_with_logits应用每个batch_size * time_steps示例的每个损失函数(现在可以正确应用);
- 平均损失值(这只是可能性,您可以根据需要汇总损失值)。
我在这里无法提供完整的解决方案,因为我没有您的数据,因此我无法精确执行您的代码。但是,我将报告以下简化片段:
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))