从 Python 中的 caffe .prototxt 模型定义中读取网络参数

Jar*_*rno 3 python protocol-buffers caffe pycaffe

我想从.prototxtPython 中定义的 caffe 网络中读出网络参数,作为layer_dict唯一的层对象告诉我,例如,它是一个“卷积”层,而不是像kernel_sizestrides等等。.prototxt文件。

所以让我们说我有一个model.prototxt这样的:

name: "Model"
layer {
  name: "data"
  type: "Input"
  top: "data"
  input_param {
    shape: {
      dim: 64
      dim: 1
      dim: 28
      dim: 28
    }
  }
}
layer {
  name: "conv2d_1"
  type: "Convolution"
  bottom: "data"
  top: "conv2d_1"
  convolution_param {
    num_output: 32
    kernel_size: 3
    stride: 1
    weight_filler {
      type: "gaussian" # initialize the filters from a Gaussian
      std: 0.01        # distribution with stdev 0.01 (default mean: 0)
    }
    bias_filler {
      type: "constant"
      value: 0
    }
  }
}

layer {
  name: "dense_1"
  type: "InnerProduct"
  bottom: "conv2d_1"
  top: "out"
  inner_product_param {
    num_output: 1024
    weight_filler {
      type: "gaussian"
      std: 0.01
    }
    bias_filler {
      type: "constant"
      value: 0
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

我发现可以像这样解析模型:

from caffe.proto import caffe_pb2
import google.protobuf.text_format
net = caffe_pb2.NetParameter()
f = open('model.prototxt', 'r')
net = google.protobuf.text_format.Merge(str(f.read()), net)
f.close()
Run Code Online (Sandbox Code Playgroud)

但我不知道如何从结果对象中获取 protobuf 消息中的字段。

rke*_*erm 5

您可以遍历层并询问它们对应的参数,例如:

for i in range(0, len(net.layer)):
    if net.layer[i].type == 'Convolution':
        net.layer[i].convolution_param.bias_term = True # bias term, for example
Run Code Online (Sandbox Code Playgroud)

合适的 *_param 类型可以在 caffe.proto 中找到,例如:

optional ConvolutionParameter convolution_param = 106
Run Code Online (Sandbox Code Playgroud)