将两个loss曲线一个accuracy曲线画在一个图上
#!/usr/bin/python
#coding:utf-8
import os
import sys
import numpy as np
import matplotlib.pyplot as plt
caffe_root = '/usr/local/Cellar/caffe/'
sys.path.insert(0, caffe_root + 'python')
import caffe
# MODEL_FILE = caffe_root+'examples/mnist/lenet.prototxt'
# PRETRAINED = caffe_root+'examples/mnist/lenet_iter_10000.caffemodel'
# IMAGE_FILE = caffe_root+'examples/images/test4.bmp'
import matplotlib.pyplot as plt
from numpy import zeros, arange
from math import ceil
import caffe
#caffe.set_device(0)
caffe.set_mode_cpu()
# 使用SGDsolver,即随机梯度下降算法,这个要看你solver文件里,一般不写的话就是sgd
# solver=caffe.AdamSolver('/root/caffe/examples/mnist/lenet_solver_adam.prototxt')
solver = caffe.SGDSolver(caffe_root + 'examples/mnist/lenet_solver_test_show.prototxt')
# 等价于solver文件中的max_iter,即最大解算次数
niter = 10000
# 每隔100次收集一次数据
display = 100
# 每次测试进行100次解算,10000/100
test_iter = 100
# 每500次训练进行一次测试(100次解算),60000/64
test_interval = 500
# 初始化
train_loss = zeros(int(niter * 1.0 / display))
test_loss = zeros(int(niter * 1.0 / test_interval))
test_acc = zeros(int(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['loss'].data # 注意,这里的loss表示你定义网络中loss层使用的名称,原博客中定义该网络使用的是SoftmaxWithLoss
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['loss'].data # loss名称和上面的一样
# 计算test accuracy
_accuracy += solver.test_nets[0].blobs['accuracy'].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()
#coding:utf-8
添加后支持中文字符;
caffe_root = '/usr/local/Cellar/caffe/'
配置自己的caffe路径;
solver = caffe.SGDSolver(caffe_root + 'examples/mnist/lenet_solver_test_show.prototxt')
配置自己的solver文件路径;(注:其中的net和snapshot_prefix建议配置绝对路径)
net: "/usr/local/Cellar/caffe/examples/mnist/lenet_train_test.prototxt"
snapshot_prefix: "/Users/taily/pycharmproj/"
训练完成后显示训练过程的loss曲线和accuracy曲线:
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:【Caffe】caffe可视化训练过程实操 - Python技术站