【Caffe】训练ImageNet模型

Caffe训练ImageNet使用的是NIPS 2012 paper论文的算法。

 

1、准备数据。

假设已经下载好数据集和验证集,存储路径为:

/path/to/imagenet/train/n01440764/n01440764_10026.JPEG

/path/to/imagenet/val/ILSVRC2012_val_00000001.JPEG

首选需要创建一个txt文件,列举出所有图像以及对应的lablecaffe包“python/caffe/imagenet/ilsvrc_2012_train.txt”和“ilsvrc_2012_val.txt”两个文件分别是标好的训练集和验证集的文件,共分为1000类。

还需要注意的是,所有的图像都需要归一到同样的尺寸。

 

2、转化生成训练集。

运行下面的命令:

GLOG_logtostderr=1 examples/convert_imageset.bin   /path/to/imagenet/train/ python/caffe/imagenet/ilsvrc_2012_train.txt    /path/to/imagenet-train-leveldb

生成文件存储在“/path/to/imagenet-train_leveldb”路径下。

 

3、计算图像均值。

执行命令:

examples/demo_compute_image_mean.bin /path/to/imagenet-train-leveldb /path/to/mean.binaryproto

第一个参数是执行脚本代码,第二个参数是上一步生成的数据集,第三个参数是存储图像均值的目录路径。

 

4、定义网络。

ImageNet的网络定义在“examples/imagenet.prototxt”文件中,使用时需要修改里面sourcemeanfile变量的值,指向自己文件的路径。

仔细观察imagenet.prototxtimagenet_val.prototxt文件可以发现,训练和验证的参数大部分都相同,不同之处在于初始层和最后一层。训练时,使用softmax_loss层来计算损失函数和初始化后向传播,验证时,使用accuracy层来预测精确度。

在文件“examples/imagenet_solver.prototxt”中定义solver协议,同样需要修改train_nettest_net的路径。

 

5、训练网络。

执行命令:

GLOG_logtostderr=1 examples/train_net.bin examples/imagenet_solver.prototxt

 

6、在python中使用已经训练好的模型。

Caffe只提供封装好的imagenet模型,给定一副图像,直接计算出图像的特征和进行预测。首先需要下载模型文件

Python代码如下:

from caffe import imagenet
from matplotlib import pyplot
# Set the right path to your model file, pretrained model
# and the image you would like to classify.
MODEL_FILE = 'examples/imagenet_deploy.prototxt'
PRETRAINED = '/home/jiayq/Downloads/caffe_reference_imagenet_model’
IMAGE_FILE = '/home/jiayq/lena.png'
 
net = imagenet.ImageNetClassifier(MODEL_FILE, PRETRAINED) 
#预测
prediction = net.predict(IMAGE_FILE)
#绘制预测图像
print 'prediction shape:', prediction.shape
pyplot.plot(prediction)
prediction shape: (1000,)
[<matplotlib.lines.Line2D at 0x8faf4d0>] #结果如图所示


 

图上的横轴表示的label,纵轴表示在该类别上的概率,有图我们看到,lena.jpg被分到了”sombrero”这组,结果还算准确。 

结束语

更多内容请参考http://daggerfs.com/caffe/

  • 6
    点赞
  • 50
    收藏
    觉得还不错? 一键收藏
  • 17
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 17
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值