學習Caffe(二)使用Caffe

如何使用Caffe

Caffe教程(http://robots.princeton.edu/courses/COS598/2015sp/slides/Caffe/caffe_tutorial.pdf

預備知識

Google Protocol Buffer

https://developers.google.com/protocol-buffers/docs/cpptutorial
Caffe數(shù)據(jù)的讀取、運算、存儲都是采用Google Protocol Buffer來進行的。PB是一種輕便、高效的結構化數(shù)據(jù)存儲格式,可以用于結構化數(shù)據(jù)串行化,很適合做數(shù)據(jù)存儲或 RPC 數(shù)據(jù)交換格式。它可用于通訊協(xié)議、數(shù)據(jù)存儲等領域的語言無關、平臺無關、可擴展的序列化結構數(shù)據(jù)格式。是一種效率和兼容性都很優(yōu)秀的二進制數(shù)據(jù)傳輸格式,目前提供了 C++、Java、Python 三種語言的 API。Caffe采用的是C++和Python的API。

轉(zhuǎn)載自https://github.com/shicai/Caffe_Manual/blob/master/ReadMe.md

初始化網(wǎng)絡

#include "caffe/caffe.hpp"
#include <string>
#include <vector>
using namespace caffe;

char *proto = "H:\\Models\\Caffe\\deploy.prototxt"; /* 加載CaffeNet的配置 */
Phase phase = TEST; /* or TRAIN */
Caffe::set_mode(Caffe::CPU);
// Caffe::set_mode(Caffe::GPU);
// Caffe::SetDevice(0);

//! Note: 后文所有提到的net,都是這個net
boost::shared_ptr< Net<float> > net(new caffe::Net<float>(proto, phase));

加載已訓練好的模型

char *model = "H:\\Models\\Caffe\\bvlc_reference_caffenet.caffemodel";    
net->CopyTrainedLayersFrom(model);

讀取模型中的每層的結構配置參數(shù)

char *model = "H:\\Models\\Caffe\\bvlc_reference_caffenet.caffemodel";
NetParameter param;
ReadNetParamsFromBinaryFileOrDie(model, &param);
int num_layers = param.layer_size();
for (int i = 0; i < num_layers; ++i)
{
    // 結構配置參數(shù):name,type,kernel size,pad,stride等
    LOG(ERROR) << "Layer " << i << ":" << param.layer(i).name() << "\t" << param.layer(i).type();
    if (param.layer(i).type() == "Convolution")
    {
        ConvolutionParameter conv_param = param.layer(i).convolution_param();
        LOG(ERROR) << "\t\tkernel size: " << conv_param.kernel_size()
            << ", pad: " << conv_param.pad()
            << ", stride: " << conv_param.stride();
    }
}

讀取圖像均值

char *mean_file = "H:\\Models\\Caffe\\imagenet_mean.binaryproto";
Blob<float> image_mean;
BlobProto blob_proto;
const float *mean_ptr;
unsigned int num_pixel;

bool succeed = ReadProtoFromBinaryFile(mean_file, &blob_proto);
if (succeed)
{
    image_mean.FromProto(blob_proto);
    num_pixel = image_mean.count(); /* NCHW=1x3x256x256=196608 */
    mean_ptr = (const float *) image_mean.cpu_data();
}

根據(jù)指定數(shù)據(jù),前向傳播網(wǎng)絡

//! Note: data_ptr指向已經(jīng)處理好(去均值的,符合網(wǎng)絡輸入圖像的長寬和Batch Size)的數(shù)據(jù)
void caffe_forward(boost::shared_ptr< Net<float> > & net, float *data_ptr)
{
    Blob<float>* input_blobs = net->input_blobs()[0];
    switch (Caffe::mode())
    {
    case Caffe::CPU:
        memcpy(input_blobs->mutable_cpu_data(), data_ptr,
            sizeof(float) * input_blobs->count());
        break;
    case Caffe::GPU:
        cudaMemcpy(input_blobs->mutable_gpu_data(), data_ptr,
            sizeof(float) * input_blobs->count(), cudaMemcpyHostToDevice);
        break;
    default:
        LOG(FATAL) << "Unknown Caffe mode.";
    } 
    net->ForwardPrefilled();
}

根據(jù)Feature層的名字獲取其在網(wǎng)絡中的Index

//! Note: Net的Blob是指,每個層的輸出數(shù)據(jù),即Feature Maps
// char *query_blob_name = "conv1";
unsigned int get_blob_index(boost::shared_ptr< Net<float> > & net, char *query_blob_name)
{
    std::string str_query(query_blob_name);    
    vector< string > const & blob_names = net->blob_names();
    for( unsigned int i = 0; i != blob_names.size(); ++i ) 
    { 
        if( str_query == blob_names[i] ) 
        { 
            return i;
        } 
    }
    LOG(FATAL) << "Unknown blob name: " << str_query;
}

讀取網(wǎng)絡指定Feature層數(shù)據(jù)

//! Note: 根據(jù)CaffeNet的deploy.prototxt文件,該Net共有15個Blob,從data一直到prob    
char *query_blob_name = "conv1"; /* data, conv1, pool1, norm1, fc6, prob, etc */
unsigned int blob_id = get_blob_index(net, query_blob_name);

boost::shared_ptr<Blob<float> > blob = net->blobs()[blob_id];
unsigned int num_data = blob->count(); /* NCHW=10x96x55x55 */
const float *blob_ptr = (const float *) blob->cpu_data();

根據(jù)文件列表,獲取特征,并存為二進制文件

詳見get_features.cpp文件:

主要包括三個步驟

  • 生成文件列表,格式與訓練用的類似,每行一個圖像
    包括文件全路徑、空格、標簽(沒有的話,可以置0)
  • 根據(jù)train_val或者deploy的prototxt,改寫生成feat.prototxt
    主要是將輸入層改為image_data層,最后加上prob和argmax(為了輸出概率和Top1/5預測標簽)
  • 根據(jù)指定參數(shù),運行程序后會生成若干個二進制文件,可以用MATLAB讀取數(shù)據(jù),進行分析

根據(jù)Layer的名字獲取其在網(wǎng)絡中的Index

//! Note: Layer包括神經(jīng)網(wǎng)絡所有層,比如,CaffeNet共有23層
// char *query_layer_name = "conv1";
unsigned int get_layer_index(boost::shared_ptr< Net<float> > & net, char *query_layer_name)
{
    std::string str_query(query_layer_name);    
    vector< string > const & layer_names = net->layer_names();
    for( unsigned int i = 0; i != layer_names.size(); ++i ) 
    { 
        if( str_query == layer_names[i] ) 
        { 
            return i;
        } 
    }
    LOG(FATAL) << "Unknown layer name: " << str_query;
}

讀取指定Layer的權重數(shù)據(jù)

//! Note: 不同于Net的Blob是Feature Maps,Layer的Blob是指Conv和FC等層的Weight和Bias
char *query_layer_name = "conv1";
const float *weight_ptr, *bias_ptr;
unsigned int layer_id = get_layer_index(net, query_layer_name);
boost::shared_ptr<Layer<float> > layer = net->layers()[layer_id];
std::vector<boost::shared_ptr<Blob<float>  >> blobs = layer->blobs();
if (blobs.size() > 0)
{
    weight_ptr = (const float *) blobs[0]->cpu_data();
    bias_ptr = (const float *) blobs[1]->cpu_data();
}

//! Note: 訓練模式下,讀取指定Layer的梯度數(shù)據(jù),與此相似,唯一的區(qū)別是將cpu_data改為cpu_diff

修改某層的Weight數(shù)據(jù)

const float* data_ptr;          /* 指向待寫入數(shù)據(jù)的指針, 源數(shù)據(jù)指針*/
float* weight_ptr = NULL;       /* 指向網(wǎng)絡中某層權重的指針,目標數(shù)據(jù)指針*/
unsigned int data_size;         /* 待寫入的數(shù)據(jù)量 */
char *layer_name = "conv1";     /* 需要修改的Layer名字 */

unsigned int layer_id = get_layer_index(net, query_layer_name);    
boost::shared_ptr<Blob<float> > blob = net->layers()[layer_id]->blobs()[0];

CHECK(data_size == blob->count());
switch (Caffe::mode())
{
case Caffe::CPU:
    weight_ptr = blob->mutable_cpu_data();
    break;
case Caffe::GPU:
    weight_ptr = blob->mutable_gpu_data();
    break;
default:
    LOG(FATAL) << "Unknown Caffe mode";
}
caffe_copy(blob->count(), data_ptr, weight_ptr);

//! Note: 訓練模式下,手動修改指定Layer的梯度數(shù)據(jù),與此相似
// mutable_cpu_data改為mutable_cpu_diff,mutable_gpu_data改為mutable_gpu_diff

保存新的模型

char* weights_file = "bvlc_reference_caffenet_new.caffemodel";
NetParameter net_param;
net->ToProto(&net_param, false);
WriteProtoToBinaryFile(net_param, weights_file);

Caffe中添加新的層

https://github.com/BVLC/caffe/wiki/Development

這里寫圖片描述

用預訓練網(wǎng)絡參數(shù)初始化

caffe的參數(shù)初始化是根據(jù)名字從caffemodel讀取的,只要修改名字,自己想要修改的層就能隨機初始化。

  • 修改名字,保留前面幾層的參數(shù),同時后面的參數(shù)設置較高的學習率,基礎學習率大概0.00001左右。
最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

  • 國家電網(wǎng)公司企業(yè)標準(Q/GDW)- 面向?qū)ο蟮挠秒娦畔?shù)據(jù)交換協(xié)議 - 報批稿:20170802 前言: 排版 ...
    庭說閱讀 12,535評論 6 13
  • Caffe GitHub頁面 1. Caffe目錄結構 data/用于存放下載的訓練數(shù)據(jù)docs/ 幫助文檔exa...
    sixfold_yuan閱讀 1,813評論 3 14
  • 簡介 用簡單的話來定義tcpdump,就是:dump the traffic on a network,根據(jù)使用者...
    保川閱讀 6,090評論 1 13
  • Spring Cloud為開發(fā)人員提供了快速構建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,695評論 19 139
  • 今天周六,每周放松的日子。挑選了幾個青花瓷的水仙盆,天氣暖起來之后,書房的銅錢草長的很快,已經(jīng)長成郁郁蔥蔥的一滿盆...
    Rene_Yu閱讀 578評論 0 0

友情鏈接更多精彩內(nèi)容