caffe源码解析-inner_product_layer

2024-08-31 21:38

本文主要是介绍caffe源码解析-inner_product_layer,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

打开inner_product_layer.hpp文件,发现全连接层是非常清晰简单的,我们主要关注如下四个函数就行。

  1. LayerSetUp(SetUp的作用一般用于初始化,比如网络结构参数的获取)
  2. Reshape
  3. Forward_cpu
  4. Backward_cpu

**

inner_product_layer.hpp

**

namespace caffe {
template <typename Dtype>
class InnerProductLayer : public Layer<Dtype> {public:explicit InnerProductLayer(const LayerParameter& param): Layer<Dtype>(param) {}virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom,const vector<Blob<Dtype>*>& top);virtual void Reshape(const vector<Blob<Dtype>*>& bottom,const vector<Blob<Dtype>*>& top);virtual inline const char* type() const { return "InnerProduct"; }virtual inline int ExactNumBottomBlobs() const { return 1; }virtual inline int ExactNumTopBlobs() const { return 1; }protected:virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom,const vector<Blob<Dtype>*>& top);virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom,const vector<Blob<Dtype>*>& top);virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom);virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom);int M_;//batchsizeint K_;//输入神经元数目int N_;//输出神经元数目bool bias_term_;Blob<Dtype> bias_multiplier_;//一般是全为1的向量,方便利用矩阵乘法进行向量的拷贝bool transpose_;  ///< if true, assume transposed weights
};}  // namespace caffe

**

LayerSetUp

**

template <typename Dtype>
//SetUp的作用一般用于初始化,比如网络结构参数的获取
void InnerProductLayer<Dtype>::LayerSetUp(const vector<Blob<Dtype>*>& bottom,const vector<Blob<Dtype>*>& top)
{//获取输出神经元个数const int num_output = this->layer_param_.inner_product_param().num_output();//bool类型,是否存在偏置项bias_term_ = this->layer_param_.inner_product_param().bias_term();// bool类型,是否对权重矩阵进行转置transpose_ = this->layer_param_.inner_product_param().transpose();N_ = num_output;//optional int32 axis = 5 [default = 1];所以默认情况,axis=1const int axis = bottom[0]->CanonicalAxisIndex(this->layer_param_.inner_product_param().axis());// Dimensions starting from "axis" are "flattened" into a single// length K_ vector. For example, if bottom[0]'s shape is (N, C, H, W),// and axis == 1, N inner products with dimension CHW are performed.//K_=C*H*WK_ = bottom[0]->count(axis);// Check if we need to set up the weights//blobs_这个成员变量一般是存放layer的权重和偏置if (this->blobs_.size() > 0){LOG(INFO) << "Skipping parameter initialization";}else{if (bias_term_){//如果有偏置,则申请两块区域this->blobs_.resize(2);}else{//否则就只申请权重的偏置this->blobs_.resize(1);}// Initialize the weightsvector<int> weight_shape(2);if (transpose_){weight_shape[0] = K_;weight_shape[1] = N_;}else{weight_shape[0] = N_;weight_shape[1] = K_;}//根据权重的大小,开辟内存//一般权重的是1*1*K*N,其中K是输入神经元,N是输出神经元this->blobs_[0].reset(new Blob<Dtype>(weight_shape));// fill the weights//shared_ptr是智能指针,这行的作用是根据配置文件,获取权重初始化函数shared_ptr<Filler<Dtype> > weight_filler(GetFiller<Dtype>(this->layer_param_.inner_product_param().weight_filler()));//利用初始化函数进行权重的初始值填充weight_filler->Fill(this->blobs_[0].get());// If necessary, intiialize and fill the bias termif (bias_term_){vector<int> bias_shape(1, N_);this->blobs_[1].reset(new Blob<Dtype>(bias_shape));shared_ptr<Filler<Dtype> > bias_filler(GetFiller<Dtype>(this->layer_param_.inner_product_param().bias_filler()));bias_filler->Fill(this->blobs_[1].get());}}  // parameter initializationthis->param_propagate_down_.resize(this->blobs_.size(), true);
}

*Reshape*

这个函数具体是干嘛的,我不是特别清楚,但是看代码的意思就是为top[0]和偏置申请了内存资源。

template <typename Dtype>
void InnerProductLayer<Dtype>::Reshape(const vector<Blob<Dtype>*>& bottom,const vector<Blob<Dtype>*>& top)
{// Figure out the dimensionsconst int axis = bottom[0]->CanonicalAxisIndex(this->layer_param_.inner_product_param().axis());const int new_K = bottom[0]->count(axis);CHECK_EQ(K_, new_K)<< "Input size incompatible with inner product parameters.";// The first "axis" dimensions are independent inner products; the total// number of these is M_, the product over these dimensions.M_ = bottom[0]->count(0, axis);// The top shape will be the bottom shape with the flattened axes dropped,// and replaced by a single axis with dimension num_output (N_).vector<int> top_shape = bottom[0]->shape();top_shape.resize(axis + 1);top_shape[axis] = N_;top[0]->Reshape(top_shape);// Set up the bias multiplierif (bias_term_){vector<int> bias_shape(1, M_);bias_multiplier_.Reshape(bias_shape);caffe_set(M_, Dtype(1), bias_multiplier_.mutable_cpu_data());}
}

