千家信息网

如何使用训练好的model做预测

发表于:2025-02-03 作者:千家信息网编辑
千家信息网最后更新 2025年02月03日,这期内容当中小编将会给大家带来有关如何使用训练好的model做预测,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。Python版本: Python2.7运行平台: U
千家信息网最后更新 2025年02月03日如何使用训练好的model做预测

这期内容当中小编将会给大家带来有关如何使用训练好的model做预测,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。

Python版本: Python2.7
运行平台: Ubuntu14.04

一、前言

在之前的笔记中,已经生成了训练好的mnist.cafffemodel,接下来我们就可以利用这个model做预测了。在这之前,我们还需要一个文件:deploy.prototxt。那么,就让我们从deploy.prototxt开始说起。

二、deploy.prototxt

deploy.prototxt文件和train.prototxt相似,区别在于第一层的输入数据层被删除,然后添加一个数据维度的描述。同时,移除了最后的"loss"和"accurary"层,加入"prob"层,也就是一个Softmax概率层。

1.第一层数据维度描述如下:

  • input:"data" 对输入数据维度进行描述;

  • input_dim:1 表示对待识别样本进行数据增广的数量,该值的大小可自行定义。但一般会进行5次crop,将整幅图像分为多个flip。该值为10则表示会将待识别的样本分为10部分输入到网络进行识别。如果相对整幅图像进行识别而不进行图像数据增广,则可将该值设置为1;

  • input_dim:3 该值表示处理的图像的通道数,若图像为RGB图像则通道数为3,设置该值为3;若图像为灰度图,通道数为1则设置该值为1;

  • input_dim:28 图像的长度,可以通过网络配置文件中的数据层中的crop_size来获取;

  • input_dim:28 图像的宽度,可以通过网络配置文件中的数据层中的crop_size来获取。

2.最后一层"prob"层:

3.编写代码:

# -*- coding: UTF-8 -*-import caffe      def creat_deploy():net = caffe.NetSpec()    net.conv1 = caffe.layers.Convolution(bottom = 'data', kernel_size = 5, num_output = 20,                                         weight_filler = dict(type = 'xavier'))    net.pool1 = caffe.layers.Pooling(net.conv1, kernel_size = 2, stride = 2,                                     pool = caffe.params.Pooling.MAX)    net.conv2 = caffe.layers.Convolution(net.pool1, kernel_size = 5, num_output = 50,                                         weight_filler = dict(type = 'xavier'))    net.pool2 = caffe.layers.Pooling(net.conv2, kernel_size = 2, stride = 2,                                     pool = caffe.params.Pooling.MAX)    net.fc1 =   caffe.layers.InnerProduct(net.pool2, num_output = 500,                                          weight_filler = dict(type = 'xavier'))    net.relu1 = caffe.layers.ReLU(net.fc1, in_place = True)    net.score = caffe.layers.InnerProduct(net.relu1, num_output = 10,                                          weight_filler = dict(type = 'xavier'))    net.prob = caffe.layers.Softmax(net.score)return net.to_proto()def write_net(deploy_proto):#写入deploy.prototxt文件with open(deploy_proto, 'w') as f:#写入第一层数据描述f.write('input:"data"\n')        f.write('input_dim:1\n')        f.write('input_dim:3\n')        f.write('input_dim:28\n')        f.write('input_dim:28\n')        f.write(str(creat_deploy()))if __name__ == '__main__':     my_project_root = "/home/Jack-Cui/caffe-master/my-caffe-project/"       deploy_proto = my_project_root + "mnist/deploy.prototxt"       write_net(deploy_proto)

4.deploy.prototxt生成的内容如下:

input:"data"input_dim:1input_dim:3input_dim:28input_dim:28layer {  name: "conv1"  type: "Convolution"  bottom: "data"  top: "conv1"  convolution_param {    num_output: 20kernel_size: 5weight_filler {      type: "xavier"}  }}layer {  name: "pool1"  type: "Pooling"  bottom: "conv1"  top: "pool1"  pooling_param {    pool: MAX    kernel_size: 2stride: 2  }}layer {  name: "conv2"  type: "Convolution"  bottom: "pool1"  top: "conv2"  convolution_param {    num_output: 50kernel_size: 5weight_filler {      type: "xavier"}  }}layer {  name: "pool2"  type: "Pooling"  bottom: "conv2"  top: "pool2"  pooling_param {    pool: MAX    kernel_size: 2stride: 2  }}layer {  name: "fc1"  type: "InnerProduct"  bottom: "pool2"  top: "fc1"  inner_product_param {    num_output: 500weight_filler {      type: "xavier"}  }}layer {  name: "relu1"  type: "ReLU"  bottom: "fc1"  top: "fc1"}layer {  name: "score"  type: "InnerProduct"  bottom: "fc1"  top: "score"  inner_product_param {    num_output: 10weight_filler {      type: "xavier"}  }}layer {  name: "prob"  type: "Softmax"  bottom: "score"  top: "prob"}

三、预测

运行上述代码,就可在my-caffe-project/mnist目录下生成deploy.prototxt文件,生成的deploy.prototxt文件即可用于使用训练好的模型做预测,如下图所示:

上个笔记中训练生成的模型在my-caffe-project目录下,如下图所示:

现在就可以使用deploy.prototxt和mnist_iter_9380.caffemodel做预测了,编写代码如下:

# -*- coding: UTF-8 -*-import caffe                                                     import numpy as npdef test(my_project_root, deploy_proto):caffe_model = my_project_root + 'mnist_iter_9380.caffemodel'        #caffe_model文件的位置img = my_project_root + 'mnist/test/6/09269.png'                    #随机找的一张待测图片labels_filename = my_project_root + 'mnist/test/labels.txt'            #类别名称文件,将数字标签转换回类别名称net = caffe.Net(deploy_proto, caffe_model, caffe.TEST)                #加载model和deploy#图片预处理设置transformer = caffe.io.Transformer({      'data': net.blobs['data'].data.shape})  #设定图片的shape格式(1,3,28,28)transformer.set_transpose('data', (2,0,1))                            #改变维度的顺序,由原始图片(28,28,3)变为(3,28,28)transformer.set_raw_scale('data', 255)                                # 缩放到【0,255】之间transformer.set_channel_swap('data', (2,1,0))                       #交换通道,将图片由RGB变为BGRim = caffe.io.load_image(img)                                       #加载图片net.blobs['data'].data[...] = transformer.preprocess('data',im)     #执行上面设置的图片预处理操作,并将图片载入到blob中out = net.forward()                                                    #执行测试labels = np.loadtxt(labels_filename, str, delimiter='\t')           #读取类别名称文件prob = net.blobs['prob'].data[0].flatten()                             #取出最后一层(Softmax)属于某个类别的概率值order = prob.argsort()[-1]                                          #将概率值排序,取出最大值所在的序号print '图片数字为:',labels[order]                                   #将该序号转换成对应的类别名称,并打印if __name__ == '__main__':    my_project_root = "/home/Jack-Cui/caffe-master/my-caffe-project/"    #my-caffe-project目录deploy_proto = my_project_root + "mnist/deploy.prototxt"            #保存deploy.prototxt文件的位置test(my_project_root, deploy_proto)

运行结果如下:

可以看到结果正确无误,我随机选取的待测图片就是数字6(mnist/test/6/09269.png)。

上述就是小编为大家分享的如何使用训练好的model做预测了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注行业资讯频道。

0