訓練好caffemodel後,需要測試模型分類的正確率,caffe 有 python接口,可以調用已訓練好的caffemodel測試分類。
有以下幾點需要注意:
1, 需要修改 net.prototxt 文件爲 deploy.prototxt 文件,方法見我的另一個博客。
deploy= '/home/justin/cnn-human/code/deploy.prototxt' #結構文件
2, 圖像的均值文件爲相應的均值文件,這部分也要修改。(如果訓練的時候沒有加入數據的均值文件,測試的時候也不要加入均值文件測試)
transformer.set_mean('data', np.load('/home/justin/cnn-human/data/train/mean.npy').mean(1).mean(1))
3, 下面的image_label.txt文件爲不同圖像和對應的label。
labels = np.loadtxt("/home/justin/cnn-human/data/image_label.txt", str,delimiter='\t')
本次我用到的爲:
0 uwalk
1 unrun
2 boxst
3 boxwa
4 aimwa
5 crawl
4, 其他的部分對比做相應的修改。
# -*- coding: UTF-8 -*-
import os
import caffe
import numpy as np
#root='/home/justin/caffe/'#指定根目錄
deploy= '/home/justin/cnn-human/code/deploy.prototxt' #結構文件
caffe_model= '/home/justin/cnn-human/code/snapshots/_iter_12500.caffemodel'
#已經訓練好的model
dir = '/home/justin/cnn-human/data/testImg' #保存測試圖片的集合
filelist=[]
filenames=os.listdir(dir)
for fn in filenames:
fullfilename = os.path.join(dir,fn)
filelist.append(fullfilename)
#filelist.append(fn)
def Test(img):
#加載模型
net = caffe.Net(deploy,caffe_model,caffe.TEST)
#網絡設置爲測試模式
# 加載輸入和配置預處理
transformer = caffe.io.Transformer({'data':net.blobs['data'].data.shape}) #不懂什麼意思?
transformer.set_mean('data', np.load('/home/justin/cnn-human/data/train/mean.npy').mean(1).mean(1))
#減去均值?
transformer.set_transpose('data', (2,0,1))
#python讀取的圖片文件格式爲H×W×K,需轉化爲K×H×W
transformer.set_channel_swap('data', (2,1,0))
#交換通道,將圖片由RGB變爲BGR(如果是灰度圖片,此處可以註釋,因爲沒有RGB一說,不註釋會報:Exception: Channel swap needs to have the same number of dimensions as the input channels.)
transformer.set_raw_scale('data', 255.0)
#縮放到[0,255]之間
#注意可以調節預處理批次的大小
#由於是處理一張圖片,所以把原來的15張的批次改爲1
net.blobs['data'].reshape(1,3,128,128)
#3通道*128*128
#加載圖片到數據層
im = caffe.io.load_image(img)
#加載圖片(caffe.io.load_image(img,color=False),如果是灰度圖片,此處第二個參數color=False一定要補上,不然默認加載成3通道圖片,會報錯,大致意思就是我們net裏定義的是1通道的,與實際不符。ValueError: could not broadcast input array from shape (3,28,28) into shape (64,1,28,28))
net.blobs['data'].data[...] = transformer.preprocess('data', im)
#執行上面設置的圖片預處理操作,並將圖片載入到blob中
#前向計算
out = net.forward()
# 其他可能的形式 : # out = net.forward_all(data=np.asarray([transformer.preprocess('data', im)]))
#預測分類
print out['prob']
print out['prob'].argmax()
# print("Predicted class is #{}.".format(out['prob'].softmax()))
#打印預測標籤
labels = np.loadtxt("/home/justin/cnn-human/data/image_label.txt", str,delimiter='\t')
top_k = net.blobs['prob'].data[0].flatten().argsort()[-1]
#輸出概率最大的類別的下標
print 'the class is:',labels[top_k]
f=file("/home/justin/cnn-human/data/label.txt","a")
f.writelines(img+' '+labels[top_k]+'\n')
#循環遍歷文件夾root+'examples/images/'下的所有圖片
for i in range(0,len(filelist)):
img=filelist[i]
Test(img)
1,net.blobs[‘data’].data.shape的解釋
2,numpy.loadtxt的解釋
可以參考:
http://blog.csdn.net/baterforyou/article/details/71430284
https://www.cnblogs.com/denny402/p/5111018.html
http://blog.csdn.net/u010925447/article/details/75805474
http://blog.csdn.net/yxq5997/article/details/53780394?utm_source=itdadao&utm_medium=referral