1

I'm trying to read weight and bias in a caffe framework with c++. Here is my code

shared_ptr<Blob<float> >& weight = current_layer->blobs()[0];//for weights
shared_ptr<Blob<float> >& bias = current_layer->blobs()[1];//for bias

But if for some model the bias is not present or defined it throughs a segmentation fault error.

So which function returns a boolean value which indicates the presens of bias and how to call the function in c++?

Shai
  • 111,146
  • 38
  • 238
  • 371
Ganesh M S
  • 1,073
  • 2
  • 13
  • 24
  • 2
    Why `shared_ptr >& weight` and not `shared_ptr > weight`? If you only take a reference to a shared pointer the object may be destroyed because taking reference does not increase the internal reference count. Dereferencing the shared pointer reference may produce the undefined behavior. – wally Oct 30 '17 at 12:15
  • I got it and try the above suggested method Rex. can you please answer the above mentioned question? – Ganesh M S Oct 30 '17 at 12:42

2 Answers2

1

The blobs returned from current_layer->blobs() are stored in a std::vector, you can use its size property:

if (current_layer->blobs().size() > 1) {
    shared_ptr<Blob<float> >& bias = current_layer->blobs()[1];//for bias
}

See this similar answer for python interface for more details.

Shai
  • 111,146
  • 38
  • 238
  • 371
1
const std::vector<string> lnames = net_->layer_names();

for (int layer_index = 0; layer_index < net_->layer_names().size(); ++layer_index)
{
     const shared_ptr<Layer<float> > CAlayer = net_->layer_by_name(lnames[layer_index]);
     std::cout << lnames[layer_index] << std::endl;

     if(CAlayer->blobs().size() > 1)
     {
             std::cout << "weight-shape" << CAlayer->blobs()[0]->shape_string() << std::endl;
             std::cout << "weight-count" << CAlayer->blobs()[0]->count() << std::endl;
             std::cout << "bias-shape" << CAlayer->blobs()[1]->shape_string() << std::endl;
             std::cout << "bias-count" << CAlayer->blobs()[1]->count() << std::endl;
     }
}

Eventally the data (weights & bias params) can be fetched from

 CAlayer->blobs()[0]->cpu_data()[...] 
ShreeVidhya
  • 123
  • 9