您的位置:首页 > 理论基础 > 计算机网络

深度学习-CAFFE利用CIFAR10网络模型训练自己的图像数据获得模型-4应用生成模型进行预测

2017-03-22 15:48 1226 查看
该步可以分两种情况进行使用:1.使用caffe所提供的
classify.py进行预测;2.使用python代码进行预测

 

1.使用caffe所提供的
classify.py进行预测

在caffe目录下面的python里有一个classify.py,进行分类。但是,好像不太好用,网上有人对代码进行了修改。修改的地方,见以前博客。

 

在终端执行:

python python/classify.py --print_results --model_def examples/testCreateLmDB/my_quick.prototxt --pretrained_model examples/testCreateLmDB/my_quick_iter_4000.caffemodel.h5 --labels_file examples/testCreateLmDB/mylabel.txt --center_only examples/testCreateLmDB/120.jpg foo



2.使用python代码进行预测

import numpy as np
import matplotlib.pyplot as plt

#[1]Load caffe 第一步:导入caffe
# The caffe module needs to be on the Python path;
#  we'll add it here explicitly.
import sys
caffe_root = '/home/lw/caffe/'  # this file should be run from {caffe_root}/examples (otherwise change this line)
sys.path.insert(0, caffe_root + 'python')

import caffe
# If you get "No module named _caffe", either you have not built pycaffe or you have the wrong path.

#[1]Import Net  第二步使用NET,注意相关文件所在路径
caffe.set_mode_gpu()

model_def = caffe_root + 'examples/cifar10/cifar10_quick.prototxt'
model_pretrained = caffe_root + 'examples/cifar10/cifar10_quick_iter_4000.caffemodel.h5'
MEAN_PROTO_PATH = caffe_root+'examples/cifar10/mean.binaryproto' #这里是二进制文件,而不是Python的npy文件
# load the mean ImageNet image (as distributed with Caffe) for subtraction

blob = caffe.proto.caffe_pb2.BlobProto()
data = open(MEAN_PROTO_PATH, 'rb' ).read()
blob.ParseFromString(data)
array = np.array(caffe.io.blobproto_to_array(blob))# 将blob中的均值转换成numpy格式,array的shape (mean_number,channel, hight, width)
mu = array[0]
mean = mu.mean(1).mean(1)  # average over pixels to obtain the mean (BGR) pixel values

#第三步,使用分类器
net = caffe.Classifier(model_def, model_pretrained,mean=mean,
channel_swap=(2,1,0),#RGB通道与BGR
raw_scale=255,#把图片归一化到0~1之间
image_dims=(32, 32))#设置输入图片的大小
#Classifier
label_list=['airplane','automobile','bird','cat','deer','dog','frog','horse','ship','truck']
input_image = caffe.io.load_image(caffe_root + 'examples/images/cat_gray.jpg')#读取图片

#第四步:显示原图片,以及分类预测结果
prediction = net.predict([input_image])#图片分类
str_gender=label_list[prediction[0].argmax()]
print str_gender

print '原数据'
print prediction[0]
print label_list
print

print '排序后的结果'
indices = (-prediction[0]).argsort()   #排序输出数组的下标,前面加负号是降序
meta = [
(label_list[i], '%.5f' % prediction[0][i])
for i in indices
]

print meta

plt.imshow(input_image)
plt.title(str_gender)
plt.show()

print '结束'

执行效果如图所示:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