基于caffe特征可视化 以及 用训练好的模型进行分类 2

1。参考官网imagenet的实现过程: http://nbviewer.ipython.org/github/BVLC/caffe/blob/master/examples/00-classification.ipynb

2。修改位置:

1)deploy.prototxt 的路径,以及该文件中参数的设置:a) input_dim: 分别为 1 3 227 227; 输入图片数目,通道数,高,宽。b) layer: fc8中 output_num : 2.

2)_iter_1000.caffemodel 的路径,该文件为使用自己的数据训练出来的caffe模型。

3)mean.npy 的路径,训练过程中只生成了 imagenet_mean.binaryproto文件,因此需要通过 CAFFE/ npy_generate.ipynb 程序将.binaryproto转为.npy格式。具体实现过程参考 http://blog.csdn.net/baobei0112/article/details/47334641

4)synset_words.txt 的路径,该文件也需要自己建立,内容很简单: 类别id 类别name

0 cardata

1 negdata


下面给出整个实现程序:

=============

import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
caffe_root = '/home/wanghl/CAFFE/'# this file is expected to be in {caffe_root}/examples
import sys
sys.path.insert(0, caffe_root + 'python')
import caffe

# Set the right path to your model definition file, pretrained model weights,
#设置好模型路径,和想分类的图像
# and the image you would like to classify.
#MODEL_FILE = caffe_root+'examples/imagenet/imagenet_deploy.prototxt'
#PRETRAINED = caffe_root+'examples/imagenet/caffe_reference_imagenet_model'
MODEL_FILE = caffe_root+'data/data_my2/commod_file/deploy.prototxt'
PRETRAINED = caffe_root+'data/data_my2/commod_file/_iter_1000.caffemodel'

caffe.set_mode_cpu()
#net = caffe.Net(caffe_root + 'models/bvlc_reference_caffenet/deploy.prototxt',
#                caffe_root + 'models/bvlc_reference_caffenet/bvlc_reference_caffenet.caffemodel',
#                caffe.TEST)

net = caffe.Net(MODEL_FILE, PRETRAINED,caffe.TEST)

# input preprocessing: 'data' is the name of the input blob == net.inputs[0]
transformer = caffe.io.Transformer({'data': net.blobs['data'].data.shape})
transformer.set_transpose('data', (2,0,1))
transformer.set_mean('data', np.load(caffe_root + 'data/data_my2/mean.npy').mean(1).mean(1)) # mean pixel
transformer.set_raw_scale('data', 255)  # the reference model operates on images in [0,255] range instead of [0,1]
transformer.set_channel_swap('data', (2,1,0))  # the reference model has channels in BGR order instead of RGB

net = caffe.Classifier(MODEL_FILE, PRETRAINED, mean=np.load(caffe_root + 'data/data_my2/mean.npy').mean(1).mean(1), channel_swap=(2,1,0), raw_scale=255,image_dims=(256, 256))

imagenet_labels_filename = caffe_root + 'data/data_my2/commod_file/synset_words.txt'
labels = np.loadtxt(imagenet_labels_filename, str, delimiter='\t')

IMAGE_FILE = caffe_root+'data/data_my2/1362383003_t.0.jpg.0.jpg'
input_image = caffe.io.load_image(IMAGE_FILE)
plt.imshow(input_image)
#plt.show()


IMAGE_FILE = caffe_root+'data/data_my2/1362383003_t.0.jpg.0.jpg'
input_image = caffe.io.load_image(IMAGE_FILE)
plt.imshow(input_image)
#plt.show()

prediction = net.predict([input_image])

print 'predicted class:',prediction[0].argmax()
top_k = net.blobs['prob'].data[0].flatten().argsort()[-1:-6:-1]
print labels[top_k]

[(k, v.data.shape) for k, v in net.blobs.items()]
[(k, v[0].data.shape) for k, v in net.params.items()]

def showimage(input_image):
    if input_image.ndim == 3:
        m = input_image[:, :, ::-1]
    plt.imshow(input_image)
    

#定义函数vis_square
def vis_square(data, padsize=1, padval=0):
    data -= data.min()
    data /= data.max()
    # force the number of filters to be square
    n = int(np.ceil(np.sqrt(data.shape[0])))
    padding = ((0, n ** 2 - data.shape[0]), (0, padsize), (0, padsize)) + ((0, 0),) * (data.ndim - 3)
    data = np.pad(data, padding, mode='constant', constant_values=(padval, padval))
    # 对图像使用滤波器
    data = data.reshape((n, n) + data.shape[1:]).transpose((0, 2, 1, 3) + tuple(range(4, data.ndim + 1)))
    data = data.reshape((n * data.shape[1], n * data.shape[3]) + data.shape[4:])
    plt.imshow(data)
    
    
conv1 = net.blobs['conv1']
conv1_data = conv1.data[0,:]
vis_square(conv1_data,padval=1)
plt.show()

res = conv1_data[84:85,:]
vis_square(res,padval=1)
plt.show()



你可能感兴趣的:(基于caffe特征可视化 以及 用训练好的模型进行分类 2)