<jupyter_start><jupyter_text>Predict with pre-trained modelsThis is a demo for predicting with a pre-trained model on the full imagenet dataset, which contains over 10 million images and 10 thousands classes. For a more detailed explanation, please refer to [predict.ipynb](https://github.com/dmlc/mxnet-notebooks/blob/master/python/how_to/predict.ipynb).We first load the synset label file and pre-trained model.<jupyter_code>import os, urllib
import mxnet as mx
from modelzoo import download_model

def download(url,prefix=''):
    filename = prefix+url.split("/")[-1]
    if not os.path.exists(filename):
        urllib.urlretrieve(url, filename)
        
def load_model(model_name):
    (prefix, epoch) = download_model(model_name, dst_dir='models')
    sym, arg_params, aux_params = mx.model.load_checkpoint(prefix, epoch)
    mod = mx.mod.Module(symbol=sym, context=mx.gpu())
    mod.bind(for_training=False, data_shapes=[('data', (1,3,224,224))])
    mod.set_params(arg_params, aux_params)
    return (sym, mod)

# first download synset labels
download('http://data.mxnet.io/models/imagenet/synset.txt', 'imagenet-')
download('http://data.mxnet.io/models/imagenet-11k/synset.txt', 'imagenet-11k-')
with open('imagenet-synset.txt', 'r') as f:
    imagenet_synsets = [l.rstrip() for l in f]
with open('imagenet-11k-synset.txt', 'r') as f:
    imagenet_11k_synsets = [l.rstrip() for l in f]

# load resnet model
resnet, resnet_mod = load_model('imagenet1k-resnet-50')
#resnet, resnet_mod = load_model('imagenet11k-resnet-152')<jupyter_output><empty_output><jupyter_text>Visualize the ResNet.<jupyter_code>mx.viz.plot_network(resnet)<jupyter_output><empty_output><jupyter_text>Next we define the function to obtain an image by a given URL and the function for predicting.<jupyter_code>%matplotlib inline
import matplotlib
matplotlib.rc("savefig", dpi=100)
import matplotlib.pyplot as plt
import cv2
import numpy as np
from collections import namedtuple
Batch = namedtuple('Batch', ['data'])

def get_image(url, show=True):
    filename = url.split("/")[-1]
    urllib.urlretrieve(url, filename)
    img = cv2.imread(filename)
    if img is None:
        print('failed to download ' + url)
    if show:
        plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
        plt.axis('off')
    return filename

def predict(filename, mod, synsets):
    img = cv2.cvtColor(cv2.imread(filename), cv2.COLOR_BGR2RGB)
    if img is None:
        return None
    img = cv2.resize(img, (224, 224))
    img = np.swapaxes(img, 0, 2)
    img = np.swapaxes(img, 1, 2) 
    img = img[np.newaxis, :] 
    
    mod.forward(Batch([mx.nd.array(img)]))
    prob = mod.get_outputs()[0].asnumpy()
    prob = np.squeeze(prob)

    a = np.argsort(prob)[::-1]    
    for i in a[0:5]:
        print('probability=%f, class=%s' %(prob[i], synsets[i]))<jupyter_output><empty_output><jupyter_text>We are able to classify an image and output the top predicted classes.<jupyter_code>url = 'http://writm.com/wp-content/uploads/2016/08/Cat-hd-wallpapers.jpg'
predict(get_image(url), resnet_mod, imagenet_synsets)
url = 'https://images-na.ssl-images-amazon.com/images/G/01/img15/pet-products/small-tiles/23695_pets_vertical_store_dogs_small_tile_8._CB312176604_.jpg'
predict(get_image(url), resnet_mod, imagenet_synsets)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.13488231744115872, 'fraction_numerical': 0.024743512371756187, 'mean_word_length': 4.656996587030717, 'pattern_counts': {'":': 0, '<': 17, '<?xml version=': 0, '>': 17, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 7, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '4', 'dir': 'jupyter-structured-clean-dedup', 'id': '212304', 'license': 'Apache-2.0', 'n_tokens_mistral': 1247, 'n_tokens_neox': 1198, 'n_words': 254, 'path': 'lab1/cnn/predict_imagenet.ipynb', 'repo_name': 'ysh329/dlsys', 'size': '3314'}