caffe Of python Interface generation deploy file
Trained models caffemodel Classify new pictures
caffe Of python Interface generation deploy fileIf you want to use the trained model to test new pictures , That has to be one deploy.prototxt file , This document is actually related to test.prototxt The documents are almost , It's just that the head and the tail are different .deploy The file has no first layer of data input , There is no final Accuracy layer , But in the end, there was one more Softmax Probability layer .
Here we use code to automatically generate the file , With mnist For example .
deploy.py
# -*- coding: utf-8 -*-from caffe import layers as L,params as P,to_protoroot='/home/xxx/'deploy=root+'mnist/deploy.prototxt' # File save path def create_deploy(): # Without the first floor ,data layer conv1=L.Convolution(bottom='data', kernel_size=5, stride=1,num_output=20, pad=0,weight_filler=dict(type='xavier')) pool1=L.Pooling(conv1, pool=P.Pooling.MAX, kernel_size=2, stride=2) conv2=L.Convolution(pool1, kernel_size=5, stride=1,num_output=50, pad=0,weight_filler=dict(type='xavier')) pool2=L.Pooling(conv2, pool=P.Pooling.MAX, kernel_size=2, stride=2) fc3=L.InnerProduct(pool2, num_output=500,weight_filler=dict(type='xavier')) relu3=L.ReLU(fc3, in_place=True) fc4 = L.InnerProduct(relu3, num_output=10,weight_filler=dict(type='xavier')) # Finally no accuracy layer , But there's one Softmax layer prob=L.Softmax(fc4) return to_proto(prob)def write_deploy(): with open(deploy, 'w') as f: f.write('name:"Lenet"\n') 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(create_deploy()))if __name__ == '__main__': write_deploy()
After running the file , Will be in mnist Under the table of contents , Generate a deploy.prototxt file .
This file is not recommended for code generation , On the contrary, it is troublesome . After you are familiar with it, you can test.prototxt A copy of , Just modify the corresponding places , It is more convenient .
Trained models caffemodel Classify new picturesAfter the previous study , We've trained a caffemodel Model , And created a deploy.prototxt file , Now let's use these two files to classify and predict a new image .
We from mnist Data sets test Focus on a random picture , For experiments .
#coding=utf-8import caffeimport numpy as nproot='/home/xxx/' # root directory deploy=root + 'mnist/deploy.prototxt' #deploy file caffe_model=root + 'mnist/lenet_iter_9380.caffemodel' # Well trained caffemodelimg=root+'mnist/test/5/00008.png' # A random picture to be tested labels_filename = root + 'mnist/test/labels.txt' # Category name file , Convert numeric labels back to category names net = caffe.Net(deploy,caffe_model,caffe.TEST) # load model and network# Picture preprocessing settings transformer = caffe.io.Transformer({'data': net.blobs['data'].data.shape}) # Set the... Of the picture shape Format (1,3,28,28)transformer.set_transpose('data', (2,0,1)) # Change the order of dimensions , From the original picture (28,28,3) Turn into (3,28,28)#transformer.set_mean('data', np.load(mean_file).mean(1).mean(1)) # Subtract the mean , The previous training model did not reduce the mean value , Not here transformer.set_raw_scale('data', 255) # Zoom to 【0,255】 Between transformer.set_channel_swap('data', (2,1,0)) # Switch channels , By the picture RGB Turn into BGRim=caffe.io.load_image(img) # Loading pictures net.blobs['data'].data[...] = transformer.preprocess('data',im) # Perform the image preprocessing operation set above , And load the picture into blob in # Perform the test out = net.forward()labels = np.loadtxt(labels_filename, str, delimiter='\t') # Read the category name file prob= net.blobs['Softmax1'].data[0].flatten() # Take out the last layer (Softmax) The probability value of belonging to a certain category , And print print proborder=prob.argsort()[-1] # Sort the probability values , Take the sequence number of the maximum value print 'the class is:',labels[order] # Convert the sequence number to the corresponding category name , And print
The final output the class is : 5
Correct classification .
If you are predicting multiple pictures , You can write the above file as a function , Then make a cycle prediction .
That's all caffe Of python Interface deploy Generate caffemodel Classify the details of the new picture , More about caffe python Generate deploy Please pay attention to other related articles of software development network for the information of picture classification !