Caffe2訓練好的模型可在Model Zoo下載,下載的命令很簡單,接下來以下載和使用squeezenet為例,進行簡單說明。
1.瀏覽可下載的模型
已有模型都放在github上,地址:https://github.com/caffe2/caffe2/wiki/Model-Zoo,當前有caffe和caffe2兩種版本的選擇。
2.選擇下載模型
注意名字為小寫,有些會加下划線,我們這里選擇caffe2的版本
下載並安裝(安裝目錄為/usr/local/caffe2/python/models),命令如下:
python -m caffe2.python.models.download --install squeezenet
有時候需要sudo的權限,則要改為執行如下命令:
sudo PYTHONPATH=/usr/local python -m caffe2.python.models.download --install squeezenet
3.應用模型
我們嘗試從網上下載一些代碼,然后進行預測,在官方代碼的基礎上做了一些改動,代碼如下:
# load up the caffe2 workspace from caffe2.python import workspace # choose your model here (use the downloader first) from caffe2.python.models import squeezenet as mynet # helper image processing functions import caffe2.python.tutorials.helpers as helpers import skimage.io from matplotlib import pyplot as plt # load the pre-trained model init_net = mynet.init_net predict_net = mynet.predict_net # you must name it something predict_net.name = "squeezenet_predict" workspace.RunNetOnce(init_net) workspace.CreateNet(predict_net) p = workspace.Predictor(init_net.SerializeToString(), predict_net.SerializeToString()) # use whatever image you want (local files or urls) #img_pth = "https://upload.wikimedia.org/wikipedia/commons/thumb/7/7b/Orange-Whole-%26-Split.jpg/1200px-Orange-Whole-%26-Split.jpg" #img_pth = "https://upload.wikimedia.org/wikipedia/commons/a/ac/Pretzel.jpg" img_pth = "https://cdn.pixabay.com/photo/2015/02/10/21/28/flower-631765_1280.jpg" # average mean to subtract from the image mean = 128 # the size of images that the model was trained with input_size = 227 # use the image helper to load the image and convert it to NCHW img = helpers.loadToNCHW(img_pth, mean, input_size) # submit the image to net and get a tensor of results results = p.run([img]) response = helpers.parseResults(results) # and lookup our result from the list print response #show result on image img_mat = skimage.io.imread(img_pth) skimage.io.imshow(img_mat) plt.title(response,{'fontsize': '20'}) plt.savefig('pretzel.jpg') plt.show()
注意別忘記把推理的文件inference_codes.txt放在程序的當前目錄
4.結果
對三張圖片分類的結果及其概率如圖所示
5.參考資料
[1].Model Zoo Doc
[2].Model Zoo Github