【Caffe】训练ImageNet模型

来源:互联网 发布:局域网电影服务器软件 编辑:程序博客网 时间:2024/04/30 15:15

【原文:http://blog.csdn.net/pirage/article/details/17553549】

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代码如下:

[python] view plaincopy在CODE上查看代码片派生到我的代码片
  1. from caffe import imagenet  
  2. from matplotlib import pyplot  
  3. # Set the right path to your model file, pretrained model  
  4. # and the image you would like to classify.  
  5. MODEL_FILE = 'examples/imagenet_deploy.prototxt'  
  6. PRETRAINED = '/home/jiayq/Downloads/caffe_reference_imagenet_model’  
  7. IMAGE_FILE = '/home/jiayq/lena.png'  
  8.    
  9. net = imagenet.ImageNetClassifier(MODEL_FILE, PRETRAINED)   
  10. #预测  
  11. prediction = net.predict(IMAGE_FILE)  
  12. #绘制预测图像  
  13. print 'prediction shape:', prediction.shape  
  14. pyplot.plot(prediction)  
  15. prediction shape: (1000,)  
  16. [<matplotlib.lines.Line2D at 0x8faf4d0>] #结果如图所示  


 

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

结束语

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


0 0
原创粉丝点击