GitHub 代碼地址: https://github.com/HansRen1024/Use-Python-to-call-Caffe-module
一、參數可視化#
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Sun Jul 30 22:15:05 2017
author: hans
"""
import caffe
import numpy as np
import matplotlib.pyplot as plt
def show(data, padsize=1, padval=0):
data = (data - data.min()) / (data.max() - data.min())
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)
plt.axis('off')
plt.show()
prototxt='doc/deploy.prototxt'
caffe_model='animal_iter_120000.caffemodel'
net = caffe.Net(prototxt,caffe_model,caffe.TEST)
for name, param_blob in net.params.items():#查看各層參數規模
print name + '\t' + str(param_blob[0].data.shape), str(param_blob[1].data.shape)
conv1_param=net.params['conv1'][0].data #提取參數w, 參數維度為(n, k, h, w)
show(conv1_param.transpose(0, 2, 3, 1)) # 對於第一層卷積層,轉換參數維度為(n, h, w, k)
#show(conv1_param.reshape(k*n, h, w) # 對於其他層,要用這句代碼。
二、特徵圖可視化#
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Sun Jul 30 22:15:05 2017
author: hans
"""
import caffe
import numpy as np
import matplotlib.pyplot as plt
def show(data, padsize=1, padval=0): # padsize為特徵圖間距
data -= data.min()
data /= data.max()
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)
plt.axis('off')
prototxt='doc/deploy_lenet.prototxt'
caffe_model='models/lenet_iter_10000.caffemodel'
mean_file='doc/mnist_mean.npy'
im = caffe.io.load_image('doc/3.jpg')
im = caffe.io.resize_image(im,(28,28,1))
caffe.set_mode_gpu()
net = caffe.Net(prototxt,caffe_model,caffe.TEST)
transformer = caffe.io.Transformer({'data': net.blobs['data'].data.shape}) #data blob 結構(n, k, h, w)
transformer.set_transpose('data', (2, 0, 1)) #改變圖片維度順序,(h, w, k) -> (k, h, w)
transformer.set_mean('data', np.load(mean_file).mean(1).mean(1))
transformer.set_raw_scale('data', 255)
# transformer.set_channel_swap('data', (2, 1, 0)) # RGB -> BGR
net.blobs['data'].data[...] = transformer.preprocess('data', im)
net.forward()
for name,feature in net.blobs.items(): #查看各層特徵規模
print name + '\t' + str(feature.data.shape)
conv1_data = net.blobs['conv1'].data[0] #提取特徵
show(conv1_data)
prob_data = net.blobs['prob'].data[0] #各類概率分布
prob_data.shape = (len(prob_data),)
plt.figure()
plt.plot(prob_data)