# -*- coding: UTF-8 -*-
__author__ = 'xuy'
import caffe
import os
import sys
#用来对于图片进行操作
# caffe_root='/home/xuy/caffe'
caffe_root='/home/xuy/caffe'
os.chdir(caffe_root)#将当前的路径换成了~/caffe
sys.path.append(caffe_root+'python')
sys.path.append('/usr/lib/python2.7/dist-packages/')
"""
对于caffe的硬件进行设置:是使用cpu还是使用gpu
"""
USE_GPU=True
if USE_GPU:
caffe.set_device(0)
caffe.set_mode_gpu()
else:
caffe.set_mode_cpu()
print 'Initialized caffe'
net=caffe.NetSpec()
"""
给caffe创建层
层的名字:这个是根据等号左面的第一个函数变量名称而来的,例如net.data,net.label,那么该层的名字就是data
层的类型:这个是根据函数来的,比如说:caffe.layers.Data,那么类型就是data类型,如果是caffe.layers.Convolution,那么类型就是convolution
top(神经网络的输出),也就是等号的左面,如果有两个top的话,那么就需要指定ntop=2,如果是2个以上,那么就在ntop定义相应的数值
bottom:是函数当中的第一个参数
层的属性:如果需要定义层当中的子属性,那么就需要用到了python当中的字典去定义了
enum DB {
LEVELDB = 0;
LMDB = 1;
}
So the backend=1 means LMDB.
"""
batch_size = 64
input_file = "examples/mnist/mnist_train_lmdb"
net.data, net.label = caffe.layers.Data(batch_size=batch_size, source=input_file, ntop=2, backend=1)
"""
This line is equivalent to the prototxt:
layer {
name: "data"
type: "Data"
top: "data"
top: "label"
data_param {
source: "examples/mnist/mnist_train_lmdb"
batch_size: 64
backend: LMDB
}
}
"""
"""
name取决于等号左面的第一个变量,因此是conv1
type是取决于caffe.layers.Convolution函数名
bottom是因为第一个参数是net.data,因此bottom:是data类型
top因为左面等号就有1个参数,因此top就一个conv1,因此不用在convolution函数里面写ntop参数了
num_output=20, kernel_size=5,这两个参数是convolution里面的自带参数,因此仅仅加到convolution_param即可
weight_filler以及bias_filler是convolution里面的自定义的参数,因此需要用到python当中的字典来定义
"""
net.conv1 = caffe.layers.Convolution(net.data, num_output=20, kernel_size=5,
weight_filler={"type": "xavier"},
bias_filler={"type": "constant"})
"""
输出prototxt的结果
layer {
name: "conv1"
type: "Convolution"
bottom: "data"
top: "conv1"
convolution_param {
num_output: 20
kernel_size: 5
weight_filler {
type: "xavier"
}
bias_filler {
type: "constant"
}
}
}
"""
"""
param={"lr_mult": 2},是特有的参数,所以需要python字典来定义
num_output=10,是全连接层InnerProduct层自带的,因此直接加入里面即可
"""
net.ip2 = caffe.layers.InnerProduct(net.conv1, num_output=10,param={"lr_mult": 2},)
"""
layer {
name: "ip2"
type: "InnerProduct"
bottom: "conv1"
top: "ip2"
param {
lr_mult: 2
}
inner_product_param {
num_output: 10
}
}
"""
"""
因为是两个输出层bottom,因此就直接在caffe.layers.SoftmaxWithLoss函数中写入这两个参数即可
"""
net.loss = caffe.layers.SoftmaxWithLoss(net.ip2, net.label)
"""
prototxt的输出
layer {
name: "loss"
type: "SoftmaxWithLoss"
bottom: "ip2"
bottom: "label"
top: "loss"
}
"""
# print str(net.to_proto())#用来输出ptototxt当中的内容
output_file="my_net.prototxt"
with open(output_file,'w') as f:#将该网络结构写入到了/home/xuy/caffe/my_net.prototxt当中
f.write(str(net.to_proto()))
pycaffe使用(第二篇)——构造网络结构
最新推荐文章于 2020-04-29 17:26:32 发布