参考文档为caffe官网指导文档 “training lenet on mnist with caffe"
准备数据集
定义MNIST网络
定义MNIST Solver
训练测试模型
(一)准备数据集
cd /home/ypp/caffe-master #cd 到caffe-master安装的根目录
sudo ./data/mnist/get_mnist.sh
sudo ./examples/mnist/create_mnist.sh
会在examples/mnist目录下生成测试和训练数据集
(二)定义MNIST网络
name: "LeNet"
#writing the data layer
layer {
name: "mnist"
type: "Data"
data_param {
source: "mnist_train_lmdb"
backend: LMDB
batch_size: 64
scale: 0.00390625
}
top: "data"
top: "label"
}
#writing the convolution layer
layer {
name: "conv1"
type: "Convolution"
param { lr_mult: 1 }
param { lr_mult: 2 }
convolution_param {
num_output: 20
kernel_size: 5
stride: 1
weight_filler {
type: "xavier"
}
bias_filler {
type: "constant"
}
}
}
#writing the pooling layer
layer {
name: "pool1"
type: "Pooling"
pooling_param {
kernel_size: 2
stride: 2
pool: MAX
}
bottom: "conv1"
top: "pool1"
}
layer {
name: "conv2"
type: "Convolution"
param { lr_mult: 1 }
param { lr_mult: 2 }
convolution_param {
num_output: 50
kernel_size: 5
stride: 1
weight_filler {
type: "xavier"
}
bias_filler {
type: "constant"
}
}
bottom: "pool1"
top: "conv2"
}
layer {
name: "pool2"
type: "Pooling"
pooling_param {
kernel_size: 2
stride: 2
pool: MAX
}
bottom: "conv2"
top: "pool2"
}
#writing the fully connected layer
layer {
name: "ip1"
type: "InnerProduct"
param { lr_mult: 1 }
param { lr_mult: 2 }
inner_product_param {
num_output: 500
weight_filler {
type: "xavier"
}
bias_filler {
type: "constant"
}
}
bottom: "pool2"
top: "ip1"
}
#writing the ReLU layer
layer {
name: "relu1"
type: "ReLU"
bottom: "ip1"
top: "ip1"
}
layer {
name: "ip2"
type: "InnerProduct"
param { lr_mult: 1 }
param { lr_mult: 2 }
inner_product_param {
num_output: 10
weight_filler {
type: "xavier"
}
bias_filler {
type: "constant"
}
}
bottom: "ip1"
top: "ip2"
}
#writing the loss layer
layer {
name: "loss"
type: "SoftmaxWithLoss"
bottom: "ip2"
bottom: "label"
}
定义的网络为:输入->卷积层 ->降采样层->卷积层->降采样层 ->全连接层->ReLU层->全连接层->损失函数
也可以根据相应的网络自行修改
(三)定义MNIST Solver
<pre name="code" class="plain">#The train/test net protocol buffer definition
net: "examples/mnist/define_myself_mnist.prototxt"
# test_iter specifies how many forward passes the test should carry out.
# In the case of MNIST, we have test batch size 100 and 100 test iterations,
# covering the full 10,000 testing images.
test_iter: 100
# Carry out testing every 500 training iterations.
test_interval: 500
# The base learning rate, momentum and the weight decay of the network.
base_lr: 0.01
momentum: 0.9
weight_decay: 0.0005
# The learning rate policy
lr_policy: "inv"
gamma: 0.0001
power: 0.75
# Display every 100 iterations
display: 100
# The maximum number of iterations
max_iter: 10000
# snapshot intermediate results
snapshot: 5000
snapshot_prefix: "examples/mnist/lenet"
# solver mode: CPU or GPU
solver_mode: CPU
(四)训练测试模型
新建脚本 train-lenet.sh
#!/usr/bin/env sh
./build/tools/caffe train --solver=examples/mnist/lenet_solver.prototxt
cd 到caffe-master根目录下 执行
sudo ./examples/mnist/train-lenet.sh