您的位置:首页 > 理论基础 > 计算机网络

Caffe windows下入门级别的从编译到训练然后到分类(用python接口)制作自己的数据和训练网络(三)

2017-02-26 17:03 537 查看

前言

上一篇我们把环境搭建好了和Caffe编译好了,接下来我们就可以去制作自己的数据集和训练我们的网络了。
接下来我们可以分为这么几步:
1.制作数据
1.获取图片
2.把图片尺寸统一为256*256
3.制作训练和验证的标签
4.制作识别用的标签
5.图片文件格式的转换
6.创建均值文件
2.训练模型
1.配置solver文件
2.配置train_val文件
3.训练


制作数据集

制作数据集的我选择写个python的脚本去解决。当然你也可以直接去下载官方案例的图片。这里我就介绍脚本解决方法。


python图片爬虫代码

这里我引用我自己写的一个关于python爬虫的例子里面源代码也都有大家反正前面python的环境也都安装好了所以这里就直接用吧。

然后是将图片的尺寸修改到256*256这里我也直接给出python的源代码:

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

from PIL import Image
import os

CheckDirPath = os.path.abspath('..') + '/pictest'
OutDirPath = os.path.abspath('..') + '/mymnist/test'
NowNum = 0

#查找图片并且转换
def ChangeImgsSize(Dir):
global NowNum
for root,dirs,files in os.walk(Dir):
for dir in dirs:
NowNum = NowNum + 1
for dirroot,dirdirs,dirfiles in os.walk(root + '/' + dir):
for file in dirfiles:
SavePath = OutDirPath + '/' + str(NowNum) + '/'
OutFilePath = SavePath + file
try:
#print dirroot + file
im = Image.open(dirroot + '/' + file)
(width, height) = im.size
#检查图片的比例如果是竖直放置的图片则调整
#if width < height:
#    im = im.rotate(90)
out = im.resize((256,256))
if os.path.exists(SavePath) == False:
os.mkdir(SavePath)
out.save(SavePath + file)
print '[Debug] : Complete the Imagefile -----> ' +  file
except Exception,e:
print '[Error] : The Error info is [Exception] : ' +  str(Exception) + '[e] : ' + str(e)
if os.path.exists(OutFilePath):
os.remove(OutFilePath)
print '[Delete] : To Delete the file --->' + OutFilePath

if __name__ == '__main__':
if os.path.exists(OutDirPath) == False:
os.mkdir(OutDirPath)
ChangeImgsSize(CheckDirPath)


然后是创建训练和验证标签的python源代码:


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

import os

CheckPicDir = 'mymnist/test/'
CheckDirPath = os.path.abspath('..') + '/' + CheckPicDir

def Create(Dir):
LabelString = ''
for root,dirs,files in os.walk(Dir):
for dir in dirs:
for dirroot,dirdirs,dirfiles in os.walk(root + dir):
for file in dirfiles:
try:
LabelString += CheckPicDir + dir + '/' + file + ' ' + str(int(dir) - 1) + '\n'
except Exception,e:
print '[Error] : Exception---->' + str(Exception) + '___e------->' + str(e)
return LabelString

if __name__ == '__main__':
LabelString = Create(CheckDirPath)
f = open(CheckDirPath + 'test.txt', 'w');
f.write(LabelString)
f.close()


然后是创建识别标签源代码:(这里的数据是我测试的时候用的所以你们改成自己的就好)


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

import os

LabelText = '哈士奇' + '\t' + '杜宾犬' + '\t' + '柴犬' + '\t' + '泰迪犬' + '\t' + '藏獒' + '\t' + '贵宾犬'

OutPath = os.path.abspath('..') + '/mymnist/test/labels.txt'
f = open(OutPath, 'w')
f.write(LabelText)
f.close();


这里是计算文件夹下有多少图片的代码后面配置的时候会可能需要数量:


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

import os

CheckDirPath = os.path.abspath('..') + '/mymnist/test/'

def CurNum(Dir):
Num = 0
for root,dirs,files in os.walk(Dir):
for dir in dirs:
for dirroot,dirdirs,dirfiles in os.walk(root + dir):
for file in dirfiles:
Num += 1
return Num

if __name__ == '__main__':
num = CurNum(CheckDirPath)
print num


下面是图片文件格式转换的代码(当然直接图片是不能拿来训练的所以我们需要转换为caffe能识别的数据格式)我们采用的数据格式为LEVELDB这种格式这些都是根据sh脚本改写的windows下的命令当然你们也可以使用一些工具直接运行sh脚本相应的脚本对用的路径在caffe-windows\examples\imagenet这文件夹里面:


# coding:utf-8

import os

EXAMPLE = os.getcwd()
DBOUTPATH = os.path.abspath('..') + '/mymnist/'
TOOLS = '~~~~~~~~\\caffe-windows\\Build\\x64\\Release'
DBTYPE="leveldb"

TRAIN_DATA_ROOT= os.path.abspath('..') + '/'
TRAIN_DATA_LABEL = os.path.abspath('..') + '/mymnist/train.txt'
VAL_DATA_ROOT= os.path.abspath('..') + '/'
VAL_DATA_LABEL = os.path.abspath('..') + '/mymnist/val.txt'

RESIZE = False;

RESIZE_HEIGHT = '256'
RESIZE_WIDTH = '256'

#print os.environ

if __name__ == '__main__':
if(RESIZE):
print '不好意思我们并没有提供重新调整尺寸的代码!'
print 'Strat Create LMDB DataBase.....'
pathtrain = DBOUTPATH + 'caffe_train_' + DBTYPE
pathtest = DBOUTPATH + 'caffe_test_' + DBTYPE

