日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 人文社科 > 生活经验 >内容正文

生活经验

Caffe源码中layer文件分析

發(fā)布時間:2023/11/27 生活经验 34 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Caffe源码中layer文件分析 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

Caffe源碼(caffe version commit: 09868ac , date: 2015.08.15)中有一些重要的頭文件,這里介紹下include/caffe/layer.hpp文件的內(nèi)容:

1.??????include文件:

(1)、<caffe/blob.hpp>:此文件的介紹可以參考:http://blog.csdn.net/fengbingchun/article/details/59106613

(2)、<caffe/common.hpp>:此文件的介紹可以參考:http://blog.csdn.net/fengbingchun/article/details/54955236

(3)、<caffe/layer_factory.hpp>:此文件的介紹可以參考:http://blog.csdn.net/fengbingchun/article/details/54310956

(4)、<caffe/proto/caffe.pb.h>:此文件的介紹可以參考:http://blog.csdn.net/fengbingchun/article/details/55267162

(5)、<caffe/util/device_alternate.hpp>:此文件的介紹可以參考:http://blog.csdn.net/fengbingchun/article/details/54955236

2.????????類Layer:抽象基類,有純虛函數(shù),不能實例化,定義了所有l(wèi)ayer的基本接口,具體的每個layer完成一類特定的計算

Layer是Caffe模型的本質(zhì)內(nèi)容和執(zhí)行計算的基本單元。Layer可以進行很多運算,如convolve(卷積)、pool(池化)、inner product(內(nèi)積),rectified-linear和sigmoid等非線性運算,元素級的數(shù)據(jù)變換,normalize(歸一化)、load data(數(shù)據(jù)加載)、softmax和hinge等losses(損失計算)。可在Caffe的 ?http://caffe.berkeleyvision.org/tutorial/layers.html? (層目錄)中查看所有操作,其囊括了絕大部分目前最前沿的深度學(xué)習(xí)任務(wù)所需要的層類型。

一個layer通過bottom(底部) 連接層接收blobs數(shù)據(jù),通過top(頂部)連接層輸出blobs數(shù)據(jù)。Caffe中每種類型layer的參數(shù)說明定義在caffe.proto文件中,具體的layer參數(shù)值則定義在具體應(yīng)用的prototxt網(wǎng)絡(luò)結(jié)構(gòu)說明文件中。

在Caffe中,一個網(wǎng)絡(luò)的大部分功能都是以layer的形式去展開的。在創(chuàng)建一個Caffe模型的時候,也是以layer為基礎(chǔ)進行的,需按照caffe.proto中定義的網(wǎng)絡(luò)及參數(shù)格式定義網(wǎng)絡(luò)prototxt文件。在.prototxt文件中會有很多個layer {? } 字段。

每一個layer都定義了3種重要的運算:setup(初始化設(shè)置),forward(前向傳播),backward(反向傳播)。

(1)、setup:在模型初始化時重置layers及其相互之間的連接;

(2)、forward:從bottom層中接收數(shù)據(jù),進行計算后將輸出送人到top層中;

(3)、backward:給定相對于top層輸出的梯度,計算其相對于輸入的梯度,并傳遞到bottom層。一個有參數(shù)的layer需要計算相對于各個參數(shù)的梯度值并存儲在內(nèi)部。

特別地,forward和backward函數(shù)分別有CPU和GPU兩張實現(xiàn)方式。如果沒有實現(xiàn)GPU版本,那么layer將轉(zhuǎn)向作為備用選項的CPU方式。這樣會增加額外的數(shù)據(jù)傳送成本(輸入數(shù)據(jù)由GPU上復(fù)制到CPU,之后輸出數(shù)據(jù)從CPU又復(fù)制回到GPU)。

