1. 程式人生 > >caffe windows 視覺化

caffe windows 視覺化

我是使用cmake的方法進行的caffe的編譯,可以看我之前的部落格。將caffe目錄下的python資料夾中的caffe資料夾拷貝到python\Lib\site-packages路徑下。然後在import caffe,出現的一般是升級之類的問題,按照要求解決就行了。
之後在spyder中就行模型的視覺化。程式碼內容主要是依據caffe官方的教程而來,添加了mean檔案的轉化函式。對於自己的網路需要修改的引數部分。
`import numpy as np
import matplotlib.pyplot as plt
#%matplotlib inline

plt.rcParams[‘figure.figsize’] = (10, 10) # large images
plt.rcParams[‘image.interpolation’] = ‘nearest’ # 不插值:顯示方形畫素
plt.rcParams[‘image.cmap’] = ‘gray’ # 使用灰度輸出

import sys
caffe_root = ‘E:/caffe’
sys.path.insert(0, caffe_root + ‘python’)
import caffe

# 將二進位制的均值轉換為python的均值
def convert_mean(binMean,npyMean):
blob = caffe.proto.caffe_pb2.BlobProto()
bin_mean = open(binMean, ‘rb’ ).read()
blob.ParseFromString(bin_mean)
arr = np.array( caffe.io.blobproto_to_array(blob) )
npy_mean = arr[0]
np.save(npyMean, npy_mean )

caffe.set_mode_cpu()
#以下引數根據實際情況進行修改
#model_def = caffe_root + ‘/models/bvlc_reference_caffenet/deploy.prototxt’
#model_weights = caffe_root + ‘/models/bvlc_reference_caffenet/bvlc_reference_caffenet.caffemodel’
model_def = ‘/Inceptionv2/deploy.prototxt’
model_weights = ‘/googlenet2_4/bvlc_googlenet2_4_iter_18000.caffemodel’
#mu = np.load(caffe_root + ‘/python/caffe/imagenet/ilsvrc_2012_mean.npy’)
mu = np.load(’/data/mean.npy’)
image = caffe.io.load_image(caffe_root + ‘/examples/images/cat.jpg’)
#labels_file = caffe_root + ‘/data/ilsvrc12/synset_words.txt’
labels_file =’/data/label.txt’

net = caffe.Net(model_def,model_weights,caffe.TEST)
mu = mu.mean(1).mean(1) #平均畫素值以獲得平均(BGR)畫素值

print ‘mean-subtracted values:’, zip(‘BGR’, mu)

#為稱為“資料”的輸入建立變換器
transformer = caffe.io.Transformer({‘data’: net.blobs[‘data’].data.shape})
#將影象通道移動到最外層
transformer.set_transpose(‘data’, (2,0,1))
transformer.set_mean(‘data’, mu)
transformer.set_raw_scale(‘data’, 255)
transformer.set_channel_swap(‘data’, (2,1,0))
#引數需要依據網路結構的輸入變化而變化
net.blobs[‘data’].reshape(50, # batch size
3, # 3-channel (BGR) images
224, 224) # image size is 227x227

transformed_image = transformer.preprocess(‘data’, image)
plt.imshow(image)
#將影象資料複製到為網路分配的記憶體中
net.blobs[‘data’].data[…] = transformed_image
output = net.forward()
#網路名稱依據大家.pro檔案中的不同自行定義,下面的同樣
output_prob = output[‘loss1/loss1’][0]
print ‘predicted class is:’, output_prob.argmax()

labels = np.loadtxt(labels_file, str, delimiter=’\t’)

print ‘output label:’, labels[output_prob.argmax()]

#((batch_size, channel_dim, height, width)
for layer_name, blob in net.blobs.iteritems():
print layer_name + ‘\t’ + str(blob.data.shape)

#(output_channels, input_channels, filter_height, filter_width)
for layer_name, param in net.params.iteritems():
print layer_name + ‘\t’ + str(param[0].data.shape), str(param[1].data.shape)

def vis_square(data):
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, 1), (0, 1)) # add some space between filters
+ ((0, 0),) * (data.ndim - 3)) # don’t pad the last dimension (if there is one)
data = np.pad(data, padding, mode=‘constant’, constant_values=1) # pad with ones (white)
#將過濾器平鋪到影象中
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’)

filters = net.params[‘conv_conv1’][0].data
vis_square(filters.transpose(0, 2, 3, 1))
print’\n’
feat = net.blobs[‘conv1’].data[0, :36]
vis_square(feat)

#第一個完全連線層,fc6 我們顯示正值的輸出值和直方圖
feat = net.blobs[‘fc6’].data[0]
plt.subplot(2, 1, 1)
plt.plot(feat.flat)
plt.subplot(2, 1, 2)
_ = plt.hist(feat.flat[feat.flat > 0], bins=100)

feat = net.blobs[‘prob’].data[0]
plt.figure(figsize=(15, 3))
plt.plot(feat.flat)

`