这是caffe文档中Notebook Examples的最后一个例子,链接地址:http://nbviewer.jupyter.org/github/BVLC/caffe/blob/master/examples/siamese/mnist_siamese.ipynb
这个例子将mnist降至2维, 可以将其特征可视化
1. 导入相应的包
import os
caffe_root = '/home/sindyz/caffe-master/'
os.chdir(caffe_root)
import sys
sys.path.insert(0,'./python')
import numpy as np
import matplotlib.pyplot as plt
import caffe
2. 载入模型和参数(如果没有运行过这个实例,按照readme的提示运行一下,就可以得到参数文件)
Model_file = "examples/siamese/mnist_siamese.prototxt"
Param_file = "examples/siamese/mnist_siamese_iter_50000.caffemodel"
caffe.set_mode_cpu()
net = caffe.Net(Model_file, Param_file, caffe.TEST)
3. 载入mnist数据
Test_Data_File = "data/mnist/t10k-images-idx3-ubyte"
Test_Label_File = "data/mnist/t10k-labels-idx1-ubyte"
n = 10000
with open(Test_Data_File, 'rb') as f:
f.read(16) # skip the header
raw_data = np.fromstring(f.read(n * 28*28), dtype=np.uint8)
with open(Test_Label_File, 'rb') as f:
f.read(8) # skip the header
labels = np.fromstring(f.read(n), dtype=np.uint8)
4. 生成关联特征
# reshape and preprocess
caffe_in = raw_data.reshape(n, 1, 28, 28) * 0.00390625 # manually scale data instead of using `caffe.io.Transformer`
out = net.forward_all(data=caffe_in)
5. 可视化
# reshape and preprocess
caffe_in = raw_data.reshape(n, 1, 28, 28) * 0.00390625 # manually scale data instead of using `caffe.io.Transformer`
out = net.forward_all(data=caffe_in)
feat = out['feat']
f = plt.figure(figsize=(16,9))
c = ['#ff0000', '#ffff00', '#00ff00', '#00ffff', '#0000ff',
'#ff00ff', '#990000', '#999900', '#009900', '#009999']
for i in range(10):
plt.plot(feat[labels==i,0].flatten(), feat[labels==i,1].flatten(), '.', c=c[i])
plt.legend(['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'])
plt.grid()
plt.show()
输出:
参考资料:
http://nbviewer.jupyter.org/github/BVLC/caffe/blob/master/examples/siamese/mnist_siamese.ipynb#Visualize-the-learned-Siamese-embedding
http://caffe.berkeleyvision.org/gathered/examples/siamese.html