總的來說,Layer承擔(dān)了網(wǎng)絡(luò)的兩個核心操作:forward pass(前向傳播)----接收輸入并計算輸出;backward pass(反向傳播)----接收關(guān)于輸出的梯度,計算相對于參數(shù)和輸入的梯度并反向傳播給在它前面的層。由此組成了每個layer的前向和反向傳播。

Layer是網(wǎng)絡(luò)的基本單元,由此派生出了各種層類。在Layer中input data用bottom表示,output data用top表示。由于Caffe網(wǎng)絡(luò)的組合性和其代碼的模塊化,自定義layer是很容易的。只要定義好layer的setup(初始化設(shè)置)、forward(前向傳播,根據(jù)input計算output)和backward(反向傳播,根據(jù)output計算input的梯度),就可將layer納入到網(wǎng)絡(luò)中。

前傳(forward)過程為給定的待推斷的輸入計算輸出。在前傳過程中,Caffe組合每一層的計算以得到整個模型的計算”函數(shù)”。本過程自底向上進行。

反傳(backward)過程根據(jù)損失來計算梯度從而進行學(xué)習(xí)。在反傳過程中,Caffe通過自動求導(dǎo)并反向組合每一層的梯度來計算整個網(wǎng)絡(luò)的梯度。這就是反傳過程的本質(zhì)。本過程自頂向下進行。

反傳過程以損失開始,然后根據(jù)輸出計算梯度。根據(jù)鏈?zhǔn)綔?zhǔn)則,逐層計算出模型其余部分的梯度。有參數(shù)的層,會在反傳過程中根據(jù)參數(shù)計算梯度。

與大多數(shù)的機器學(xué)習(xí)模型一樣,在Caffe中,學(xué)習(xí)是由一個損失函數(shù)驅(qū)動的(通常也被稱為誤差、代價或者目標(biāo)函數(shù))。一個損失函數(shù)通過將參數(shù)集(即當(dāng)前的網(wǎng)絡(luò)權(quán)值)映射到一個可以標(biāo)識這些參數(shù)”不良程度”的標(biāo)量值來學(xué)習(xí)目標(biāo)。因此,學(xué)習(xí)的目的是找到一個網(wǎng)絡(luò)權(quán)重的集合,使得損失函數(shù)最小。

在Caffe中,損失是通過網(wǎng)絡(luò)的前向計算得到的。每一層由一系列的輸入blobs(bottom),然后產(chǎn)生一系列的輸出blobs(top)。這些層的某些輸出可以用來作為損失函數(shù)。典型的一對多分類任務(wù)的損失函數(shù)是softMaxWithLoss函數(shù)。

Caffe中每種類型layer的參數(shù)說明定義在caffe.proto文件中,具體的layer參數(shù)值則定義在具體應(yīng)用的protobuf網(wǎng)絡(luò)結(jié)構(gòu)說明文件中。

注:以上關(guān)于Layer內(nèi)容的介紹主要摘自由CaffeCN社區(qū)翻譯的《Caffe官方教程中譯本》。

<caffe/layer.hpp>文件的詳細(xì)介紹如下:

