使用python接口來運行caffe程序,主要的緣由是python很是容易可視化。因此不推薦你們在命令行下面運行python程序。若是非要在命令行下面運行,還不如直接用 c++算了。python
推薦使用jupyter notebook,spyder等工具來運行python代碼,這樣才和它的可視化完美結合起來。c++
由於我是用anaconda來安裝一系列python第三方庫的,因此我使用的是spyder,與matlab界面相似的一款編輯器,在運行過程當中,能夠查看各變量的值,便於理解,以下圖:算法
只要安裝了anaconda,運行方式也很是方便,直接在終端輸入spyder命令就能夠了。編輯器
在caffe的訓練過程當中,咱們若是想知道某個階段的loss值和accuracy值,並用圖表畫出來,用python接口就對了。工具
# -*- coding: utf-8 -*- """ Created on Tue Jul 19 16:22:22 2016 @author: root """ import matplotlib.pyplot as plt import caffe caffe.set_device(0) caffe.set_mode_gpu() # 使用SGDSolver,即隨機梯度降低算法 solver = caffe.SGDSolver('/home/xxx/mnist/solver.prototxt') # 等價於solver文件中的max_iter,即最大解算次數 niter = 9380 # 每隔100次收集一次數據 display= 100 # 每次測試進行100次解算,10000/100 test_iter = 100 # 每500次訓練進行一次測試(100次解算),60000/64 test_interval =938 #初始化 train_loss = zeros(ceil(niter * 1.0 / display)) test_loss = zeros(ceil(niter * 1.0 / test_interval)) test_acc = zeros(ceil(niter * 1.0 / test_interval)) # iteration 0,不計入 solver.step(1) # 輔助變量 _train_loss = 0; _test_loss = 0; _accuracy = 0 # 進行解算 for it in range(niter): # 進行一次解算 solver.step(1) # 每迭代一次,訓練batch_size張圖片 _train_loss += solver.net.blobs['SoftmaxWithLoss1'].data if it % display == 0: # 計算平均train loss train_loss[it // display] = _train_loss / display _train_loss = 0 if it % test_interval == 0: for test_it in range(test_iter): # 進行一次測試 solver.test_nets[0].forward() # 計算test loss _test_loss += solver.test_nets[0].blobs['SoftmaxWithLoss1'].data # 計算test accuracy _accuracy += solver.test_nets[0].blobs['Accuracy1'].data # 計算平均test loss test_loss[it / test_interval] = _test_loss / test_iter # 計算平均test accuracy test_acc[it / test_interval] = _accuracy / test_iter _test_loss = 0 _accuracy = 0 # 繪製train loss、test loss和accuracy曲線 print '\nplot the train loss and test accuracy\n' _, ax1 = plt.subplots() ax2 = ax1.twinx() # train loss -> 綠色 ax1.plot(display * arange(len(train_loss)), train_loss, 'g') # test loss -> 黃色 ax1.plot(test_interval * arange(len(test_loss)), test_loss, 'y') # test accuracy -> 紅色 ax2.plot(test_interval * arange(len(test_acc)), test_acc, 'r') ax1.set_xlabel('iteration') ax1.set_ylabel('loss') ax2.set_ylabel('accuracy') plt.show()
最後生成的圖表在上圖中已經顯示出來了。測試