【问题标题】:Customizing the convolution layer in caffe windows cpp在caffe windows cpp中自定义卷积层
【发布时间】:2017-04-30 22:19:51
【问题描述】:

我有这个网'RGB2GRAY.prototxt':

name: "RGB2GRAY"
layer {
  name: "data"
  type: "Input"
  top: "data"
  input_param { shape: { dim: 1 dim: 3 dim: 512 dim: 512 } }
}

layer {
    name: "conv1"
    bottom: "data"
    top: "conv1"
    type: "Convolution"
    convolution_param {
        num_output: 1
        kernel_size: 1
        pad: 0
        stride: 1
        bias_term: false
        weight_filler {
        type: "constant"
        value: 1
        }
    }
}

我正在尝试使用此公式将 RGB 转换为灰色的自己的网络

x = 0.299r + 0.587g + 0.114b.

所以基本上,我可以使用自定义权重 (0.299, 0.587, 0.114) 进行卷积核大小为 1 的卷积。但我不知道如何修改卷积层。我已经设置了权重和偏差,但无法修改过滤器值。 我尝试了以下方法,但无法更新卷积过滤器。

shared_ptr<Net<float> > net_;
net_.reset(new Net<float>("path of model file", TEST));

const shared_ptr<Blob<float> >& conv_blob = net_->blob_by_name("conv1");
float* conv_weight = conv_blob->mutable_cpu_data();
conv_weight[0] =  0.299;
conv_weight[1] =  0.587;
conv_weight[2] =  0.114;

net_->Forward();

//for dumping the output
const shared_ptr<Blob<float> >& probs = net_->blob_by_name("conv1");
const float* probs_out = probs->cpu_data();

cv::Mat matout(height, width, CV_32F);

for (size_t i = 0; i < height; i++)
{
    for (size_t j = 0; j < width; j++)
    {
        matout.at<float>(i, j) = probs_out[i* width + j];
    }

}
matout.convertTo(matout, CV_8UC1);
cv::imwrite("gray.bmp", matout);

在 python 中,我发现自定义卷积过滤器更容易,但我需要 C++ 中的解决方案。

【问题讨论】:

  • 我正在寻找相同的解决方案。
  • /我无法理解您的解决方案有什么问题? weight_fillrer 仅在没有权重时使用(“冷启动”)。如果您现在保存网络,它不会保持正确的权重吗?
  • @shai...yes.... 权重没有更新!!

标签: c++ neural-network deep-learning caffe conv-neural-network


【解决方案1】:

只需在你的 c++ 代码中做一个小改动:

// access the convolution layer by its name
const shared_ptr<Layer<float> >& conv_layer = net_->layer_by_name("conv1");
// access the layer's blob that stores weights
shared_ptr<Blob<float> >& weight = conv_layer->blobs()[0];
float* conv_weight = weight->mutable_cpu_data();
conv_weight[0] =  0.299;
conv_weight[1] =  0.587;
conv_weight[2] =  0.114;

其实,“conv1”是指你代码中卷积层的输出blob,而不是包含权重的blobNet&lt;Dtype&gt;::blob_by_name(const string&amp; blob_name)的作用是返回存储中间结果的blob网络中的层。

【讨论】:

  • @AnkitSahu 请再试一次最新的,我无法运行代码,所以需要你多试几次。 :)
  • @AnkitSahu 你能在我的回答中打印出weight blob 的形状吗?还要确保您已将输入图像输入net_
  • @Dale ...向你致敬 :) (y)
猜你喜欢
  • 1970-01-01
  • 2018-02-10
  • 1970-01-01
  • 2018-08-20
  • 1970-01-01
  • 2017-11-28
  • 2018-01-26
  • 2021-11-05
  • 2016-11-24
相关资源
最近更新 更多