深度学习中的优化算法之NAG

2023-11-03

      之前在https://blog.csdn.net/fengbingchun/article/details/124648766 介绍过Momentum SGD,这里介绍下深度学习的另一种优化算法NAG。

      NAG:Nesterov Accelerated Gradient或Nesterov momentum,是梯度优化算法的扩展,在基于Momentum SGD的基础上作了改动。如下图所示,截图来自:https://arxiv.org/pdf/1609.04747.pdf

       基于动量的SGD在最小点附近会震荡,为了减少这些震荡,我们可以使用NAG。NAG与基于动量的SGD的区别在于更新梯度的方式不同。

       以下是与Momentum SGD不同的代码片段:

       1. 在原有枚举类Optimization的基础上新增NAG:

enum class Optimization {
	BGD, // Batch Gradient Descent
	SGD, // Stochastic Gradient Descent
	MBGD, // Mini-batch Gradient Descent
	SGD_Momentum, // SGD with Momentum
	AdaGrad, // Adaptive Gradient
	RMSProp, // Root Mean Square Propagation
	Adadelta, // an adaptive learning rate method
	Adam, // Adaptive Moment Estimation
	AdaMax, // a variant of Adam based on the infinity norm
	NAG // Nesterov Accelerated Gradient
};

       2. 计算z的方式不同:NAG使用z2

float LogisticRegression2::calculate_z(const std::vector<float>& feature) const
{
	float z{0.};
	for (int i = 0; i < feature_length_; ++i) {
		z += w_[i] * feature[i];
	}
	z += b_;

	return z;
}

float LogisticRegression2::calculate_z2(const std::vector<float>& feature, const std::vector<float>& vw) const
{
	float z{0.};
	for (int i = 0; i < feature_length_; ++i) {
		z += (w_[i] - mu_ * vw[i]) * feature[i];
	}
	z += b_;

	return z;
}

       3. calculate_gradient_descent函数:

