pycaffe网络定义
以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)
定义激活函数层:
relu3=L.ReLU(fc3, in_place=True)
定义全连接层:
fc3=L.InnerProduct(pool2, num_output=500,weight_filler=dict(type='xavier'))
计算损失函数:
loss = L.SoftmaxWithLoss(fc4, label)
计算精度:
acc = L.Accuracy(fc4, label)
保存网络定义.prototxt文件
以Lenet为例,网络结构代码如下:
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)
上述代码中,通过to_proto()函数,保存网络定义,保存为.prototxt文件,
with open(train_proto, 'w') as f:
f.write(str(Lenet(train_list,batch_size=64)))
train_list为模型输入,train_proto为.prototxt文件名,保存的.prototxt文件内容如下:
layer {