Caffe 学习系列(7):mnist 图片数据实例

引言

深度学习的第一个实例一般都是 mnist数据集,只要这个例子完全弄懂了,其他的就可以举一反三。由于篇幅问题,本文不介绍配置文件里面每一个参数的具体含义。如有需要参看之前的博文或者自行搜索学习。

一、数据准备

官网提供的 mnist 数据并不是图片,但是我们以后做的实际项目大多数都涉及到图片。在此提供一个百度云盘,里面存着mnist 图片数据。mnist图片数据下载链接

数据分成了训练集(60000张共10类)和测试集(10000张共10类),每个类别放在一个单独的文件夹中。并且将所有的图片,都生成了 txt 列表清单( trian.txt 和 test.txt ). 文件下载后,解压复制到自己的工作目录下即可。

二、导入 caffe 库,并设定文件路径

import caffe
from caffe import layers as L,params as P,proto,to_proto
#设定文件的保存路径
root='/home/xxx/'                           #根目录
train_list=root+'mnist/train/train.txt'     #训练图片列表
test_list=root+'mnist/test/test.txt'        #测试图片列表
train_proto=root+'mnist/train.prototxt'     #训练配置文件
test_proto=root+'mnist/test.prototxt'       #测试配置文件
solver_proto=root+'mnist/solver.prototxt'   #参数文件

其中 trian.txt 和 test.txt 文件已经有了,其他三个文件,需要我们自己编写。

此处注意:一般 caffe 程序都是将图片数据转换成 lmdb 文件,但这样做有点麻烦。因此在这里就没有转换,直接用原始图片进行操作。此处图片数据量不大,手写数字识别案例较为简单,所以测试效果区别不大。

二、生成配置文件

配置文件实际上就是一些 txt 文档,只是后缀名是 prototxt ,可以直接在txt/word等编译器直接编写,也可以代码生成。此处用python 语言代码生成:

#编写一个函数,生成配置文件prototxt
def Lenet(img_list,batch_size,include_acc=False):
    #第一层,数据输入层,以ImageData格式输入
    data, label = L.ImageData(source=img_list, batch_size=batch_size, ntop=2,root_folder=root,
        transform_param=dict(scale= 0.00390625))
    #第二层:卷积层
    conv1=L.Convolution(data, kernel_size=5, stride=1,num_output=20, pad=0,weight_filler=dict(type='xavier'))
    #池化层
    pool1=L.Pooling(conv1, pool=P.Pooling.MAX, kernel_size=2, stride=2)
    #卷积层
    conv2=L.Convolution(pool1, kernel_size=5, stride=1,num_output=50, pad=0,weight_filler=dict(type='xavier'))
    #池化层
    pool2=L.Pooling(conv2, pool=P.Pooling.MAX, kernel_size=2, stride=2)
    #全连接层
    fc3=L.InnerProduct(pool2, num_output=500,weight_filler=dict(type='xavier'))
    #激活函数层
    relu3=L.ReLU(fc3, in_place=True)
    #全连接层
    fc4 = L.InnerProduct(relu3, num_output=10,weight_filler=dict(type='xavier'))
    #softmax层
    loss = L.SoftmaxWithLoss(fc4, label)
    
    if include_acc:             # test阶段需要有accuracy层
        acc = L.Accuracy(fc4, label)
        return to_proto(loss, acc)
    else:
        return to_proto(loss)
    
def write_net():
    #写入train.prototxt
    with open(train_proto, 'w') as f:
        f.write(str(Lenet(train_list,batch_size=64)))

    #写入test.prototxt    
    with open(test_proto, 'w') as f:
        f.write(str(Lenet(test_list,batch_size=100, include_acc=True)))

配置文件里面存放的,就是我们平时所说的 network 网络结构。(有兴趣可以用 python代码实现 经典的网络结构,以备自我学习参考之用)

三、生成solver 参数文件

同样,可以在编译器中直接书写,也可以用代码生成:

#编写一个函数,生成参数文件
def gen_solver(solver_file,train_net,test_net):
    s=proto.caffe_pb2.SolverParameter()
    s.train_net =train_net
    s.test_net.append(test_net)
    s.test_interval = 938    #60000/64,测试间隔参数:训练完一次所有的图片,进行一次测试  
    s.test_iter.append(100)  #10000/100 测试迭代次数,需要迭代100次,才完成一次所有数据的测试
    s.max_iter = 9380       #10 epochs , 938*10,最大训练次数
    s.base_lr = 0.01    #基础学习率
    s.momentum = 0.9    #动量
    s.weight_decay = 5e-4  #权值衰减项
    s.lr_policy = 'step'   #学习率变化规则
    s.stepsize=3000         #学习率变化频率
    s.gamma = 0.1          #学习率变化指数
    s.display = 20         #屏幕显示间隔
    s.snapshot = 938       #保存caffemodel的间隔
    s.snapshot_prefix =root+'mnist/lenet'   #caffemodel前缀
    s.type ='SGD'         #优化算法
    s.solver_mode = proto.caffe_pb2.SolverParameter.GPU    #加速
    #写入solver.prototxt
    with open(solver_file, 'w') as f:
        f.write(str(s))

