本文在LeNet5结构的基础上通过不断调整学习速率和权衰量来训练自己的汉字数据集
caffe的Python接口安装成功后,安装jupyter:
sudo pip install jupyter
安装成功后,运行。运行命令:
jupyter notebook
运行后会在网页中出现如下界面:
点击页面右上角下的New--Python 2
输入如下代码:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
import sys,os,caffe
#设置当前目录
caffe_root = '/home/lrj/Caffe/caffe-master/'
sys.path.insert(0, caffe_root + 'python')
os.chdir(caffe_root)
#设置为cpu模式
caffe.set_mode_cpu()
solver = caffe.SGDSolver('examples/hanzi/mylenet_solver.prototxt')
按shift+enter键(运行当前代码并跳到下以输入)
niter =800
test_interval = 20
train_loss = np.zeros(niter)
test_acc = np.zeros(int(np.ceil(niter / test_interval)))
# the main solver loop
for it in range(niter):
solver.step(1) # SGD by Caffe
# store the train loss 小写.net 我不知道为什么显示的为大写
train_loss[it] = solver.net.blobs['loss'].data
solver.test_nets[0].forward(start='conv1')
if it % test_interval == 0:
acc=solver.test_nets[0].blobs['accuracy'].data
print 'Iteration', it, 'testing...','accuracy:',acc
test_acc[it // test_interval] = acc
按shift+enter键
此时,开始开始迭代计算
然后输入:
print test_acc
_, ax1 = plt.subplots()
ax2 = ax1.twinx()
ax1.plot(np.arange(niter), train_loss)
ax2.plot(test_interval * np.arange(len(test_acc)), test_acc, 'r')
ax1.set_xlabel('iteration')
ax1.set_ylabel('train loss')
ax2.set_ylabel('test accuracy')
按shift+enter键运行即可得到曲线