#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()