**

Forward_cpu

**

template <typename Dtype>
void InnerProductLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom,const vector<Blob<Dtype>*>& top)
{//获得输入数据的指针bottom_dataconst Dtype* bottom_data = bottom[0]->cpu_data();//获得输出数据的指针top_dataDtype* top_data = top[0]->mutable_cpu_data();//获得权重数据的指针weightconst Dtype* weight = this->blobs_[0]->cpu_data();//调用矩阵乘法完成y=w*x,其中x是输入神经元,y是输出神经元caffe_cpu_gemm<Dtype>(CblasNoTrans, transpose_ ? CblasNoTrans : CblasTrans,M_, N_, K_, (Dtype)1.,bottom_data, weight, (Dtype)0., top_data);if (bias_term_){//加上偏置caffe_cpu_gemm<Dtype>(CblasNoTrans, CblasNoTrans, M_, N_, 1, (Dtype)1.,bias_multiplier_.cpu_data(),this->blobs_[1]->cpu_data(), (Dtype)1., top_data);}
}

补充一下:caffe矩阵乘法调用的是cblas_dgemm这个函数,而这个函数的定义和用法可以参照该网址;

//该函数主要完成C=alpha*A*B+beta*C的任务
template<>
void caffe_cpu_gemm<double>(const CBLAS_TRANSPOSE TransA,const CBLAS_TRANSPOSE TransB,const int M,const int N,const int K,const double alpha,const double* A,const double* B,const double beta,double* C)
{int lda = (TransA == CblasNoTrans) ? K : M;int ldb = (TransB == CblasNoTrans) ? N : K;cblas_dgemm(CblasRowMajor,//行优先还是列优先,caffe中的数据都默认为行优先TransA,//A矩阵是否转置TransB,//B矩阵是否转置M,//A默认情况的行,C的行N,//B默认情况的列,C的列K,//A的列,B的行,这三个参数是不随矩阵是否转置发生变化的alpha,A,//A矩阵默认为M*K,如果是K*M则需要设置TransA对矩阵进行转置lda,//代表A矩阵转置前的列数B,ldb,//代表B矩阵转置前的列数beta,C,N);//代表C矩阵的列
}

**

Backward_cpu

**
BP算法可以分解为三部分:

  1. 先获得权重的增量,这个根据BP的原理,等于输入值和残差的乘积加和
  2. 然后获得偏置bias的增量,这个根据BP的原理,直接等于输出的残差
  3. 最后是更新输入的残差,这样才能逐层反向传递

对应的数学公式如下:
这里写图片描述

这里写图片描述

template <typename Dtype>
void InnerProductLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top,const vector<bool>& propagate_down,const vector<Blob<Dtype>*>& bottom)
{//如果进行反向传播,这个标志的意义在于,预训练时有可能某些layer不需要进行反向传播if (this->param_propagate_down_[0]){//获得输出的残差const Dtype* top_diff = top[0]->cpu_diff();//获得输入数据const Dtype* bottom_data = bottom[0]->cpu_data();// Gradient with respect to weight,起始反向转播可以分为三步//1.先获得权重的增量,这个根据BP的原理,等于输入值和残差的乘积加和//权重进行转置if (transpose_){//bottom_data是输入数据,是一个M*K的矩阵//top_diff是输出的残差,是一个M*N的矩阵//this->blobs_[0]->mutable_cpu_diff()是权重的增量,是一个K*N的矩阵caffe_cpu_gemm<Dtype>(CblasTrans, CblasNoTrans,K_, N_, M_,(Dtype)1., bottom_data, top_diff,(Dtype)1., this->blobs_[0]->mutable_cpu_diff());}//权重不进行转置else{caffe_cpu_gemm<Dtype>(CblasTrans, CblasNoTrans,N_, K_, M_,(Dtype)1., top_diff, bottom_data,(Dtype)1., this->blobs_[0]->mutable_cpu_diff());}}if (bias_term_ && this->param_propagate_down_[1]){const Dtype* top_diff = top[0]->cpu_diff();// Gradient with respect to bias//2.然后获得偏置bias的增量,这个根据BP的原理,直接等于输出的残差//bias_multiplier_.cpu_data()是一个1*M的单位向量caffe_cpu_gemv<Dtype>(CblasTrans, M_, N_, (Dtype)1., top_diff,bias_multiplier_.cpu_data(), (Dtype)1.,this->blobs_[1]->mutable_cpu_diff());}if (propagate_down[0]){const Dtype* top_diff = top[0]->cpu_diff();// Gradient with respect to bottom data//3.最后是更新输入的残差,这样才能逐层反向传递if (transpose_){//根据BP原理,输出(下一层)的残差是权重和输出(上一层)//残差的加权和,再乘以激活函数的导数。但是这个激活函数的//caffe丢给了激活函数层,所以这里就不需要//top_diff 是输出残差//this->blobs_[0]->cpu_data()是权重//bottom[0]->mutable_cpu_diff()便是输入的残差caffe_cpu_gemm<Dtype>(CblasNoTrans, CblasTrans,M_, K_, N_,(Dtype)1., top_diff, this->blobs_[0]->cpu_data(),(Dtype)0., bottom[0]->mutable_cpu_diff());}else{caffe_cpu_gemm<Dtype>(CblasNoTrans, CblasNoTrans,M_, K_, N_,(Dtype)1., top_diff, this->blobs_[0]->cpu_data(),(Dtype)0., bottom[0]->mutable_cpu_diff());}}
}

