AssertionError:assert(arg_shapes is not None)
Hello!
I get a error When I try to load my own data into mxnet. But I use another symbol will not get the error except the LSTM symbol.
I am a beginner and can you give me some help?
Thanks a lot!
Error:
File "lstm_ocr5_10.py", line 265, in <module>
batch_end_callback=mx.callback.Speedometer(BATCH_SIZE, 50))
File "../../python/mxnet/model.py", line 745, in fit
self._init_params(dict(data.provide_data+data.provide_label))
File "../../python/mxnet/model.py", line 486, in _init_params
assert(arg_shapes is not None)
AssertionError
This is my code
data_shape = (3, 25, 150)
data_train = mx.io.ImageRecordIter(
path_imgrec = arg_dir + 'train.rec',
path_imglist = arg_dir + 'train.lst',
data_shape = data_shape,
lable_width = 1,
rand_crop=True,
rand_mirror=True,
label_name = 'label',
batch_size = BATCH_SIZE)
data_val = mx.io.ImageRecordIter(
path_imgrec = arg_dir + 'train.rec',
path_imglist = arg_dir + 'train.lst',
data_shape = data_shape,
rand_crop=False,
rand_mirror=False,
lable_width = 1,
batch_size = BATCH_SIZE,
label_name = 'label')
def sym_gen(seq_len):
return lstm_unroll(num_lstm_layer, seq_len,
num_hidden=num_hidden,
num_label = num_label)
SEQ_LENGTH = 1 //when the value > 3 the other error
symbol = sym_gen(SEQ_LENGTH)
model = mx.model.FeedForward(ctx=contexts,
symbol=symbol,
num_epoch=num_epoch,
learning_rate=learning_rate,
momentum=momentum,
wd=0.00001,
initializer=mx.init.Xavier(factor_type="in", magnitude=2.34))
model.fit(X=data_train, eval_data=data_val,
eval_metric = mx.metric.np(Accuracy),
batch_end_callback=mx.callback.Speedometer(BATCH_SIZE, 50))
try mx.module.bucketingmodule
@piiswrong I try to use mx.module.bucketing_module.BucketingModule train my data(image data),but I got a error and I don't find way how to use data_shape and lable_shape.Even I don't know how to load my data(image).The doc example always train words sequence data. error:
Traceback (most recent call last):
File "lstm_ctc_bucket.py", line 90, in <module>
initializer=mx.init.Xavier(factor_type="in", magnitude=2.34))
File "../../python/mxnet/module/base_module.py", line 333, in fit
for_training=True, force_rebind=force_rebind)
File "../../python/mxnet/module/bucketing_module.py", line 181, in bind
force_rebind=False, shared_module=None)
File "../../python/mxnet/module/module.py", line 258, in bind
shared_group, logger=self.logger)
File "../../python/mxnet/module/executor_group.py", line 95, in __init__
self.bind_exec(data_shapes, label_shapes, shared_group)
File "../../python/mxnet/module/executor_group.py", line 123, in bind_exec
self.execs.append(self._bind_ith_exec(i, data_shapes, label_shapes, shared_group))
File "../../python/mxnet/module/executor_group.py", line 322, in _bind_ith_exec
assert arg_shapes is not None, "shape inference failed"
AssertionError: shape inference failed
code:
def sym_gen(seq_len):
sym = lstm_unroll(num_lstm_layer, seq_len,
num_hidden=num_hidden,
num_label=1)
data_names = ['data'] + state_names
label_names = ['label']
return (sym, data_names, label_names)
data_shape = (3, 25, 150)
data_train = mx.io.ImageRecordIter(
path_imgrec = arg_dir + 'train.rec',
path_imglist = arg_dir + 'train.lst',
data_shape = data_shape,
label_shape = data_shape,
lable_width = 4,
label_name = 'label',
batch_size = BATCH_SIZE)
data_val = mx.io.ImageRecordIter(
path_imgrec = arg_dir + 'train.rec',
path_imglist = arg_dir + 'train.lst',
data_shape = data_shape,
label_shape = data_shape,
lable_width = 4,
batch_size = BATCH_SIZE,
label_name = 'label')
mod = mx.module.bucketing_module.BucketingModule(sym_gen,
default_bucket_key = 1,
context = contexts,
)
mod.fit(data_train, eval_data=data_val,
optimizer_params={'learning_rate':0.01, 'momentum': 0.9},
batch_end_callback=mx.callback.Speedometer(BATCH_SIZE, 50),
num_epoch=num_epoch,
initializer=mx.init.Xavier(factor_type="in", magnitude=2.34))
I have the same question. Do you have a solution? How to train my own data in the lstm?
getting the same error. not sure what to do. code below is to do binary addition (from Hinton's course) using RNN network. I don't want to use bucketing module (using NDArrayIter below).
#!/usr/bin/env python
import mxnet as mx
import numpy as np
def create_dataset(nb_samples, sequence_len):
"""Create a dataset for binary addition and return as input, targets."""
max_int = 2**(sequence_len - 1) # Maximum integer that can be added
# Transform integer in binary format
format_str = '{:0' + str(sequence_len) + 'b}'
nb_inputs = 2 # Add 2 binary numbers
nb_outputs = 1 # Result is 1 binary number
X = np.zeros((nb_samples, sequence_len, nb_inputs)) # Input samples
T = np.zeros((nb_samples, sequence_len, nb_outputs)) # Target samples
# Fill up the input and target matrix
for i in xrange(nb_samples):
# Generate random numbers to add
nb1 = np.random.randint(0, max_int)
nb2 = np.random.randint(0, max_int)
# Fill current input and target row.
# Note that binary numbers are added from right to left,
# but our RNN reads from left to right, so reverse the sequence.
X[i, :, 0] = list(reversed([int(b) for b in format_str.format(nb1)]))
X[i, :, 1] = list(reversed([int(b) for b in format_str.format(nb2)]))
T[i, :, 0] = list(reversed([int(b)
for b in format_str.format(nb1 + nb2)]))
return X, T
# Show an example input and target
def printSample(x1, x2, t, y=None):
"""Print a sample in a more visual way."""
x1 = ''.join([str(int(d)) for d in x1])
x2 = ''.join([str(int(d)) for d in x2])
t = ''.join([str(int(d[0])) for d in t])
if y is not None:
y = ''.join([str(int(d[0])) for d in y])
print('x1: {:s} {:2d}'.format(x1, int(''.join(reversed(x1)), 2)))
print('x2: + {:s} {:2d} '.format(x2, int(''.join(reversed(x2)), 2)))
print(' ------- --')
print('t: = {:s} {:2d}'.format(t, int(''.join(reversed(t)), 2)))
if y is not None:
print('y: = {:s} {:2d}'.format(y, int(''.join(reversed(y)), 2)))
print '\n'
def rnn_step(input_, state, wx, wh, b, n_hidden):
# n_hidden = wh.shape[0]
# update
i2h = mx.sym.FullyConnected(data=input_,
weight=wx,
no_bias=True,
num_hidden=n_hidden,
name='i2h')
# memory
h2h = mx.sym.FullyConnected(data=state,
weight=wh,
bias=b,
num_hidden=n_hidden,
name='h2h')
# activation
hidden = mx.sym.Activation(data=i2h + h2h, act_type="tanh")
return hidden
def rnn_unroll(seq_len, n_inputs, n_hidden, n_outputs):
# n_embed = n_inputs
# we = mx.sym.Variable('we')
wx = mx.sym.Variable('wx')
wh = mx.sym.Variable('wh')
b = mx.sym.Variable('b')
wa = mx.sym.Variable('wa')
ba = mx.sym.Variable('ba')
state = mx.sym.Variable('state')
data = mx.sym.Variable('data')
label = mx.sym.Variable('label')
x_mat = mx.sym.SliceChannel(
data=data, num_outputs=seq_len, squeeze_axis=1)
hiddens = []
for i in xrange(seq_len):
state = rnn_step(input_=x_mat[i],
state=state,
wx=wx,
wh=wh,
b=b,
n_hidden=n_hidden)
hiddens.append(state)
hiddens = mx.sym.Concat(*hiddens, dim=0)
fc = mx.sym.FullyConnected(data=hiddens, weight=wa, bias=ba,
num_hidden=n_outputs,
name='pred',
)
sm = mx.sym.SoftmaxOutput(data=fc,
label=label,
# label=mx.sym.Variable('label'),
name='softmax',
)
return sm
def loss_func(Y, T, ep=1e-10):
# import pdb
# pdb.set_trace()
loss = -np.sum(np.multiply(T, np.log(Y + ep)) +
np.multiply((1 - T), np.log(1 - Y + ep))) \
/ (Y.shape[0] * Y.shape[1])
return loss
if __name__ == '__main__':
# Create dataset
nb_train = 2000 # Number of training samples
nb_test = 100
# Addition of 2 n-bit numbers can result in a n+1 bit number
seq_len = 7 # Length of the binary sequence
batch_size = 100
# Create training samples
np.random.seed(seed=2)
X_train, T_train = create_dataset(nb_train, seq_len)
X_test, T_test = create_dataset(nb_test, seq_len)
print('X_train shape: {0}'.format(X_train.shape))
print('T_train shape: {0}'.format(T_train.shape))
# Print the first sample
printSample(X_train[0, :, 0], X_train[0, :, 1], T_train[0, :, :])
train_dataiter = mx.io.NDArrayIter(data=X_train,
label=T_train,
batch_size=batch_size,
label_name='label',
shuffle=True)
test_dataiter = mx.io.NDArrayIter(data=X_test,
label=T_test,
batch_size=batch_size,
shuffle=False)
sym = rnn_unroll(seq_len=seq_len,
n_inputs=2,
n_hidden=3,
n_outputs=1)
model = mx.model.FeedForward( # ctx=contexts,
symbol=sym,
num_epoch=20,
learning_rate=0.05,
momentum=0.8,
)
model.fit(X=train_dataiter) # , eval_data=test_dataiter,
# eval_metric=mx.metric.np(loss_func),
# )
pass
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!