四、开始训练

训练过程中,就是神经网络在不停迭代测试,自我参数更新的过程:

#开始训练
def training(solver_proto):
    caffe.set_device(0)
    caffe.set_mode_gpu()
    solver = caffe.SGDSolver(solver_proto)
    solver.solve()

最后,通过主函数调用实现即可:

if __name__ == '__main__':
    write_net()
    gen_solver(solver_proto,train_proto,test_proto) 
    training(solver_proto)

五、完整的 python 代码文件 mnist.py :

# -*- coding: utf-8 -*-

import caffe
from caffe import layers as L,params as P,proto,to_proto
#设定文件的保存路径
root='/home/xxx/'                           #根目录
train_list=root+'mnist/train/train.txt'     #训练图片列表
test_list=root+'mnist/test/test.txt'        #测试图片列表
train_proto=root+'mnist/train.prototxt'     #训练配置文件
test_proto=root+'mnist/test.prototxt'       #测试配置文件
solver_proto=root+'mnist/solver.prototxt'   #参数文件

#编写一个函数,生成配置文件prototxt
def Lenet(img_list,batch_size,include_acc=False):
    #第一层,数据输入层,以ImageData格式输入
    data, label = L.ImageData(source=img_list, batch_size=batch_size, ntop=2,root_folder=root,
        transform_param=dict(scale= 0.00390625))
    #第二层:卷积层
    conv1=L.Convolution(data, kernel_size=5, stride=1,num_output=20, pad=0,weight_filler=dict(type='xavier'))
    #池化层
    pool1=L.Pooling(conv1, pool=P.Pooling.MAX, kernel_size=2, stride=2)
    #卷积层
    conv2=L.Convolution(pool1, kernel_size=5, stride=1,num_output=50, pad=0,weight_filler=dict(type='xavier'))
    #池化层
    pool2=L.Pooling(conv2, pool=P.Pooling.MAX, kernel_size=2, stride=2)
    #全连接层
    fc3=L.InnerProduct(pool2, num_output=500,weight_filler=dict(type='xavier'))
    #激活函数层
    relu3=L.ReLU(fc3, in_place=True)
    #全连接层
    fc4 = L.InnerProduct(relu3, num_output=10,weight_filler=dict(type='xavier'))
    #softmax层
    loss = L.SoftmaxWithLoss(fc4, label)
    
    if include_acc:             # test阶段需要有accuracy层
        acc = L.Accuracy(fc4, label)
        return to_proto(loss, acc)
    else:
        return to_proto(loss)
    
def write_net():
    #写入train.prototxt
    with open(train_proto, 'w') as f:
        f.write(str(Lenet(train_list,batch_size=64)))

    #写入test.prototxt    
    with open(test_proto, 'w') as f:
        f.write(str(Lenet(test_list,batch_size=100, include_acc=True)))

#编写一个函数,生成参数文件
def gen_solver(solver_file,train_net,test_net):
    s=proto.caffe_pb2.SolverParameter()
    s.train_net =train_net
    s.test_net.append(test_net)
    s.test_interval = 938    #60000/64,测试间隔参数:训练完一次所有的图片,进行一次测试  
    s.test_iter.append(500)  #50000/100 测试迭代次数,需要迭代500次,才完成一次所有数据的测试
    s.max_iter = 9380       #10 epochs , 938*10,最大训练次数
    s.base_lr = 0.01    #基础学习率
    s.momentum = 0.9    #动量
    s.weight_decay = 5e-4  #权值衰减项
    s.lr_policy = 'step'   #学习率变化规则
    s.stepsize=3000         #学习率变化频率
    s.gamma = 0.1          #学习率变化指数
    s.display = 20         #屏幕显示间隔
    s.snapshot = 938       #保存caffemodel的间隔
    s.snapshot_prefix = root+'mnist/lenet'   #caffemodel前缀
    s.type ='SGD'         #优化算法
    s.solver_mode = proto.caffe_pb2.SolverParameter.GPU    #加速
    #写入solver.prototxt
    with open(solver_file, 'w') as f:
        f.write(str(s))
  
#开始训练
def training(solver_proto):
    caffe.set_device(0)
    caffe.set_mode_gpu()
    solver = caffe.SGDSolver(solver_proto)
    solver.solve()
#
if __name__ == '__main__':
    write_net()
    gen_solver(solver_proto,train_proto,test_proto) 
    training(solver_proto)

将此文件放在根目录下的 mnist 文件夹下(根据自己的情况而定),用下面的代码进行执行:

sudo python mnist/mnist.py

在训练过程中,会保存一些 caffemodel。多久保存一次,保存多少次,都可以在 solver 参数文件中设置。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值