【发布时间】:2017-11-09 09:31:22
【问题描述】:
我正在尝试在 TensorFlow 上使用 LSTM 构建 RNN。输入和输出都是 5000 x 2 矩阵,其中的列代表特征。然后将这些矩阵馈送到启用反向传播的 batchX 和 batchY 占位符。代码的主要定义在底部。我收到以下错误:
“等级不匹配:标签等级(收到 2)应等于 logits 等级减去 1(收到 2)。”
我检查了logits_series 和labels_series,它们似乎都包含[batch_size, num_features] 形状的张量的反向传播量
我感到困惑的是:既然logits是标签的预测,它们不应该有相同的维度吗?
'''
RNN definitions
input_dimensions = [batch_size, truncated_backprop_length, num_features_input]
output_dimensions = [batch_size, truncated_backprop_length, num_features_output]
state_dimensions = [batch_size, state_size]
'''
batchX_placeholder = tf.placeholder(tf.float32, (batch_size, truncated_backprop_length, num_features_input))
batchY_placeholder = tf.placeholder(tf.int32, (batch_size, truncated_backprop_length, num_features_output))
init_state = tf.placeholder(tf.float32, (batch_size, state_size))
inputs_series = tf.unstack(batchX_placeholder, axis=1)
labels_series = tf.unstack(batchY_placeholder, axis=1)
w = tf.Variable(np.random.rand(num_features_input+state_size,state_size), dtype = tf.float32)
b = tf.Variable(np.zeros((batch_size, state_size)), dtype = tf.float32)
w2 = tf.Variable(np.random.rand(state_size, num_features_output), dtype = tf.float32)
b2 = tf.Variable(np.zeros((batch_size, num_features_output)), dtype=tf.float32)
#calculate state and output variables
state_series = []
output_series = []
current_state = init_state
#iterate over each truncated_backprop_length
for current_input in inputs_series:
current_input = tf.reshape(current_input,[batch_size, num_features_input])
input_and_state_concatenated = tf.concat([current_input,current_state], 1)
next_state = tf.tanh(tf.matmul(input_and_state_concatenated, w) + b)
state_series.append(next_state)
current_state = next_state
output = tf.matmul(current_state, w2)+b2
output_series.append(output)
#calculate expected output for each state
logits_series = [tf.matmul(state, w2) + b2 for state in state_series]
#print(logits_series)
predictions_series = [tf.nn.softmax(logits) for logits in logits_series]
'''
batchY_placeholder = np.zeros((batch_size,truncated_backprop_length))
for i in range(batch_size):
for j in range(truncated_backprop_length):
batchY_placeholder[i,j] = batchY1_placeholder[j, i, 0]+batchY1_placeholder[j, i, 1]
'''
print("logits_series", logits_series)
print("labels_series", labels_series)
#calculate losses given each actual and calculated output
losses = [tf.nn.sparse_softmax_cross_entropy_with_logits(logits = logits, labels = labels) for logits, labels in zip(logits_series,labels_series)]
total_loss = tf.reduce_mean(losses)
【问题讨论】:
-
标签的最后一个维度(带 2 个元素)是单热格式吗?如果您使用
tf.nn.sparse_softmax_cross_entropy_with_logits,则应该减少该维度(即[5000]),每个元素存储相应的类标签(例如0或1)。 -
感谢您的回复。是的,标签的最后一个维度是单热格式是绝对正确的。我应该通过将两个 one-hot 维度转换为具有元素 0、1、2、3 的单个维度来减少它吗?
-
按照你说的压缩类并减少最后一个维度。
-
成功了,非常感谢
标签: tensorflow