使用caffe提供的python接口訓練mnist例子


1 首先肯定是安裝caffe,並且編譯python接口,如果是在windows上,最好把編譯出來的python文件夾的caffe文件夾拷貝到anaconda文件夾下面去,這樣就有代碼自動提示功能,如下:

image

本文中使用的ide為anaconda安裝中自帶的spyder,如圖所示,將根目錄設置為caffe的根目錄。

image

import caffe
caffe.set_mode_cpu()
solver = caffe.SGDSolver('examples/mnist/lenet_solver.prototxt')
solver.solve()

以上為一次全部迭代,如果想自己控制,可使用如下代碼:

import caffe
caffe.set_mode_cpu()
solver = caffe.SGDSolver('examples/mnist/lenet_solver.prototxt')
#solver.solve()

iter = solver.iter
while iter<10000:
    solver.step(1)
    iter = solver.iter
    input_data = solver.net.blobs['data'].data  
    loss = solver.net.blobs['loss'].data
    accuracy = solver.test_nets[0].blobs['accuracy'].data
    print 'iter:', iter, 'loss:', loss,'accuracy:',accuracy
import caffe
import matplotlib.pyplot as plt     
import numpy as np

def vis_square(data):
    """Take an array of shape (n, height, width) or (n, height, width, 3)
       and visualize each (height, width) thing in a grid of size approx. sqrt(n) by sqrt(n)"""
    
    # normalize data for display
    data = (data - data.min()) / (data.max() - data.min())
    
    # 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, 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)
    
    # 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:])
    if data.shape[2] == 1:
        data = data[:,:,0]
    plt.imshow(data); plt.axis('off')

if __name__ == '__main__':
    caffe.set_mode_cpu()
    solver = caffe.SGDSolver('examples/mnist/lenet_solver.prototxt')
    solver.step(1)
    input_data = solver.net.blobs['data'].data  
    plt.figure(0)
    vis_square(input_data.transpose(0, 2, 3, 1))  
    filters = solver.net.params['conv1'][0].data
    plt.figure(1)
    vis_square(filters.transpose(0, 2, 3, 1))

    特征圖:
image   
    權值圖

image


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM