Mxnet图片分类(4)利用训练好的模型进行测试

利用训练好的模型测试只需要把模型和数据准备好。

系统: ubuntu14.04
Mxnet: 0.904

1.模型和数据准备

这里写图片描述

这里写图片描述

2.模型加载测试

import mxnet as mx
sym,arg_params,aux_params = mx.model.load_checkpoint('vggnew',40)
mod = mx.mod.Module(symbol=sym,context=mx.gpu(),data_names=['data'],label_names=['softmax_label'])
mod.bind(for_training=False,data_shapes=[('data',(1,3,224,224))])
mod.set_params(arg_params,aux_params)

需要输出标签还要准备一个synset.txt文件,格式如图:
这里写图片描述

with open('synset.txt','r') as f:
    labels = [l.rstrip() for l in f]

对图片进行处理

%matplotlib inline
import matplotlib.pyplot as plt
import cv2
import numpy as np
# define a simple data batch
from collections import namedtuple
Batch = namedtuple('Batch', ['data'])

def get_image(url, show=False):
    #url:图片路径
    #show:是否显示图片
    img = cv2.cvtColor(cv2.imread(url), cv2.COLOR_BGR2RGB)
    if img is None:
         return None
    if show:
         plt.imshow(img)
         plt.axis('off')
    # convert into format (batch, RGB, width, height)
    img = cv2.resize(img, (224, 224))
    img = np.swapaxes(img, 0, 2)
    img = np.swapaxes(img, 1, 2)
    img = img[np.newaxis, :]
    return img

def predict(url):
    img = get_image(url, show=True)
    # compute the predict probabilities
    mod.forward(Batch([mx.nd.array(img)]))
    prob = mod.get_outputs()[0].asnumpy()
    # print the top-5
    prob = np.squeeze(prob)
    prob = np.argsort(prob)[::-1]
    top1=prob[0]#取概率最高的一类
    print top1  #输入类别
    print labels[top1] #输出标签
#批量测试
path = '/mxnet/tools/train-cat/2'
import os 
for lists in os.listdir(path):
    image = os.path.join(path,lists)
    predict(image)

这里写图片描述

参考文献:

[1]http://mxnet.io/api/python/model.html?highlight=predict#mxnet.model.FeedForward.predict
[2]http://mxnet.io/tutorials/python/predict_image.html?highlight=predict

模型的训练可以参考

  1. Mxnet图片分类(2)训练模型
  2. Mxnet图片分类(3)fine-tune
  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值