本文主体来自[Caffe学习系列(17):模型各层数据和参数可视化],加了一点自己的注释(http://www.cnblogs.com/denny402/p/5105911.html)
先用caffe对cifar10进行训练,将训练的结果模型进行保存,得到一个caffemodel,然后从测试图片中选出一张进行测试,并进行可视化。
# 加载必要的库
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline # 在notebook里面显示图像
import sys, os, caffe
# 设置当前目录,判断模型是否训练好
caffe_root = '/home/huitr/caffe/'
os.chdir(caffe_root)
if not os.path.isfile(caffe_root + 'examples/cifar10/cifar10_quick_iter_4000.caffemodel'):
print("caffemodel is not exist...")
# 利用提前训练好的模型,设置测试网络
caffe.set_mode_gpu()
net = caffe.Net(caffe_root + 'examples/cifar10/cifar10_quick.prototxt',
caffe_root + 'examples/cifar10/cifar10_quick_iter_4000.caffemodel',
caffe.TEST)
print net.blobs['data'].data.shape
print type(net.blobs['data']) # 键data所对应的值就是Blob,不是BlobVector,注意和params区分
print type(net.blobs['data'].data) # Blob.data得到的是numpy.ndarray
(1, 3, 32, 32)
<class 'caffe._caffe.Blob'>
<type 'numpy.ndarray'>
#加载测试图片,并显示
img = caffe.io.load_image('examples/images/cat.jpg')
print img.shape
plt.imshow(img)
plt.axis('off')
(360, 480, 3)
(-0.5, 479.5, 359.5, -0.5)
# 编写一个函数,将二进制的均值转换为python的均值
def convert_mean(binMean,npyMean):
blob = caffe.proto.caffe_pb2.BlobProto() # 声明一个blob
bin_mean = open(binMean, 'rb' ).read() # 打开二进制均值文件
blob.ParseFromString(bin_mean) # 将二进制均值文件读入blob
arr = np.array( caffe.io.blobproto_to_array(blob) ) # 将blob转成numpy array
npy_mean = arr[0]
print arr.shape # arr是4维array,第一维表示第一张图,其实就是唯一一张均值图
np.save(npyMean, npy_mean )
binMean = caffe_root + 'examples/cifar10/mean.binaryproto'
npyMean = caffe_root + 'examples/cifar10/mean.npy'
convert_mean(binMean,npyMean)
(1, 3, 32, 32)
# 定义转换,即预处理函数
# caffe中用的图像是BGR空间,但是matplotlib用的是RGB空间;
# 再比如caffe的数值空间是[0,255]但是matplotlib的空间是[0,1]。这些都需要转换过来
# 预处理函数应该自动resize了测试图片的大小
mu = np.load(npyMean) # 载入均值文件
mu = mu.mean(1).mean(1) # 计算像素的平均值
transformer = caffe.io.Transformer({'data': net.blobs['data'].data.shape}) # 定义转换输入的data数值的函数
transformer.set_transpose('data', (2,0,1)) # 把通道那一维放到最前面以适应caffe,即HxWxC变为CxHxW
transformer.set_mean('data', mu) # 减去均值
transformer.set_raw_scale('data', 255) # 将0-1空间变成0-255空间
transformer.set_channel_swap('data', (2,1,0)) # 将RGB空间转换为BGR空间
net.blobs['data'].data[...] = transformer.preprocess('data',img)
inputData=net.blobs['data'].data
#显示减去均值前后的数据
plt.figure()
plt.subplot(1,2,1),plt.title("origin")
plt.imshow(img)
plt.axis('off')
plt.subplot(1,2,2),plt.title("subtract mean")
plt.imshow(transformer.deprocess('data', inputData[0]))
plt.axis('off')
(-0.5, 31.5, 31.5, -0.5)
# 运行测试模型,并显示各层数据信息
net.forward()
[(k, v.data.shape) for k, v in net.blobs.items()]
[('data', (1, 3, 32, 32)),
('conv1', (1, 32, 32, 32)),
('pool1', (1, 32, 16, 16)),
('conv2', (1, 32, 16, 16)),
('pool2', (1, 32, 8, 8)),
('conv3', (1, 64, 8, 8)),
('pool3', (1, 64, 4, 4)),
('ip1', (1, 64)),
('ip2', (1, 10)),
('prob', (1, 10))]
# 显示各层的参数信息,只显示weight
[(k, v[0].data.shape) for k, v in net.params.items()]
[('conv1', (32, 3, 5, 5)),
('conv2', (32, 32, 5, 5)),
('conv3', (64, 32, 5, 5)),
('ip1', (64, 1024)),
('ip2', (10, 64))]
# 编写一个函数,用于显示各层数据
def show_data(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))
# tile the filters into an image
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.figure()
plt.imshow(data,cmap='gray')
plt.axis('off')
plt.rcParams['figure.figsize'] = (8, 8) # 显示图像的最大范围
plt.rcParams['image.interpolation'] = 'nearest' # 插值方式
plt.rcParams['image.cmap'] = 'gray' # 灰度空间
# 显示第一个卷积层的输出数据和权值(filter)
show_data(net.blobs['conv1'].data[0]) # net.blobs['conv1'].data其实就是经过conv1卷积后的feature maps
print net.blobs['conv1'].data.shape
show_data(net.params['conv1'][0].data.reshape(32*3,5,5))
print net.params['conv1'][0].data.shape
(1, 32, 32, 32)
(32, 3, 5, 5)
# 显示第一次pooling后的输出数据
show_data(net.blobs['pool1'].data[0])
net.blobs['pool1'].data.shape
(1, 32, 16, 16)
# 显示第二次卷积后的输出数据以及相应的权值(filter)
show_data(net.blobs['conv2'].data[0],padval=0.5)
print net.blobs['conv2'].data.shape
show_data(net.params['conv2'][0].data.reshape(32**2,5,5))
print net.params['conv2'][0].data.shape
(1, 32, 16, 16)
(32, 32, 5, 5)
# 显示第三次卷积后的输出数据以及相应的权值(filter),取前1024个进行显示
show_data(net.blobs['conv3'].data[0],padval=0.5)
print net.blobs['conv3'].data.shape
show_data(net.params['conv3'][0].data.reshape(64*32,5,5)[:1024])
print net.params['conv3'][0].data.shape
(1, 64, 8, 8)
(64, 32, 5, 5)
# 显示第三次池化后的输出数据
show_data(net.blobs['pool3'].data[0],padval=0.2)
print net.blobs['pool3'].data.shape
(1, 64, 4, 4)
# 最后一层输出的是测试图片属于某个类的概率
feat = net.blobs['prob'].data[0]
print feat
plt.plot(feat.flat)
[ 5.16919652e-03 9.77844349e-04 1.36706114e-01 5.60458541e-01
1.42503247e-01 6.61528260e-02 3.86934169e-03 3.14827710e-02
1.05555431e-04 5.25745414e-02]
[<matplotlib.lines.Line2D at 0x7fb87074acd0>]