#ifndef CAFFE_LAYER_H_
#define CAFFE_LAYER_H_#include <algorithm>
#include <string>
#include <vector>#include "caffe/blob.hpp"
#include "caffe/common.hpp"
#include "caffe/layer_factory.hpp"
#include "caffe/proto/caffe.pb.h"
#include "caffe/util/device_alternate.hpp"/**Forward declare boost::thread instead of including boost/thread.hppto avoid a boost/NVCC issues (#1009, #1010) on OSX.*/
// 前向聲明boost的互斥類:boost::mutex
namespace boost { class mutex; }namespace caffe {
/*** @brief An interface for the units of computation which can be composed into a*        Net.** Layer%s must implement a Forward function, in which they take their input* (bottom) Blob%s (if any) and compute their output Blob%s (if any).* They may also implement a Backward function, in which they compute the error* gradients with respect to their input Blob%s, given the error gradients with* their output Blob%s.*/
template <typename Dtype>
class Layer { // 抽象基類,有純虛函數(shù),不能實例化,定義了所有l(wèi)ayer的基本接口public:/*** You should not implement your own constructor. Any set up code should go* to SetUp(), where the dimensions of the bottom blobs are provided to the* layer.*/
// 顯式構(gòu)造函數(shù),不需要重寫,獲得成員變量layer_param_、phase_、blobs_的值explicit Layer(const LayerParameter& param): layer_param_(param), is_shared_(false) {// Set phase and copy blobs (if there are any).phase_ = param.phase();if (layer_param_.blobs_size() > 0) {blobs_.resize(layer_param_.blobs_size());for (int i = 0; i < layer_param_.blobs_size(); ++i) {blobs_[i].reset(new Blob<Dtype>());blobs_[i]->FromProto(layer_param_.blobs(i));}}}
// 虛析構(gòu)函數(shù)virtual ~Layer() {}/*** @brief Implements common layer setup functionality.** @param bottom the preshaped input blobs* @param top*     the allocated but unshaped output blobs, to be shaped by Reshape** Checks that the number of bottom and top blobs is correct.* Calls LayerSetUp to do special layer setup for individual layer types,* followed by Reshape to set up sizes of top blobs and internal buffers.* Sets up the loss weight multiplier blobs for any non-zero loss weights.* This method may not be overridden.*/
// layer初始化,此方法不需要重寫void SetUp(const vector<Blob<Dtype>*>& bottom,const vector<Blob<Dtype>*>& top) {InitMutex();CheckBlobCounts(bottom, top);LayerSetUp(bottom, top);Reshape(bottom, top);SetLossWeights(top);}/*** @brief Does layer-specific setup: your layer should implement this function*        as well as Reshape.** @param bottom*     the preshaped input blobs, whose data fields store the input data for*     this layer* @param top*     the allocated but unshaped output blobs** This method should do one-time layer specific setup. This includes reading* and processing relevent parameters from the <code>layer_param_</code>.* Setting up the shapes of top blobs and internal buffers should be done in* <code>Reshape</code>, which will be called before the forward pass to* adjust the top blob sizes.*/
// 通過Layer參數(shù)即LayerParameter類獲得layer中某些成員變量的值virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom,const vector<Blob<Dtype>*>& top) {}/*** @brief Whether a layer should be shared by multiple nets during data*        parallelism. By default, all layers except for data layers should*        not be shared. data layers should be shared to ensure each worker*        solver access data sequentially during data parallelism.*/
// 獲得layer data共享狀態(tài):一個layer的data是否被多個net共享virtual inline bool ShareInParallel() const { return false; }/** @brief Return whether this layer is actually shared by other nets.*         If ShareInParallel() is true and using more than one GPU and the*         net has TRAIN phase, then this function is expected return true.*/
// 獲得layer是否被其它net共享inline bool IsShared() const { return is_shared_; }/** @brief Set whether this layer is actually shared by other nets*         If ShareInParallel() is true and using more than one GPU and the*         net has TRAIN phase, then is_shared should be set true.*/
// 設(shè)置layer是否被其它net共享inline void SetShared(bool is_shared) {CHECK(ShareInParallel() || !is_shared)<< type() << "Layer does not support sharing.";is_shared_ = is_shared;}/*** @brief Adjust the shapes of top blobs and internal buffers to accommodate*        the shapes of the bottom blobs.** @param bottom the input blobs, with the requested input shapes* @param top the top blobs, which should be reshaped as needed** This method should reshape top blobs as needed according to the shapes* of the bottom (input) blobs, as well as reshaping any internal buffers* and making any other necessary adjustments so that the layer can* accommodate the bottom blobs.*/
// 調(diào)整top blobs的shapevirtual void Reshape(const vector<Blob<Dtype>*>& bottom,const vector<Blob<Dtype>*>& top) = 0;/*** @brief Given the bottom blobs, compute the top blobs and the loss.** @param bottom*     the input blobs, whose data fields store the input data for this layer* @param top*     the preshaped output blobs, whose data fields will store this layers'*     outputs* \return The total loss from the layer.** The Forward wrapper calls the relevant device wrapper function* (Forward_cpu or Forward_gpu) to compute the top blob values given the* bottom blobs.  If the layer has any non-zero loss_weights, the wrapper* then computes and returns the loss.** Your layer should implement Forward_cpu and (optionally) Forward_gpu.*/
// 前向傳播,通過輸入bottom blobs,計算輸出top blobs和返回loss和inline Dtype Forward(const vector<Blob<Dtype>*>& bottom,const vector<Blob<Dtype>*>& top);/*** @brief Given the top blob error gradients, compute the bottom blob error*        gradients.** @param top*     the output blobs, whose diff fields store the gradient of the error*     with respect to themselves* @param propagate_down*     a vector with equal length to bottom, with each index indicating*     whether to propagate the error gradients down to the bottom blob at*     the corresponding index* @param bottom*     the input blobs, whose diff fields will store the gradient of the error*     with respect to themselves after Backward is run** The Backward wrapper calls the relevant device wrapper function* (Backward_cpu or Backward_gpu) to compute the bottom blob diffs given the* top blob diffs.** Your layer should implement Backward_cpu and (optionally) Backward_gpu.*/
// 反向傳播,通過給定top blob誤差梯度,計算bottom blob誤差梯度inline void Backward(const vector<Blob<Dtype>*>& top,const vector<bool>& propagate_down,const vector<Blob<Dtype>*>& bottom);/*** @brief Returns the vector of learnable parameter blobs.*/
// 獲得layer的權(quán)值、偏置等vector<shared_ptr<Blob<Dtype> > >& blobs() {return blobs_;}/*** @brief Returns the layer parameter.*/
// 獲得layer的配置參數(shù)const LayerParameter& layer_param() const { return layer_param_; }/*** @brief Writes the layer parameter to a protocol buffer*/
// 序列化函數(shù),將layer參數(shù)寫入protobuf文件virtual void ToProto(LayerParameter* param, bool write_diff = false);/*** @brief Returns the scalar loss associated with a top blob at a given index.*/
// 獲得top blob指定index的loss值inline Dtype loss(const int top_index) const {return (loss_.size() > top_index) ? loss_[top_index] : Dtype(0);}/*** @brief Sets the loss associated with a top blob at a given index.*/
// 設(shè)置top blob指定index的loss值inline void set_loss(const int top_index, const Dtype value) {if (loss_.size() <= top_index) {loss_.resize(top_index + 1, Dtype(0));}loss_[top_index] = value;}/*** @brief Returns the layer type.*/
// 獲得layer的類型virtual inline const char* type() const { return ""; }/*** @brief Returns the exact number of bottom blobs required by the layer,*        or -1 if no exact number is required.** This method should be overridden to return a non-negative value if your* layer expects some exact number of bottom blobs.*/
// 獲得layer所需的bottom blobs的個數(shù)virtual inline int ExactNumBottomBlobs() const { return -1; }/*** @brief Returns the minimum number of bottom blobs required by the layer,*        or -1 if no minimum number is required.** This method should be overridden to return a non-negative value if your* layer expects some minimum number of bottom blobs.*/
// 獲得layer所需的bottom blobs的最少個數(shù)virtual inline int MinBottomBlobs() const { return -1; }/*** @brief Returns the maximum number of bottom blobs required by the layer,*        or -1 if no maximum number is required.** This method should be overridden to return a non-negative value if your* layer expects some maximum number of bottom blobs.*/
// 獲得layer所需的bottom blobs的最多個數(shù)virtual inline int MaxBottomBlobs() const { return -1; }/*** @brief Returns the exact number of top blobs required by the layer,*        or -1 if no exact number is required.** This method should be overridden to return a non-negative value if your* layer expects some exact number of top blobs.*/
// 獲得layer所需的top blobs的個數(shù)virtual inline int ExactNumTopBlobs() const { return -1; }/*** @brief Returns the minimum number of top blobs required by the layer,*        or -1 if no minimum number is required.** This method should be overridden to return a non-negative value if your* layer expects some minimum number of top blobs.*/
// 獲得layer所需的top blobs的最少個數(shù)virtual inline int MinTopBlobs() const { return -1; }/*** @brief Returns the maximum number of top blobs required by the layer,*        or -1 if no maximum number is required.** This method should be overridden to return a non-negative value if your* layer expects some maximum number of top blobs.*/
// 獲得layer所需的top blobs的最多個數(shù)virtual inline int MaxTopBlobs() const { return -1; }/*** @brief Returns true if the layer requires an equal number of bottom and*        top blobs.** This method should be overridden to return true if your layer expects an* equal number of bottom and top blobs.*/
// 判斷l(xiāng)ayer所需的bottom blobs和top blobs的個數(shù)是否相等virtual inline bool EqualNumBottomTopBlobs() const { return false; }/*** @brief Return whether "anonymous" top blobs are created automatically*        by the layer.** If this method returns true, Net::Init will create enough "anonymous" top* blobs to fulfill the requirement specified by ExactNumTopBlobs() or* MinTopBlobs().*/
// 判斷l(xiāng)ayer所需的的top blobs是否需要由Net::Init來創(chuàng)建virtual inline bool AutoTopBlobs() const { return false; }/*** @brief Return whether to allow force_backward for a given bottom blob*        index.** If AllowForceBackward(i) == false, we will ignore the force_backward* setting and backpropagate to blob i only if it needs gradient information* (as is done when force_backward == false).*/
// 判斷l(xiāng)ayer指定的bottom blob是否需要強制梯度返回,因為有些layer其實不需要梯度信息virtual inline bool AllowForceBackward(const int bottom_index) const { return true; }/*** @brief Specifies whether the layer should compute gradients w.r.t. a*        parameter at a particular index given by param_id.** You can safely ignore false values and always compute gradients* for all parameters, but possibly with wasteful computation.*/
// 判斷l(xiāng)ayer指定的blob是否應(yīng)該計算梯度inline bool param_propagate_down(const int param_id) {return (param_propagate_down_.size() > param_id) ?param_propagate_down_[param_id] : false;}/*** @brief Sets whether the layer should compute gradients w.r.t. a*        parameter at a particular index given by param_id.*/
// 設(shè)置layer指定的blob是否應(yīng)該計算梯度inline void set_param_propagate_down(const int param_id, const bool value) {if (param_propagate_down_.size() <= param_id) {param_propagate_down_.resize(param_id + 1, true);}param_propagate_down_[param_id] = value;}protected:
// Caffe中類的成員變量名都帶有后綴"_",這樣就容易區(qū)分臨時變量和類成員變量/** The protobuf that stores the layer parameters */
// 配置的layer參數(shù),創(chuàng)建layer對象時,通過調(diào)用構(gòu)造函數(shù)從上層傳入,
// 關(guān)于LayerParameter類的具體參數(shù)可參考caffe.proto中的message LayerParameterLayerParameter layer_param_;/** The phase: TRAIN or TEST */
// layer狀態(tài):指定參與網(wǎng)絡(luò)的是train還是test,Phase phase_;/** The vector that stores the learnable parameters as a set of blobs. */
// 用于存儲layer的學(xué)習(xí)的參數(shù)如權(quán)值和偏置vector<shared_ptr<Blob<Dtype> > > blobs_;/** Vector indicating whether to compute the diff of each param blob. */
// 標(biāo)志是否為layer指定的blob計算梯度值vector<bool> param_propagate_down_;/** The vector that indicates whether each top blob has a non-zero weight in*  the objective function. */
// 標(biāo)志layer指定的top blob是否有一個非0權(quán)值vector<Dtype> loss_;/** @brief Using the CPU device, compute the layer output. */
// CPU實現(xiàn)layer的前向傳播virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom,const vector<Blob<Dtype>*>& top) = 0;/*** @brief Using the GPU device, compute the layer output.*        Fall back to Forward_cpu() if unavailable.*/
// GPU實現(xiàn)layer的前向傳播virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom,const vector<Blob<Dtype>*>& top) {// LOG(WARNING) << "Using CPU code as backup.";return Forward_cpu(bottom, top);}/*** @brief Using the CPU device, compute the gradients for any parameters and*        for the bottom blobs if propagate_down is true.*/
// CPU實現(xiàn)layer的反向傳播virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,const vector<bool>& propagate_down,const vector<Blob<Dtype>*>& bottom) = 0;/*** @brief Using the GPU device, compute the gradients for any parameters and*        for the bottom blobs if propagate_down is true.*        Fall back to Backward_cpu() if unavailable.*/
// GPU實現(xiàn)layer的反向傳播virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,const vector<bool>& propagate_down,const vector<Blob<Dtype>*>& bottom) {// LOG(WARNING) << "Using CPU code as backup.";Backward_cpu(top, propagate_down, bottom);}/*** Called by the parent Layer's SetUp to check that the number of bottom* and top Blobs provided as input match the expected numbers specified by* the {ExactNum,Min,Max}{Bottom,Top}Blobs() functions.*/
// 檢查bottom 和top blobs個數(shù)是否匹配virtual void CheckBlobCounts(const vector<Blob<Dtype>*>& bottom,const vector<Blob<Dtype>*>& top) {if (ExactNumBottomBlobs() >= 0) {CHECK_EQ(ExactNumBottomBlobs(), bottom.size())<< type() << " Layer takes " << ExactNumBottomBlobs()<< " bottom blob(s) as input.";}if (MinBottomBlobs() >= 0) {CHECK_LE(MinBottomBlobs(), bottom.size())<< type() << " Layer takes at least " << MinBottomBlobs()<< " bottom blob(s) as input.";}if (MaxBottomBlobs() >= 0) {CHECK_GE(MaxBottomBlobs(), bottom.size())<< type() << " Layer takes at most " << MaxBottomBlobs()<< " bottom blob(s) as input.";}if (ExactNumTopBlobs() >= 0) {CHECK_EQ(ExactNumTopBlobs(), top.size())<< type() << " Layer produces " << ExactNumTopBlobs()<< " top blob(s) as output.";}if (MinTopBlobs() >= 0) {CHECK_LE(MinTopBlobs(), top.size())<< type() << " Layer produces at least " << MinTopBlobs()<< " top blob(s) as output.";}if (MaxTopBlobs() >= 0) {CHECK_GE(MaxTopBlobs(), top.size())<< type() << " Layer produces at most " << MaxTopBlobs()<< " top blob(s) as output.";}if (EqualNumBottomTopBlobs()) {CHECK_EQ(bottom.size(), top.size())<< type() << " Layer produces one top blob as output for each "<< "bottom blob input.";}}/*** Called by SetUp to initialize the weights associated with any top blobs in* the loss function. Store non-zero loss weights in the diff blob.*/
// 設(shè)置top blobs中diff值inline void SetLossWeights(const vector<Blob<Dtype>*>& top) {const int num_loss_weights = layer_param_.loss_weight_size();if (num_loss_weights) {CHECK_EQ(top.size(), num_loss_weights) << "loss_weight must be ""unspecified or specified once per top blob.";for (int top_id = 0; top_id < top.size(); ++top_id) {const Dtype loss_weight = layer_param_.loss_weight(top_id);if (loss_weight == Dtype(0)) { continue; }this->set_loss(top_id, loss_weight);const int count = top[top_id]->count();Dtype* loss_multiplier = top[top_id]->mutable_cpu_diff();caffe_set(count, loss_weight, loss_multiplier);}}}private:/** Whether this layer is actually shared by other nets*/
//標(biāo)志當(dāng)前l(fā)ayer是否被其它net共享bool is_shared_;/** The mutex for sequential forward if this layer is shared */
// 聲明boost::mutex對象,互斥鎖變量shared_ptr<boost::mutex> forward_mutex_;/** Initialize forward_mutex_ */
// 初始化互斥鎖void InitMutex();/** Lock forward_mutex_ if this layer is shared */
// 如果layer是共享的則加鎖void Lock();/** Unlock forward_mutex_ if this layer is shared */
// 如果layer是共享的則解鎖void Unlock();// 禁止使用Layer類的拷貝和賦值操作DISABLE_COPY_AND_ASSIGN(Layer);
};  // class Layer// Forward and backward wrappers. You should implement the cpu and
// gpu specific implementations instead, and should not change these
// functions.
// 前向傳播,通過輸入bottom blobs,計算輸出top blobs和loss值
template <typename Dtype>
inline Dtype Layer<Dtype>::Forward(const vector<Blob<Dtype>*>& bottom,const vector<Blob<Dtype>*>& top) {// Lock during forward to ensure sequential forwardLock();Dtype loss = 0;Reshape(bottom, top);switch (Caffe::mode()) {case Caffe::CPU:Forward_cpu(bottom, top);for (int top_id = 0; top_id < top.size(); ++top_id) {if (!this->loss(top_id)) { continue; }const int count = top[top_id]->count();const Dtype* data = top[top_id]->cpu_data();const Dtype* loss_weights = top[top_id]->cpu_diff();loss += caffe_cpu_dot(count, data, loss_weights);}break;case Caffe::GPU:Forward_gpu(bottom, top);
#ifndef CPU_ONLYfor (int top_id = 0; top_id < top.size(); ++top_id) {if (!this->loss(top_id)) { continue; }const int count = top[top_id]->count();const Dtype* data = top[top_id]->gpu_data();const Dtype* loss_weights = top[top_id]->gpu_diff();Dtype blob_loss = 0;caffe_gpu_dot(count, data, loss_weights, &blob_loss);loss += blob_loss;}
#endifbreak;default:LOG(FATAL) << "Unknown caffe mode.";}Unlock();return loss;
}// 反向傳播,通過給定top blob誤差梯度,計算bottom blob誤差梯度
template <typename Dtype>
inline void Layer<Dtype>::Backward(const vector<Blob<Dtype>*>& top,const vector<bool>& propagate_down,const vector<Blob<Dtype>*>& bottom) {switch (Caffe::mode()) {case Caffe::CPU:Backward_cpu(top, propagate_down, bottom);break;case Caffe::GPU:Backward_gpu(top, propagate_down, bottom);break;default:LOG(FATAL) << "Unknown caffe mode.";}
}// Serialize LayerParameter to protocol buffer
// 序列化函數(shù),將layer參數(shù)寫入protobuf文件
template <typename Dtype>
void Layer<Dtype>::ToProto(LayerParameter* param, bool write_diff) {param->Clear();param->CopyFrom(layer_param_);param->clear_blobs();for (int i = 0; i < blobs_.size(); ++i) {blobs_[i]->ToProto(param->add_blobs(), write_diff);}
}}  // namespace caffe#endif  // CAFFE_LAYER_H_
在caffe.proto文件中,主要 有一個message是與layer 相關(guān)的,如下:
enum Phase { // layer狀態(tài):train、testTRAIN = 0;TEST = 1;
}// NOTE
// Update the next available ID when you add a new LayerParameter field.
//
// LayerParameter next available layer-specific ID: 137 (last added: reduction_param)
message LayerParameter { // Layer參數(shù)optional string name = 1; // the layer name, layer名字,可由自己任意制定optional string type = 2; // the layer type, layer類型,在具體層中寫定,可以通過type()函數(shù)獲得repeated string bottom = 3; // the name of each bottom blob, bottom名字,可有多個repeated string top = 4; // the name of each top blob,top名字,可有多個// The train / test phase for computation.optional Phase phase = 10; // layer狀態(tài):enum Phase {TRAIN = 0; TEST = 1;}// The amount of weight to assign each top blob in the objective.// Each layer assigns a default value, usually of either 0 or 1,// to each top blob.repeated float loss_weight = 5; // 個數(shù)必須與top blob一致// Specifies training parameters (multipliers on global learning constants,// and the name and other settings used for weight sharing).repeated ParamSpec param = 6; // train時用到的參數(shù)// The blobs containing the numeric parameters of the layer.repeated BlobProto blobs = 7; // blobs個數(shù)// Specifies on which bottoms the backpropagation should be skipped.// The size must be either 0 or equal to the number of bottoms.repeated bool propagate_down = 11; // 長度或者是0或者與bottoms個數(shù)一致// Rules controlling whether and when a layer is included in the network,// based on the current NetState.  You may specify a non-zero number of rules// to include OR exclude, but not both.  If no include or exclude rules are// specified, the layer is always included.  If the current NetState meets// ANY (i.e., one or more) of the specified rules, the layer is// included/excluded.repeated NetStateRule include = 8; // net state rulerepeated NetStateRule exclude = 9; // net state rule// Parameters for data pre-processing.optional TransformationParameter transform_param = 100; // 對data進行預(yù)處理包括縮放、剪切等// Parameters shared by loss layers.optional LossParameter loss_param = 101; // loss parameters// Layer type-specific parameters.//// Note: certain layers may have more than one computational engine// for their implementation. These layers include an Engine type and// engine parameter for selecting the implementation.// The default for the engine is set by the ENGINE switch at compile-time.// 具體layer參數(shù)optional AccuracyParameter accuracy_param = 102;optional ArgMaxParameter argmax_param = 103;optional ConcatParameter concat_param = 104;optional ContrastiveLossParameter contrastive_loss_param = 105;optional ConvolutionParameter convolution_param = 106;optional DataParameter data_param = 107;optional DropoutParameter dropout_param = 108;optional DummyDataParameter dummy_data_param = 109;optional EltwiseParameter eltwise_param = 110;optional ExpParameter exp_param = 111;optional FlattenParameter flatten_param = 135;optional HDF5DataParameter hdf5_data_param = 112;optional HDF5OutputParameter hdf5_output_param = 113;optional HingeLossParameter hinge_loss_param = 114;optional ImageDataParameter image_data_param = 115;optional InfogainLossParameter infogain_loss_param = 116;optional InnerProductParameter inner_product_param = 117;optional LogParameter log_param = 134;optional LRNParameter lrn_param = 118;optional MemoryDataParameter memory_data_param = 119;optional MVNParameter mvn_param = 120;optional PoolingParameter pooling_param = 121;optional PowerParameter power_param = 122;optional PReLUParameter prelu_param = 131;optional PythonParameter python_param = 130;optional ReductionParameter reduction_param = 136;optional ReLUParameter relu_param = 123;optional ReshapeParameter reshape_param = 133;optional SigmoidParameter sigmoid_param = 124;optional SoftmaxParameter softmax_param = 125;optional SPPParameter spp_param = 132;optional SliceParameter slice_param = 126;optional TanHParameter tanh_param = 127;optional ThresholdParameter threshold_param = 128;optional WindowDataParameter window_data_param = 129;
}

GitHub: https://github.com/fengbingchun/Caffe_Test

總結(jié)

以上是生活随笔為你收集整理的Caffe源码中layer文件分析的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。