#coding=utf-8 import caffe import numpy as np import struct import matplotlib.pyplot as plt #读取mnist数据集 filename = 'train-images.idx3-ubyte' binfile = open(filename, 'rb') buf = binfile.read() #提取第1张图片进行测试 index = 0 #0代表第一张图,784*(n-1)代表第n张图片 magic, numImages, numRows, numColumns = struct.unpack_from('>IIII', buf, index) index += struct.calcsize('>IIII') im = struct.unpack_from('>784B', buf, index) index += struct.calcsize('>784B') #模型和部署文件的加载 deploy='lenet_deploy.prototxt' #deploy文件 caffe_model= 'lenet_iter_10000.caffemodel' #训练好的 caffemodel #将向量展开为28*28的图片 im = np.array(im) im = im.reshape(28, 28) #显示图片 fig = plt.figure() plotwindow = fig.add_subplot(111) plt.imshow(im, cmap='gray') plt.show() #将图片reshape为神经网络的输入 im = im.reshape(28, 28,1) im=im.astype(np.float32) #数据转换 print "The shape of im:", im.shape gender_net = caffe.Classifier(deploy, caffe_model) output =gender_net.predict([im],oversample = False) caffe.set_mode_cpu() print 'predicted class:',output[0].argmax()