if os.path.exists(pathtrain) == False:
os.mkdir(pathtrain)
print 'Create the Path : ' + pathtrain
if os.path.exists(pathtest) == False:
os.mkdir(pathtest)
print  'Create the Path : ' + pathtest

cmd1 = TOOLS + '/convert_imageset --resize_height=' + RESIZE_HEIGHT + ' --resize_width=' + RESIZE_WIDTH + " --shuffle --backend="+ DBTYPE +" " + TRAIN_DATA_ROOT + ' ' +  TRAIN_DATA_LABEL + ' ' + pathtrain + ' 1'
print 'The cmd1 is : ' + cmd1 + 'and Start Create train ' + DBTYPE + '.....'
os.system(cmd1)

cmd2 = TOOLS + '/convert_imageset --resize_height=' + RESIZE_HEIGHT + ' --resize_width=' + RESIZE_WIDTH + " --shuffle --backend="+ DBTYPE +" " + VAL_DATA_ROOT + ' ' + VAL_DATA_LABEL + ' ' + pathtest + ' 1'
print 'The cmd2 is : ' + cmd2 + 'and Start Create val ' + DBTYPE + '.......'
os.system(cmd2)


格式也转换好了然后我们可以创建均值文件了(然后设置好我们转换后的数据的路径和均值文件的输出路径就好):


# coding:utf-8

import os

MEAN_EXE_PATH = '~~~~~~~~\\caffe-windows\\Build\\x64\\Release\\compute_image_mean.exe'
DBTYPE = 'leveldb'
DBTYPE_PATH = os.path.abspath('..') + '/mymnist/caffe_train_leveldb'
MEAN_OUT_PATH = os.path.abspath('..') + '/mymnist/mean/'
MEAN_NAME = 'mean.binaryproto'

def CreateMeanFile():
cmd = MEAN_EXE_PATH + ' --backend=' + DBTYPE + ' ' + DBTYPE_PATH + ' ' + MEAN_OUT_PATH + MEAN_NAME
print 'Strat Create MeanFile..........'
os.system(cmd)
print '[Debug] : Complete!'

if __name__ == '__main__':
if os.path.exists(MEAN_OUT_PATH) == False:
os.mkdir(MEAN_OUT_PATH)
print '[Debug] : Create the path' + MEAN_OUT_PATH
CreateMeanFile()


训练模型

大家找到这个路径caffe-windows\models\bvlc_reference_caffenet我们所需要的2个配置文件全部都在这个路径下所以我们直接复制我们最上面列出的2个文件,复制到我们的工程目录下然后用编辑器打开修改对应的参数,
solver文件(~~~~~~~~这个换成你们自己的路径我这里就不显示具体的了)这里参数的讲解我想就不另外写了我直接放上别人的地址基本上都是一样的:


参数详解

net: "~~~~~~~~/train_val.prototxt"
test_iter: 30
test_interval: 500
base_lr: 0.0001
lr_policy: "step"
gamma: 0.1
stepsize: 100000
display: 20
max_iter: 7000
momentum: 0.9
weight_decay: 0.0005
snapshot: 1000
snapshot_prefix: "~~~~~~~~/caffenet_train"
solver_mode: CPU


然后是train_val文件(由于这个文件太长我就不放全部了就放关键的部分,~~~~~~~~~~~~这个同样换成自己的路径)对了最后不要忘记吧最后的输出数量改成自己要分类的数量如果我们要分的类别是6种就像我的测试一样的话 请设置为num_output: 6:


name: "CaffeNet"
layer {
name: "data"
type: "Data"
top: "data"
top: "label"
include {
phase: TRAIN
}
transform_param {
mirror: true
crop_size: 227
mean_file: "~~~~~~~~~~~~/mean/mean.binaryproto"
}
# mean pixel / channel-wise mean instead of mean image
#  transform_param {
#    crop_size: 227
#    mean_value: 104
#    mean_value: 117
#    mean_value: 123
#    mirror: true
#  }
data_param {
source: "~~~~~~~~~~~~/caffe_train_leveldb"
batch_size: 20
backend: LEVELDB
}
}
layer {
name: "data"
type: "Data"
top: "data"
top: "label"
include {
phase: TEST
}
transform_param {
mirror: false
crop_size: 227
mean_file: "~~~~~~~~~~~~/mean/mean.binaryproto"
}
# mean pixel / channel-wise mean instead of mean image
#  transform_param {
#    crop_size: 227
#    mean_value: 104
#    mean_value: 117
#    mean_value: 123
#    mirror: false
#  }
data_param {
source: "~~~~~~~~~~~~/caffe_test_leveldb"
batch_size: 50
backend: LEVELDB
}
}
.......................


上面都OK之后就可以开始训练了,这个是训练的python代码(注:如果代码卡主那么应该是你没有设置好上面的参数,请把test_iter: 30
test_interval: 500这2个改小如果还是卡主很久很久 那么再把batch_size改小在train_val文件的往下第一个batch_size改小然后就可以跑训练数据了,对了如果还是卡主很久很久的话要么就是机子太烂了,或则就就打开dos直接输入命令去运行会好一些比如~~~~~~~~caffe.exe train --solver=~~~~~~~~\solver.prototxt 当然~~~~~~~~这个改成自己的路径caffe.exe在build里面),最后等待训练结束就OK:


# coding:utf-8

import os

CaffePath = '~~~~~~~~/caffe-windows/Build/x64/Release/caffe.exe'
SolverPath = os.path.abspath('..') + '/mymnist/solver.prototxt'

def Train():
cmd = CaffePath + ' train --solver=' + SolverPath
print '[Debug] : Start train the net.....'
os.system(cmd)
print '[Debug] : Complete....'

if __name__ == '__main__':
Train()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