caffe学习笔记-模型代码生成.prototxt文件

这篇博客介绍了如何使用pycaffe定义ImageData输入的网络结构,包括卷积、池化、激活函数、全连接层,并展示了以Lenet为例的网络定义代码。通过to_proto()函数,将网络定义保存为.prototxt文件。此外,还提到了网络训练过程,需要solver.prototxt文件来定义训练参数,以及训练代码的编写方式。
摘要由CSDN通过智能技术生成

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文件内容如下:

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值