void LogisticRegression2::calculate_gradient_descent(int start, int end)
{
	switch (optim_) {
		case Optimization::NAG: {
			int len = end - start;
			std::vector<float> v(feature_length_, 0.);
			std::vector<float> z(len, 0), dz(len, 0);
			for (int i = start, x = 0; i < end; ++i, ++x) {
				z[x] = calculate_z2(data_->samples[random_shuffle_[i]], v);
				dz[x] = calculate_loss_function_derivative(calculate_activation_function(z[x]), data_->labels[random_shuffle_[i]]);

				for (int j = 0; j < feature_length_; ++j) {
					float dw = data_->samples[random_shuffle_[i]][j] * dz[x];
					v[j] = mu_ * v[j] + alpha_ * dw; // formula 5
					w_[j] = w_[j] - v[j];
				}

				b_ -= (alpha_ * dz[x]);
			}
		}
			break;
		case Optimization::AdaMax: {
			int len = end - start;
			std::vector<float> m(feature_length_, 0.), u(feature_length_, 1e-8), mhat(feature_length_, 0.);
			std::vector<float> z(len, 0.), dz(len, 0.);
			float beta1t = 1.;
			for (int i = start, x = 0; i < end; ++i, ++x) {
				z[x] = calculate_z(data_->samples[random_shuffle_[i]]);
				dz[x] = calculate_loss_function_derivative(calculate_activation_function(z[x]), data_->labels[random_shuffle_[i]]);

				beta1t *= beta1_;

				for (int j = 0; j < feature_length_; ++j) {
					float dw = data_->samples[random_shuffle_[i]][j] * dz[x];
					m[j] = beta1_ * m[j] + (1. - beta1_) * dw; // formula 19
					u[j] = std::max(beta2_ * u[j], std::fabs(dw)); // formula 24

					mhat[j] = m[j] / (1. - beta1t); // formula 20

					// Note: need to ensure than u[j] cannot be 0.
					// (1). u[j] is initialized to 1e-8, or
					// (2). if u[j] is initialized to 0., then u[j] adjusts to (u[j] + 1e-8)
					w_[j] = w_[j] - alpha_ * mhat[j] / u[j]; // formula 25
				}

				b_ -= (alpha_ * dz[x]);
			}
		}
			break;
		case Optimization::Adam: {
			int len = end - start;
			std::vector<float> m(feature_length_, 0.), v(feature_length_, 0.), mhat(feature_length_, 0.), vhat(feature_length_, 0.);
			std::vector<float> z(len, 0.), dz(len, 0.);
			float beta1t = 1., beta2t = 1.;
			for (int i = start, x = 0; i < end; ++i, ++x) {
				z[x] = calculate_z(data_->samples[random_shuffle_[i]]);
				dz[x] = calculate_loss_function_derivative(calculate_activation_function(z[x]), data_->labels[random_shuffle_[i]]);

				beta1t *= beta1_;
				beta2t *= beta2_;

				for (int j = 0; j < feature_length_; ++j) {
					float dw = data_->samples[random_shuffle_[i]][j] * dz[x];
					m[j] = beta1_ * m[j] + (1. - beta1_) * dw; // formula 19
					v[j] = beta2_ * v[j] + (1. - beta2_) * (dw * dw); // formula 19

					mhat[j] = m[j] / (1. - beta1t); // formula 20
					vhat[j] = v[j] / (1. - beta2t); // formula 20

					w_[j] = w_[j] - alpha_ * mhat[j] / (std::sqrt(vhat[j]) + eps_); // formula 21
				}

				b_ -= (alpha_ * dz[x]);
			}
		}
			break;
		case Optimization::Adadelta: {
			int len = end - start;
			std::vector<float> g(feature_length_, 0.), p(feature_length_, 0.);
			std::vector<float> z(len, 0.), dz(len, 0.);
			for (int i = start, x = 0; i < end; ++i, ++x) {
				z[x] = calculate_z(data_->samples[random_shuffle_[i]]);
				dz[x] = calculate_loss_function_derivative(calculate_activation_function(z[x]), data_->labels[random_shuffle_[i]]);

				for (int j = 0; j < feature_length_; ++j) {
					float dw = data_->samples[random_shuffle_[i]][j] * dz[x];
					g[j] = mu_ * g[j] + (1. - mu_) * (dw * dw); // formula 10

					//float alpha = std::sqrt(p[j] + eps_) / std::sqrt(g[j] + eps_);
					float change = -std::sqrt(p[j] + eps_) / std::sqrt(g[j] + eps_) * dw; // formula 17
					w_[j] = w_[j] + change;

					p[j] = mu_ * p[j] +  (1. - mu_) * (change * change); // formula 15
				}

				b_ -= (eps_ * dz[x]);
			}
		}
			break;
		case Optimization::RMSProp: {
			int len = end - start;
			std::vector<float> g(feature_length_, 0.);
			std::vector<float> z(len, 0), dz(len, 0);
			for (int i = start, x = 0; i < end; ++i, ++x) {
				z[x] = calculate_z(data_->samples[random_shuffle_[i]]);
				dz[x] = calculate_loss_function_derivative(calculate_activation_function(z[x]), data_->labels[random_shuffle_[i]]);

				for (int j = 0; j < feature_length_; ++j) {
					float dw = data_->samples[random_shuffle_[i]][j] * dz[x];
					g[j] = mu_ * g[j] + (1. - mu_) * (dw * dw); // formula 18
					w_[j] = w_[j] - alpha_ * dw / std::sqrt(g[j] + eps_);
				}

				b_ -= (alpha_ * dz[x]);
			}
		}
			break;
		case Optimization::AdaGrad: {
			int len = end - start;
			std::vector<float> g(feature_length_, 0.);
			std::vector<float> z(len, 0), dz(len, 0);
			for (int i = start, x = 0; i < end; ++i, ++x) {
				z[x] = calculate_z(data_->samples[random_shuffle_[i]]);
				dz[x] = calculate_loss_function_derivative(calculate_activation_function(z[x]), data_->labels[random_shuffle_[i]]);

				for (int j = 0; j < feature_length_; ++j) {
					float dw = data_->samples[random_shuffle_[i]][j] * dz[x];
					g[j] += dw * dw;
					w_[j] = w_[j] - alpha_ * dw / std::sqrt(g[j] + eps_); // formula 8
				}

				b_ -= (alpha_ * dz[x]);
			}
		}
			break;
		case Optimization::SGD_Momentum: {
			int len = end - start;
			std::vector<float> v(feature_length_, 0.);
			std::vector<float> z(len, 0), dz(len, 0);
			for (int i = start, x = 0; i < end; ++i, ++x) {
				z[x] = calculate_z(data_->samples[random_shuffle_[i]]);
				dz[x] = calculate_loss_function_derivative(calculate_activation_function(z[x]), data_->labels[random_shuffle_[i]]);

				for (int j = 0; j < feature_length_; ++j) {
					float dw = data_->samples[random_shuffle_[i]][j] * dz[x];
					v[j] = mu_ * v[j] + alpha_ * dw; // formula 4
					w_[j] = w_[j] - v[j];
				}

				b_ -= (alpha_ * dz[x]);
			}
		}
			break;
		case Optimization::SGD:
		case Optimization::MBGD: {
			int len = end - start;
			std::vector<float> z(len, 0), dz(len, 0);
			for (int i = start, x = 0; i < end; ++i, ++x) {
				z[x] = calculate_z(data_->samples[random_shuffle_[i]]);
				dz[x] = calculate_loss_function_derivative(calculate_activation_function(z[x]), data_->labels[random_shuffle_[i]]);

				for (int j = 0; j < feature_length_; ++j) {
					float dw = data_->samples[random_shuffle_[i]][j] * dz[x];
					w_[j] = w_[j] - alpha_ * dw;
				}

				b_ -= (alpha_ * dz[x]);
			}
		}
			break;
		case Optimization::BGD:
		default: // BGD
			std::vector<float> z(m_, 0), dz(m_, 0);
			float db = 0.;
			std::vector<float> dw(feature_length_, 0.);
			for (int i = 0; i < m_; ++i) {
				z[i] = calculate_z(data_->samples[i]);
				o_[i] = calculate_activation_function(z[i]);
				dz[i] = calculate_loss_function_derivative(o_[i], data_->labels[i]);

				for (int j = 0; j < feature_length_; ++j) {
					dw[j] += data_->samples[i][j] * dz[i]; // dw(i)+=x(i)(j)*dz(i)
				}
				db += dz[i]; // db+=dz(i)
			}

			for (int j = 0; j < feature_length_; ++j) {
				dw[j] /= m_;
				w_[j] -= alpha_ * dw[j];
			}

			b_ -= alpha_*(db/m_);
	}
}

       执行结果如下图所示:测试函数为test_logistic_regression2_gradient_descent,多次执行每种配置,最终结果都相同。图像集使用MNIST,其中训练图像总共10000张,0和1各5000张,均来自于训练集;预测图像总共1800张,0和1各900张,均来自于测试集。NAG和Momentum SGD配置参数相同的情况下,即学习率为0.01,动量设为0.7,它们的耗时均为6秒,识别率均为100%

       GitHubhttps://github.com/fengbingchun/NN_Test

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

