Classifying ImageNet: the instant Caffe way
本文主要参考http://nbviewer.ipython.org/github/BVLC/caffe/blob/master/examples/classification.ipynb,主要介绍如何通过已经学习到的模型来进行分类,分类是在ImageNet数据集上进行的,如何训练模型可参考博文 Caffe初识,揭开面纱 (三、caffe中比较有用且基础的接口)。
1、我们需要通过预先训练的模型及网络结果来加载分类器,因此先设置相关文件路径
import numpy as np import matplotlib.pyplot as plt %matplotlib inline # Make sure that caffe is on the python path: caffe_root = '/home/ring/Documents/caffe-master/' # 最好写绝对路径 import sys sys.path.insert(0, caffe_root + 'python') import caffe # Set the right path to your model definition file, pretrained model weights, # and the image you would like to classify. MODEL_FILE = caffe_root + 'models/bvlc_reference_caffenet/deploy.prototxt' PRETRAINED = caffe_root + 'models/bvlc_reference_caffenet/bvlc_reference_caffenet.caffemodel' IMAGE_FILE = caffe_root + 'examples/images/cat.jpg' # 加载自己的图片
2、加载分类器
net = caffe.Classifier(.....) 获取分类器
net.set_phase_test() 设置为测试阶段,训练阶段与测试阶段模型稍有不同,比如训练阶段最后一层是LOSS,而测试阶段最后一层是Accuracy
net.set_mode_cpu() 仅使用cpu , 通过net.set_mode_gpu()设置gpu模式
注:教程中使用caffe.set_phase_test() , caffe.set_mode_cpu(),这样会报错,作者在后面的教程中有更正,使用如下方法
net = caffe.Classifier(MODEL_FILE, PRETRAINED, mean=np.load(caffe_root + 'python/caffe/imagenet/ilsvrc_2012_mean.npy'), channel_swap=(2,1,0), raw_scale=255, image_dims=(256, 256))
net.set_phase_test()
net.set_mode_cpu()
3、加载测试图片并显示
input_image = caffe.io.load_image(IMAGE_FILE)
plt.imshow(input_image)
4、预测,显示每一类的score
prediction = net.predict([input_image]) # predict takes any number of images, and formats them for the Caffe net automatically print 'prediction shape:', prediction[0].shape plt.plot(prediction[0]) print 'predicted class:', prediction[0].argmax()
prediction shape: (1000) predicted class: 281
结果为1000维,因为imageNet有1000类

浙公网安备 33010602011771号