Shape of labels does not match shape of predictions
I'm using the official LSTM model with my own iterator(https://github.com/dmlc/mxnet/issues/2105). However, it reports "Shape of labels does not match shape of predictions" even though I reshaped the variable label in the model. The codes for the model:
def lstm_unroll(batch_size, num_lstm_layer, seq_len,
num_hidden, num_label, dropout=0.):
# embed_weight = mx.sym.Variable("embed_weight")
cls_weight = mx.sym.Variable("cls_weight")
cls_bias = mx.sym.Variable("cls_bias")
param_cells = []
last_states = []
for i in range(num_lstm_layer):
param_cells.append(LSTMParam(i2h_weight=mx.sym.Variable("l%d_i2h_weight" % i),
i2h_bias=mx.sym.Variable("l%d_i2h_bias" % i),
h2h_weight=mx.sym.Variable("l%d_h2h_weight" % i),
h2h_bias=mx.sym.Variable("l%d_h2h_bias" % i)))
state = LSTMState(c=mx.sym.Variable("l%d_init_c" % i),
h=mx.sym.Variable("l%d_init_h" % i))
last_states.append(state)
assert(len(last_states) == num_lstm_layer)
# convolution layers
data = mx.sym.Variable('data')
label = mx.sym.Variable('softmax_label')
conv1_weight = mx.sym.Variable('conv1_weight')
conv1_bias = mx.sym.Variable('conv1_bias')
conv2_weight = mx.sym.Variable('conv2_weight')
conv2_bias = mx.sym.Variable('conv2_bias')
# pool2 = [[]] * seq_len
# for i in range(seq_len):
# print data.infer_shape()
pool = []
data = mx.sym.SliceChannel(data=data, num_outputs=batch_size, axis=0, squeeze_axis=True)
for i in range(batch_size):
conv1 = mx.sym.Convolution(data=data[i], kernel=(3,3), num_filter=100, weight=conv1_weight, bias=conv1_bias)
# print conv1.infer_shape()
conv1 = mx.sym.Activation(data=conv1, act_type='relu')
pool1 = mx.sym.Pooling(data=conv1, kernel=(3,3), stride=(2,2), pool_type='max')
conv2 = mx.sym.Convolution(data=pool1, kernel=(3,3), num_filter=100, weight=conv2_weight, bias=conv2_bias)
conv2 = mx.sym.Activation(data=conv2, act_type='relu')
pool2 = mx.sym.Pooling(data=conv2, kernel=(3,3), stride=(2,2), pool_type='max')
# shape = pool2.infer_shape(**{'data':(batch_size, seq_len, 1, 120, 160)})[-2][0]
pool2 = mx.sym.Reshape(data=pool2, target_shape=(1, 500, 100, 28, 38))
pool.append(pool2)
# embed = mx.sym.Embedding(data=data, input_dim=input_size,
# weight=embed_weight, output_dim=num_embed, name='embed')
# wordvec = mx.sym.SliceChannel(data=embed, num_outputs=seq_len, squeeze_axis=1)
pool = mx.sym.Concat(*pool, dim=0)
# pool = mx.sym.SliceChannel(data=pool, num_outputs=batch_size, axis=0)
data_seq = mx.sym.SliceChannel(data=pool, num_outputs=seq_len, axis=1, squeeze_axis=True)
hidden_all = []
for seqidx in range(seq_len):
hidden = data_seq[seqidx]
# stack LSTM
for i in range(num_lstm_layer):
if i == 0:
dp_ratio = 0.
else:
dp_ratio = dropout
next_state = lstm(num_hidden, indata=hidden,
prev_state=last_states[i],
param=param_cells[i],
seqidx=seqidx, layeridx=i, dropout=dp_ratio)
hidden = next_state.h
last_states[i] = next_state
# decoder
if dropout > 0.:
hidden = mx.sym.Dropout(data=hidden, p=dropout)
hidden_all.append(hidden)
hidden_concat = mx.sym.Concat(*hidden_all, dim=0)
pred = mx.sym.FullyConnected(data=hidden_concat, num_hidden=num_label,
weight=cls_weight, bias=cls_bias, name='pred')
################################################################################
# Make label the same shape as our produced data path
# I did not observe big speed difference between the following two ways
label = mx.sym.transpose(data=label)
label = mx.sym.Reshape(data=label, target_shape=(batch_size * seq_len,))
#label_slice = mx.sym.SliceChannel(data=label, num_outputs=seq_len)
#label = [label_slice[t] for t in range(seq_len)]
#label = mx.sym.Concat(*label, dim=0)
#label = mx.sym.Reshape(data=label, target_shape=(0,))
################################################################################
# return label
sm = mx.sym.SoftmaxOutput(data=pred, label=label, name='softmax')
return sm
Thank you in advance!
Do you get this error in metric?
@Godricly Yes. The full traceback:
Traceback (most recent call last):
File "video_lstm_2.py", line 277, in <module>
model = mx.model.FeedForward.create(m, X=iter, eval_data=val_iter, num_epoch
= 200, learning_rate=0.01, epoch_end_callback=a_epoch, batch_end_callback=mx.ca
llback.Speedometer(batch_size))
File "F:\PublicToolbox\Anaconda\lib\site-packages\mxnet-0.5.0-py2.7.egg\mxnet\
model.py", line 900, in create
eval_batch_end_callback=eval_batch_end_callback)
File "F:\PublicToolbox\Anaconda\lib\site-packages\mxnet-0.5.0-py2.7.egg\mxnet\
model.py", line 783, in fit
sym_gen=self.sym_gen)
File "F:\PublicToolbox\Anaconda\lib\site-packages\mxnet-0.5.0-py2.7.egg\mxnet\
model.py", line 245, in _train_multi_device
executor_manager.update_metric(eval_metric, data_batch.label)
File "F:\PublicToolbox\Anaconda\lib\site-packages\mxnet-0.5.0-py2.7.egg\mxnet\
executor_manager.py", line 406, in update_metric
self.curr_execgrp.update_metric(metric, labels)
File "F:\PublicToolbox\Anaconda\lib\site-packages\mxnet-0.5.0-py2.7.egg\mxnet\
executor_manager.py", line 262, in update_metric
metric.update(labels_slice, texec.outputs)
File "F:\PublicToolbox\Anaconda\lib\site-packages\mxnet-0.5.0-py2.7.egg\mxnet\
metric.py", line 141, in update
check_label_shapes(label, pred_label)
File "F:\PublicToolbox\Anaconda\lib\site-packages\mxnet-0.5.0-py2.7.egg\mxnet\
metric.py", line 20, in check_label_shapes
"predictions {}".format(label_shape, pred_shape))
ValueError: Shape of labels 1 does not match shape of predictions 500
And I tried to print the labels, it should have been an NDArray shaped like (500,), however it actually shaped like (1,500,)
A stupid way I used is to write another metric to bypass this check and handle your data label urself. I think mxnet is giving you the shape of your raw label(before reshape). I can't remember the exact reason as my coworker get into this problem before, It probably because the metric is using data_batch.label in its update in the model.py. @piiswrong
@helloworldlxb Hi! Have you fixed your problem? I am having exactly the same issue here. Any wisdom please? Many thanks!
For everyone's information, hereby I would like to share my solution to this problem. Although the structure of my customized networks is different, I also encountered the same error, i.e. "Shape of labels does not match shape of predictions".
I agree with @Godricly that this is kind of a bug of the metric. Even we have reshaped the label to 1D vector, the metric will use the shape provided by the data batch, i.e. (1, 500,) in your case. Hence, to address this issue, the straight way is to modify your customized DataIter code to make sure the labels provided are a 1D vector.
However, if you have labels for each time step, the solution above doesn't work. Here is another ugly trick for both cases. Just modify the codes in the metric.py (of course, you need root/sudo permission) to squeeze the labels. The squeeze function will remove the single dimension. If I remember correctly, there is one line like "label = labels[i].asnumpy().astype("int32")". Below it, you could add a new line "label = label.squeeze()". I know this sounds crazy, but it works anyway.
Hope my reply would help you guys.
This issue is closed due to lack of activity in the last 90 days. Feel free to reopen if this is still an active issue. Thanks!
So mxnet just ignore this bug and leave it alone???
@Matafight are you still running into this issue on certain metric?
@szha yes, at first, I thought there may be sth wrong with my own iterator, just now I tried with mx.io.NDArrayIter, the same error occured。
@szha the error is:
Traceback (most recent call last):
File ".\all_test.py", line 57, in <module>
mod.fit(data_iter,num_epoch=5,epoch_end_callback=checkpoint)
File "C:\ProgramData\Anaconda3\lib\site-packages\mxnet-0.11.1-py3.6.egg\mxnet\module\base_module.py", line 496, in fit
self.update_metric(eval_metric, data_batch.label)
File "C:\ProgramData\Anaconda3\lib\site-packages\mxnet-0.11.1-py3.6.egg\mxnet\module\module.py", line 735, in update_metric
self._exec_group.update_metric(eval_metric, labels)
File "C:\ProgramData\Anaconda3\lib\site-packages\mxnet-0.11.1-py3.6.egg\mxnet\module\executor_group.py", line 582, in update_metric
eval_metric.update_dict(labels_, preds)
File "C:\ProgramData\Anaconda3\lib\site-packages\mxnet-0.11.1-py3.6.egg\mxnet\metric.py", line 108, in update_dict
self.update(label, pred)
File "C:\ProgramData\Anaconda3\lib\site-packages\mxnet-0.11.1-py3.6.egg\mxnet\metric.py", line 396, in update
check_label_shapes(label, pred_label)
File "C:\ProgramData\Anaconda3\lib\site-packages\mxnet-0.11.1-py3.6.egg\mxnet\metric.py", line 41, in check_label_shapes
"predictions {}".format(label_shape, pred_shape))
ValueError: Shape of labels 128 does not match shape of predictions 11520
And the simplified codes that can reproduce the above issue is as follows:
#_*_coding:utf-8_*_
import mxnet as mx
import mxnet.ndarray as nd
#setup parameters
def get_parameters():
batch_size = 128
embed_dim = 200
num_steps = 90
num_hidden = 100
return batch_size,embed_dim,num_steps,num_hidden
def try_gpu():
try:
ctx=mx.gpu()
_ = nd.array([0],ctx=ctx)
except:
ctx=mx.cpu()
return ctx
#setup context
context = try_gpu()
#load data
def test_mx_io_dataiter(batch_size,num_steps):
corpus_vec = nd.ones(shape = (1024,num_steps),ctx=context)
dataiter = mx.io.NDArrayIter(data = corpus_vec,label=corpus_vec,batch_size=batch_size,data_name='data',label_name='softmax_label')
return dataiter
def poem_rnn(batch_size,vocab_size,embed_dim,num_hidden,num_steps):
seq_input = mx.symbol.Variable('data')
label = mx.sym.Variable('softmax_label')
embedded_seq = mx.symbol.Embedding(data=seq_input,
input_dim=vocab_size,
output_dim=embed_dim)
lstm_cell = mx.rnn.LSTMCell(num_hidden=num_hidden)
#NTC : batch_size *num_steps*input_embed_dim
outputs, _ = lstm_cell.unroll(length=num_steps,
inputs=embedded_seq,
layout='NTC',
merge_outputs=True)
pred = mx.sym.Reshape(outputs,shape=(-1,num_hidden))
pred = mx.sym.FullyConnected(data = pred,num_hidden=vocab_size,name='pred')
label = mx.sym.Reshape(label,shape=(-1,))
pred = mx.sym.SoftmaxOutput(data = pred,label=label,name='softmax')
return pred
batch_size,embed_dim,num_steps,num_hidden = get_parameters()
vocab_size = 1500
data_iter = test_mx_io_dataiter(batch_size,num_steps)
output = poem_rnn(batch_size,vocab_size,embed_dim,num_hidden,num_steps)
mod = mx.mod.Module(output,data_names=["data"],label_names=["softmax_label"])
model_prefix = 'poem_rnn'
save_period = 1
checkpoint = mx.callback.do_checkpoint(model_prefix,period = save_period)
mod.fit(data_iter,num_epoch=5,epoch_end_callback=checkpoint)
I'am not sure if it is actually the same bug or there is some other bugs in my codes
mod.fit(data_iter,num_epoch=5,epoch_end_callback=checkpoint)
The default evel_metric above is 'acc'. However, when I choose to use other metrics,the error disappear
mod.fit(data_iter, eval_metric='ce', num_epoch=5, epoch_end_callback=checkpoint)
or
mod.fit(data_iter, eval_metric=mx.metric.Perplexity(ignore_label=-1), num_epoch=5, epoch_end_callback=checkpoint)
I think we can avoid this issue by specifying a specific evel_metric.
@helloworldlxb @Matafight this issue should be fix by PR #10446
@sandeep-krishnamurthy Please close this issue as it has been fixed with the PR.
@helloworldlxb @Matafight Please feel free to reopen this issue if you encounter it again.