Help with prediction using pretained resnet model

Hello guys,

I am trying to predict from an URL using the method from pretrained model for resnet (https://mxnet.incubator.apache.org/tutorials/python/predict_image.html). I modified the code to fit my parameters from the trained dataset.

The code is below:

Load the model:
symbol, arg_params, aux_params = mx.model.load_checkpoint(‘food_classification_resnet-18’,30)
net = mx.mod.Module(symbol=symbol, context=ctx)
net.bind(for_training=False, data_shapes=[(‘data’, (1,3,299,299))],
label_shapes=train_itr.provide_label)
net.set_params(arg_params, aux_params)

Predict:
%matplotlib inline

import urllib.request
from collections import namedtuple

Batch = namedtuple(‘Batch’, [‘data’])

with open(‘classes.txt’, ‘r’) as f:
labels = [l.rstrip() for l in f]

def get_image(url, show=False):
# download and show the image
fname = mx.test_utils.download(url)
img = mx.image.imread(fname)
if img is None:
return None
if show:
plt.imshow(img.asnumpy())
plt.axis(‘off’)
# convert into format (batch, RGB, width, height)
img = mx.image.imresize(img, 299, 299) # resize
img = img.transpose((1,2,0)) # Channel first
img = img.expand_dims(axis=0) # batchify
return img

def predict(url):
img = get_image(url, show=True)

net.forward(Batch([img]))

prob = net.get_outputs()[0].asnumpy()
# print the top-5
prob = np.squeeze(prob)
a = np.argsort(prob)[::-1]
for i in a[0:5]:
    print('probability: %f' %(prob[i], labels[i]))

The error I am getting is:


TypeError Traceback (most recent call last)
in ()
----> 1 predict(‘http://www.sakinahalalgrill.com/wp-content/uploads/2018/04/chicken-samosa.jpg’)

in predict(url)
32 a = np.argsort(prob)[::-1]
33 for i in a[0:5]:
—> 34 print(‘probability: %f’ %(prob[i], labels[i]))

TypeError: not all arguments converted during string formatting.

Can I get help on this error. Really appreciate any help with this error.

Srinivas

hi,

your error is in our print statement print('probability: %f' %(prob[i], labels[i])). You have two arguments: prob[i] and labels[i] but only one place holder.

Perhaps you want something like print('probability of label %s: %f' %(prob[i], labels[i])).

Hi

Thank you for the reply. After modification of the above print statement. I encountered another error with net.forward(Batch([img])) command. How do I resolve this index error.

please find the error below:

IndexError Traceback (most recent call last)
in ()
----> 1 predict(‘http://www.sakinahalalgrill.com/wp-content/uploads/2018/04/chicken-samosa.jpg’)

in predict(url)
26 def predict(url):
27 img = get_image(url, show=True)
—> 28 net.forward(Batch([img]))
29 prob = net.get_outputs()[0].asnumpy()
30 # print the top-5

~/anaconda3/envs/mxnet_p36/lib/python3.6/site-packages/mxnet/module/module.py in forward(self, data_batch, is_train)
608 self.reshape(new_dshape, new_lshape)
609
–> 610 self._exec_group.forward(data_batch, is_train)
611
612 def backward(self, out_grads=None):

~/anaconda3/envs/mxnet_p36/lib/python3.6/site-packages/mxnet/module/executor_group.py in forward(self, data_batch, is_train)
433
434 “”"
–> 435 _load_data(data_batch, self.data_arrays, self.data_layouts)
436 if is_train is None:
437 is_train = self.for_training

~/anaconda3/envs/mxnet_p36/lib/python3.6/site-packages/mxnet/module/executor_group.py in _load_data(batch, targets, major_axis)
65 def _load_data(batch, targets, major_axis):
66 “”“Load data into sliced arrays.”""
—> 67 _load_general(batch.data, targets, major_axis)
68
69

~/anaconda3/envs/mxnet_p36/lib/python3.6/site-packages/mxnet/module/executor_group.py in _load_general(data, targets, major_axis)
46 if do_crop:
47 if axis == 0:
—> 48 d_src[slice_idx.start:slice_idx.stop].copyto(d_dst)
49 else:
50 if d_src.context == d_dst.context:

~/anaconda3/envs/mxnet_p36/lib/python3.6/site-packages/mxnet/ndarray/ndarray.py in getitem(self, key)
497 indexing_dispatch_code = _get_indexing_dispatch_code(key)
498 if indexing_dispatch_code == _NDARRAY_BASIC_INDEXING:
–> 499 return self._get_nd_basic_indexing(key)
500 elif indexing_dispatch_code == _NDARRAY_ADVANCED_INDEXING:
501 return self._get_nd_advanced_indexing(key)

~/anaconda3/envs/mxnet_p36/lib/python3.6/site-packages/mxnet/ndarray/ndarray.py in _get_nd_basic_indexing(self, key)
772 return op.slice(self, begin=(key.start,), end=(key.stop,), step=(key.step,))
773 elif key.start is not None or key.stop is not None:
–> 774 return self._slice(key.start, key.stop)
775 else:
776 return self

~/anaconda3/envs/mxnet_p36/lib/python3.6/site-packages/mxnet/ndarray/ndarray.py in _slice(self, start, stop)
887 “”"
888 handle = NDArrayHandle()
–> 889 start, stop, _ = _get_index_range(start, stop, self.shape[0])
890
891 check_call(_LIB.MXNDArraySlice(

~/anaconda3/envs/mxnet_p36/lib/python3.6/site-packages/mxnet/ndarray/ndarray.py in _get_index_range(start, stop, length, step)
2081 raise IndexError(‘Slicing stop %d exceeds limit of %d’ % (stop-length, length))
2082 elif stop > length:
-> 2083 raise IndexError(‘Slicing stop %d exceeds limit of %d’ % (stop, length))
2084
2085 return start, stop, step

IndexError: Slicing stop 100 exceeds limit of 1