这篇关于caffe源码解析-inner_product_layer的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1125068

相关文章

全面解析HTML5中Checkbox标签

《全面解析HTML5中Checkbox标签》Checkbox是HTML5中非常重要的表单元素之一,通过合理使用其属性和样式自定义方法,可以为用户提供丰富多样的交互体验,这篇文章给大家介绍HTML5中C... 在html5中,Checkbox(复选框)是一种常用的表单元素,允许用户在一组选项中选择多个项目。本

Python包管理工具核心指令uvx举例详细解析

《Python包管理工具核心指令uvx举例详细解析》:本文主要介绍Python包管理工具核心指令uvx的相关资料,uvx是uv工具链中用于临时运行Python命令行工具的高效执行器,依托Rust实... 目录一、uvx 的定位与核心功能二、uvx 的典型应用场景三、uvx 与传统工具对比四、uvx 的技术实

SpringBoot排查和解决JSON解析错误(400 Bad Request)的方法

《SpringBoot排查和解决JSON解析错误(400BadRequest)的方法》在开发SpringBootRESTfulAPI时,客户端与服务端的数据交互通常使用JSON格式,然而,JSON... 目录问题背景1. 问题描述2. 错误分析解决方案1. 手动重新输入jsON2. 使用工具清理JSON3.

Redis过期删除机制与内存淘汰策略的解析指南

《Redis过期删除机制与内存淘汰策略的解析指南》在使用Redis构建缓存系统时,很多开发者只设置了EXPIRE但却忽略了背后Redis的过期删除机制与内存淘汰策略,下面小编就来和大家详细介绍一下... 目录1、简述2、Redis http://www.chinasem.cn的过期删除策略(Key Expir

Go学习记录之runtime包深入解析

《Go学习记录之runtime包深入解析》Go语言runtime包管理运行时环境,涵盖goroutine调度、内存分配、垃圾回收、类型信息等核心功能,:本文主要介绍Go学习记录之runtime包的... 目录前言:一、runtime包内容学习1、作用:① Goroutine和并发控制:② 垃圾回收:③ 栈和

Spring组件实例化扩展点之InstantiationAwareBeanPostProcessor使用场景解析

《Spring组件实例化扩展点之InstantiationAwareBeanPostProcessor使用场景解析》InstantiationAwareBeanPostProcessor是Spring... 目录一、什么是InstantiationAwareBeanPostProcessor?二、核心方法解

深入解析 Java Future 类及代码示例

《深入解析JavaFuture类及代码示例》JavaFuture是java.util.concurrent包中用于表示异步计算结果的核心接口,下面给大家介绍JavaFuture类及实例代码,感兴... 目录一、Future 类概述二、核心工作机制代码示例执行流程2. 状态机模型3. 核心方法解析行为总结:三

springboot项目中使用JOSN解析库的方法

《springboot项目中使用JOSN解析库的方法》JSON,全程是JavaScriptObjectNotation,是一种轻量级的数据交换格式,本文给大家介绍springboot项目中使用JOSN... 目录一、jsON解析简介二、Spring Boot项目中使用JSON解析1、pom.XML文件引入依

Python中文件读取操作漏洞深度解析与防护指南

《Python中文件读取操作漏洞深度解析与防护指南》在Web应用开发中,文件操作是最基础也最危险的功能之一,这篇文章将全面剖析Python环境中常见的文件读取漏洞类型,成因及防护方案,感兴趣的小伙伴可... 目录引言一、静态资源处理中的路径穿越漏洞1.1 典型漏洞场景1.2 os.path.join()的陷

C#代码实现解析WTGPS和BD数据

《C#代码实现解析WTGPS和BD数据》在现代的导航与定位应用中,准确解析GPS和北斗(BD)等卫星定位数据至关重要,本文将使用C#语言实现解析WTGPS和BD数据,需要的可以了解下... 目录一、代码结构概览1. 核心解析方法2. 位置信息解析3. 经纬度转换方法4. 日期和时间戳解析5. 辅助方法二、L