深度学习中的优化算法之NAG 的相关文章

  • 如何高速安装jetson-inference,一步到位,避免踩坑!

    踩了很长时间的坑 终于弄明白怎么高速下载jetson inference 来源 安装jetson inference 自动下载模型 满速下载起飞 解决下载模型被墙问题 奈流云何的博客 CSDN博客 需要将Github的仓库复制到Gitee上
  • 深度学习优化算法大全系列3:NAG(Nesterov Acceleration Gradient)

    1 NAG与SGD M的区别 NAG全称为Nesterov Accelerated Gradient 是在SGD Momentum基础进一步优化所得 前面的文章我们提到过 SGD M主要是利用历史累积动量来代替当前梯度从而达到减小震荡 加速
  • 3W字长文总结PyTorch中常用的函数

    quad quad PyTorch基本函数更新 quad q
  • 【生成式网络】入门篇(二):GAN的 代码和结果记录

    GAN非常经典 我就不介绍具体原理了 直接上代码 感兴趣的可以阅读 里面有更多变体 https github com rasbt deeplearning models tree master pytorch ipynb gan GAN 在
  • 深度学习知识体系学习大全 牛!!

    搬来了大牛的博客 点击直接前往 https www yuque com angsweet machine learning jian jie 配一张大牛的思维导图 具体内容点进去都能看到 数学 机器学习 语言 算法 深度学习 书籍推荐 东西
  • windows下运行pointnet(全)

    放假闲着在家没事 本人突然想跑一下3d深度学习的开山之作 pointnet玩一玩 可是目前网上大部分pointnet的运行教程都是在Ubuntu系统下的 其实本人也曾装过双系统 但是因为我太菜了 在Ubuntu下装完显卡驱动和cuda后切换
  • 笔记︱几款多模态向量检索引擎:Faiss 、milvus、Proxima、vearch、Jina等

    转自 https zhuanlan zhihu com p 364923722 引用文章 7 的开篇 来表示什么是 向量化搜索 人工智能算法可以对物理世界的人 物 场景所产生各种非结构化数据 如语音 图片 视频 语言文字 行为等 进行抽象
  • tiny-cnn执行过程分析(MNIST)

    在http blog csdn net fengbingchun article details 50573841中以MNIST为例对tiny cnn的使用进行了介绍 下面对其执行过程进行分析 支持两种损失函数 1 mean squared
  • libsvm库简介及使用

    libsvm是基于支持向量机 support vector machine SVM 实现的开源库 由台湾大学林智仁 Chih Jen Lin 教授等开发 它主要用于分类 支持二分类和多分类 和回归 它的License是BSD 3 Claus
  • 几乎最全的中文NLP资源库

    NLP民工的乐园 The Most Powerful NLP Weapon Arsenal NLP民工的乐园 几乎最全的中文NLP资源库 词库 工具包 学习资料 在入门到熟悉NLP的过程中 用到了很多github上的包 遂整理了一下 分享在
  • 深度学习中的验证集和超参数简介

    大多数机器学习算法都有超参数 可以设置来控制算法行为 超参数的值不是通过学习算法本身学习出来的 尽管我们可以设计一个嵌套的学习过程 一个学习算法为另一个学习算法学出最优超参数 在多项式回归示例中 有一个超参数 多项式的次数 作为容量超参数
  • 16个车辆信息检测数据集收集汇总(简介及链接)

    16个车辆信息检测数据集收集汇总 简介及链接 目录 1 UA DETRAC 2 BDD100K 自动驾驶数据集 3 综合汽车 CompCars 数据集 4 Stanford Cars Dataset 5 OpenData V11 0 车辆重
  • PyTorch训练简单的全连接神经网络:手写数字识别

    文章目录 pytorch 神经网络训练demo 输出结果 来源 pytorch 神经网络训练demo 数据集 MNIST 该数据集的内容是手写数字识别 其分为两部分 分别含有60000张训练图片和10000张测试图片 神经网络 全连接网络
  • GNN等优缺点总结及解决方案

    https www zhihu com question 338051122 https www zhihu com question 346942899 https zhuanlan zhihu com p 291230435 GCN的缺
  • Pytorch Advanced(三) Neural Style Transfer

    神经风格迁移在之前的博客中已经用keras实现过了 比较复杂 keras版本 这里用pytorch重新实现一次 原理图如下 from future import division from torchvision import models
  • Deep Learning(深度学习)之(三)Deep Learning的常用模型或者方法

    九 Deep Learning的常用模型或者方法 9 1 AutoEncoder自动编码器 Deep Learning最简单的一种方法是利用人工神经网络的特点 人工神经网络 ANN 本身就是具有层次结构的系统 如果给定一个神经网络 我们假设
  • 小样本学习(one/few-shot learning)

    原文 https blog csdn net mao feng article details 78939864 原博地址 https blog csdn net xhw205 article details 79491649 小样本学习
  • 深度学习中的优化算法之AdaGrad

    之前在https blog csdn net fengbingchun article details 123955067 介绍过SGD Mini Batch Gradient Descent MBGD 有时提到SGD的时候 其实指的是MB
  • 【深度学习】模型评价指标

    一 分类任务 分类任务一般有二分类 多分类和多标签分类 多分类 表示分类任务中有多个类别 但是对于每个样本有且仅有一个标签 例如一张动物图片 它只可能是猫 狗 虎等中的一种标签 二分类特指分类任务中只有两个类别 多标签 一个样本可以有多个标
  • 基于矩阵求解多元线性回归

    多元线性回归法也是深度学习的内容之一 用java实现一下多元线性回归 一元线性回归的公式为 y a x b 多元线性回归的公式与一元线性回归的公式类似 不过是矩阵的形式 可以表示为Y AX b 其中 Y是样本输出的合集 X是样本输入的合集

随机推荐