STL源码分析之数值算法

数值分析常见基本算法及MATLAB代码总结 刚考完研究生的数值分析课,打算整理一下平时的上机代码,做一个汇总。 数值分析大致八部分内容—— 解线性方程组的直接法:Gauss消去法与矩阵三角分解法(Doolittle分解法相比Crout分解法更常用)及其选择列主元的改进方法、Doolittle分解法的延伸(实对称正定矩阵利用Cholesky分解得到的平方根法、三对角矩阵作为线性方程组系数矩阵的追赶法) 解线性方程组的迭代法:Jacobi迭代法、Gauss-Seidel迭代法(利用前者每次迭代已得到的最新分量加速)、逐次超松弛(SOR,Succes 阅读详情

前言

本节所分析的算法是在stl_numeric.h中, 本节以源码 + 例子的形式一起分析这些实现的操作.

数值算法分析

accumulate

要求传入两个InputIterator类型的迭代器和一个初始化值, 第二个版本还支持在传入一个仿函数或函数.

// 版本一
template <class InputIterator, class T>
T accumulate(InputIterator first, InputIterator last, T init) {
  for ( ; first != last; ++first)
    init = init + *first;
  return init;
}
// 版本二 : 接受函数或仿函数
template <class InputIterator, class T, class BinaryOperation>
T accumulate(InputIterator first, InputIterator last, T init,
             BinaryOperation binary_op) {
  for ( ; first != last; ++first)
    init = binary_op(init, *first);
  return init;
}

实例:

// 函数
inline int  binary(int a1, int a2)
{
	return a1 - a2;
}
// 仿函数
struct mybinary 
{
	int operator() (const int a1, const int a2)
	{
		return a1 + a2;
	}
}mybinary;

int main()
{
	int a[4]= {1, 2, 3, 4};
	int sum = 0;
	sum = accumulate(a, a+4, sum);	// 版本一
	for(const auto &i : a)
		cout << i << " ";	// 1 2 3 4 
	cout << sum;	// 10

	sum = accumulate(a, a+4, sum, binary);	// 版本二, 函数
	cout << sum;	// 0

	sum = accumulate(a, a+4, sum, mybinary);	// 版本二, 仿函数
	cout << sum;	// 10

	exit(0);
}
inner_product

两个版本.

版本一 : 两个InputIterator类型的迭代器, 一个迭代器(所有的数据 * first2), 一个初始化值.

template <class InputIterator1, class InputIterator2, class T>
T inner_product(InputIterator1 first1, InputIterator1 last1,
                InputIterator2 first2, T init) {
  for ( ; first1 != last1; ++first1, ++first2)
    init = init + (*first1 * *first2);
  return init;
}

版本二 : 比版本一多接受两个函数或仿函数, 先执行binary_op2操作再执行binary_op1. 与上面的accumulate一样.

template <class InputIterator1, class InputIterator2, class T,
          class BinaryOperation1, class BinaryOperation2>
T inner_product(InputIterator1 first1, InputIterator1 last1,
                InputIterator2 first2, T init, BinaryOperation1 binary_op1,
                BinaryOperation2 binary_op2) {
  for ( ; first1 != last1; ++first1, ++first2)
    init = binary_op1(init, binary_op2(*first1, *first2));
  return init;
}
partial_sum

两个版本. 功能 : 将传入的InputIterator两个迭代器范围内的值进行局部求和. 即 y0 = x0; y1 = x0 + x1; …

版本一 : 默认操作

template <class InputIterator, class OutputIterator, class T>
OutputIterator __partial_sum(InputIterator first, InputIterator last,
                             OutputIterator result, T*) {
  T value = *first;
    // 跳过x0, 从x1开始局部求和
  while (++first != last) {
    value = value + *first;
    *++result = value;
  }
  return ++result;
}

template <class InputIterator, class OutputIterator>
OutputIterator partial_sum(InputIterator first, InputIterator last,
                           OutputIterator result) {
  if (first == last) return result;
  *result = *first;
  return __partial_sum(first, last, result, value_type(first));
}

版本二 : 比版本一多了一个二元操作.

template <class InputIterator, class OutputIterator, class T,
          class BinaryOperation>
OutputIterator __partial_sum(InputIterator first, InputIterator last,
                             OutputIterator result, T*,
                             BinaryOperation binary_op) {
  T value = *first;
	// 跳过x0, 从x1开始局部求和
  while (++first != last) {
    value = binary_op(value, *first);
    *++result = value;
  }
  return ++result;
}

template <class InputIterator, class OutputIterator, class BinaryOperation>
OutputIterator partial_sum(InputIterator first, InputIterator last,
                           OutputIterator result, BinaryOperation binary_op) {
  if (first == last) return result;
  *result = *first;
  return __partial_sum(first, last, result, value_type(first), binary_op);
}

实例:

inline int partial_inc(int a1, int a2)
{
	return a2+2;
}

int main()
{
	int a[4] = {1, 2, 3, 4 };
	int a2[4];

	partial_sum(a, a+sizeof(a)/sizeof(int), a2);	// 版本一
	for(const auto &i : a)
		cout << i << " ";	// 1 2 3 4

	for(const auto &i : a2)
		cout << i << " ";	// 1 3 6 10 
	
	partial_sum(a, a+sizeof(a)/sizeof(int), a2, partial_inc);	// 版本二
	for(const auto &i : a2)
		cout << i << " ";	// 1 4 5 6 

	exit(0);
}
adjacent_difference

两个版本. 功能 : 将传入的InputIterator两个迭代器范围内的值进行局部相减. 即 y0 = x0; y1 = x0 - x1 …

版本一

template <class InputIterator, class OutputIterator, class T>
OutputIterator __adjacent_difference(InputIterator first, InputIterator last, 
                                     OutputIterator result, T*) {
  T value = *first;
  while (++first != last) {
    T tmp = *first;
    *++result = tmp - value;	// 进行相减
    value = tmp;
  }
  return ++result;
}

template <class InputIterator, class OutputIterator>
OutputIterator adjacent_difference(InputIterator first, InputIterator last, 
                                   OutputIterator result) {
  if (first == last) return result;
  *result = *first;
  return __adjacent_difference(first, last, result, value_type(first));
}

版本二 : 指定二元操作

template <class InputIterator, class OutputIterator, class T, class BinaryOperation>
OutputIterator __adjacent_difference(InputIterator first, InputIterator last, 
                                     OutputIterator result, T*,
                                     BinaryOperation binary_op) {
  T value = *first;
  while (++first != last) {
    T tmp = *first;
    *++result = binary_op(tmp, value);	
    value = tmp;
  }
  return ++result;
}

template <class InputIterator, class OutputIterator, class BinaryOperation>
OutputIterator adjacent_difference(InputIterator first, InputIterator last,
                                   OutputIterator result,
                                   BinaryOperation binary_op) {
  if (first == last) return result;
  *result = *first;
  return __adjacent_difference(first, last, result, value_type(first),
                               binary_op);
}

实例:

struct adjacent{
	int operator() (const int tmp, const int a) { return tmp - a - a; }
}adjacent;

int main()
{
	int a[4] = {1, 2, 3, 4};
	int a2[4];

	for(const auto &i : a)
		cout << i <<  " ";	// 1 2 3 4 

	adjacent_difference(a,  a+4, a2);
	for(const auto &i : a2)
		cout << i <<  " ";	// 1 1 1 1
    
	partial_sum(a2, a2+4, a2);
	for(const auto &i : a2)
		cout << i <<  " ";	// 1 2 3 4 
    
	adjacent_difference(a, a+4, a2, adjacent);
	for(const auto &i : a2)
		cout << i <<  " ";	// 1 0 -1 -2

	exit(0);
}

从实例可以看出来adjacent_difference与partial_sum相结合可以恢复.

power

一个版本. 幂次方。如果指定为乘法运算,则当n >= 0 时传回 x^n

// Returns x ** n, where n >= 0.  Note that "multiplication"
//  is required to be associative, but not necessarily commutative.   
template <class T, class Integer, class MonoidOperation>
T power(T x, Integer n, MonoidOperation op) {
  if (n == 0)
    return identity_element(op);
  else {
    while ((n & 1) == 0) {
      n >>= 1;
      x = op(x, x);
    }

    T result = x;
    n >>= 1;
    while (n != 0) {
      x = op(x, x);
      if ((n & 1) != 0)
        result = op(result, x);
      n >>= 1;
    }
    return result;
  }
}

template <class T, class Integer>
inline T power(T x, Integer n) {
  return power(x, n, multiplies<T>());
}
iota

设定某个区间的内容, 使其每个元素从指定值value开始, 呈现递增

template <class ForwardIterator, class T>
void iota(ForwardIterator first, ForwardIterator last, T value) {
  while (first != last) *first++ = value++;
}

实例:

int main()
{
	int a[4] = {1, 2, 3, 4};
	iota(a+1, a+4, 10);
	for(const auto &i : a)
		cout << i << ' '; // 1 10 11 12

	return 0;
}

总结

本节对numeric.h中的算法进行了分析, 这些都是很简单的函数实现, 但是大都提供了两个版本, 可接受二元操作的函数, 这由用户定义, 也就提高了STL的灵活性.

数值分析算法总结 数值分析的算法总结,用 Python 简要描述各种方法。考前复习(预习)向。 非线性方程求根 二分法 不动点迭代 牛顿迭代 插值 Lagrange 插值 Newton 插值 最小二乘拟合 数值积分 梯形求积公式 辛普森求积公式 Newton-Cotes 常微分方程初值问题 改进 Euler RK4 线性方程组直接解法 高斯消元 LU 分解 线性方程组迭代解法 Jacobi 迭代 Gauss-Seidel 迭代 特征值求法 正幂法 反幂法 阅读详情

相关推荐

C++ STL源码分析——算法(一)

accumulate

ZLP_优快云的博客 702

STL算法_数值算法篇

STL算法_数值篇1)accumulate算法:用来计算初始值init和[first,last)内所有元素的总和。// 计算init和[first,last)内所有元素的总和 // 版本1 template <class _InputIterator, class _Tp> _Tp accumulate(_InputIterator __first, _InputIterator __last, _

没有最好,只有更好! 1220

图解|从武侠角度探究STL排序算法的奥秘

前言今天来看一下STL中的sort算法的底层实现和代码技巧。众所周知STL是借助于模板化来支撑数据结构和算法的通用化,通用化对于C++使用者来说已经很惊喜了,但是如果你看看STL开发者强大...

编程与实战的博客 1166

数据分析及算法总结

一. K-近邻算 工作原理 简洁的讲: 如果一个样本在特定的空间中的K个最邻近的中的大多数属于某个类,则这个样本属于这个类. 用途 k近邻的目的是测量不同特征值与数据集之间的距离来进行分类 样本差异性 欧式距离 优缺点 优点:精度高、对异常值不敏感、无数据输入假定。 缺点:时间复杂度高、空间复杂度高。 适用数据范围:数值型和标称型。 导包 分类问题:from sklearn.neighb...

weixin_42825585的博客 2万+

《STL源码剖析》深入剖析理解

《STL源码剖析》是由侯捷所著,是一本经典的C++ STL源码解析书籍,它深入剖析SGI版本的C++ STL源代码,解释了STL各个组件的实现原理和设计思路。

qq_51969153的博客 1083

cpp20规范 vs2019 STL库 unordered_map源码分析

经过源代码查找,_Hasher = hash,和 _Keyeq = equal_to里都没有 is_transparent 的定义。而哈希时int 整数应该是最常用的情况。绿箭头1 处的模板类,继承了绿箭头2 , 绿箭头2 又继承了红框模板。但红框模板有一个泛化版本和一个特化版本,选择哪一个呢?所以应该是继承了泛化版本,就是透明的哈希容器。虽然,还不知道透明是啥意思。只是这个模板里强制了一个类型引用。(1) unordered_map 模板有如下的模板调用和包含关系。

zhangzhangkeji的博客 317

五 STL算法(一)数值算法

一  概述: 使用数值算法需要包含头文件,但它们实际定义于中。 二 相关算法: (1)accumulate:用来计算[first,last)内所有元素和init的值的总和。如果希望计算[first,last)中所有数值的总和,应该把init设置为0。 accumulate的定义: //版本1 template T accumulate(InputIterator fi

linux系统、网络编程和分布式计算 830

电流舵DAC设计(一)

如果分辨率继续增加,温度计码译码逻辑成为面积的主要决定因素,数字版图面积增加,总的面积消耗成上升趋势。缺点是:对于高分辨率的 DAC,高位码元和低位码元权重相差很大,当输入码元转换时(以 8 位二进制型 DAC 为例)尤其是中码转换(从 01111111 转换到 10000000),因为此时电流源的选通动作并非理想情况下的绝对一致等因素,导致在极短的时间内,码元会从 01111111 跳转到 11111111 再跳到10000000,这个过程中所有开关都参与转换,会引起最大幅度的尖峰毛刺(glitch);

模拟芯片设计 2872

STL-----容器进行数值计算类算法

前言: 此类算法都是在容器内进行数值计算的算法,常用在顺序容器上,向vector容器,数组等等。像我们平时如果要求容器内元素的总和,或者是两两之差,之和,之积等等,那肯定是自己写个for循环,但是STL库有这么方便的算法,那我们肯定用方便的玩意啦。 分为两类,第一类是用于单个容器算法,比如:accumulate,adjacent_difference,partial_sum:第二类是用于两个容器的...

weixin_43743711的博客 518

手把手实战:快速构建合同智能审查Agent

配置“模型供应商”,选择 “OpenAI-API-compatible”,输入申请到的 “API Key” 和 “URL” 后点击“保存”,如下图示例完成 “AlayaNew/DeepSeek-R1。至此,我们完成了合同智能审核Agent的构建,我们也可以在Dify中把这个智能体发布为API服务,这样企业其它应用如OA就可以通过API集成,在原合同流程中实现智能审核工作。该节点“输入变量”中,配置从“开始”节点中获取上传的文件,输出变量就是合同的内容,配置如下图。接下来我们开始创建智能体。

weixin_46880696的博客 4403

Xilinx VU+系列多DIE FPGA时序约束与跨DIE信号优化策略

本文深入探讨了Xilinx VU+系列多DIE FPGA的时序约束与跨DIE信号优化策略。针对2.5D/3D封装技术带来的时序挑战,详细解析了SLR区域约束、Laguna寄存器配置及跨时钟域约束等关键技术,提供了实用的TCL脚本和RTL优化示例,帮助开发者有效提升设计性能和时序收敛效率。

weixin_29209801的博客 654

SGISTL源码探究-stl_numeric.h中的数值算法

前言上一小节中,我们对stl中的算法部分做了一个大致的说明。本小节我们将进入到其中关于数值算法的部分,都在stl_numeric.h文件中。废话不多说,直接看源码吧。stl_numericaccumulate注意该算法要求了迭代器的类型至少是InputIterator类型,如果是OutputIterator类型,肯定是不行的。 用于计算元素总和,init加上[first, last)范围内的元素之

Move_now的博客 682

nRF5340双核实战:从Zephyr环境搭建到蓝牙协议栈部署

本文详细介绍了nRF5340双核处理器的开发实践,包括Zephyr环境搭建、蓝牙协议栈部署及双核协同工作配置。通过实战案例展示了如何利用nRF5340的双核异构架构提升蓝牙应用性能,并提供了调试技巧与资源优化建议,帮助开发者高效实现低功耗蓝牙设备开发。

weixin_42525385的博客 380

数值算法 —— 累加(accumulate)

参考书籍:《STL源码剖析》 参考源码: cygnus C++2.91.57 for Windows I. 所在文件位置 // numeric #ifndef __SGI_STL_NUMERIC #define __SGI_STL_NUMERIC // ...... #include <stl_numeric.h> // ...... #endif /* __SGI_STL_NUMERIC */ // stl_nameric.h #ifndef __SGI_STL_INTERNAL_.

qq_35484146的博客 1112

【汽车故障诊断2】从标准到实战:解码DTC格式背后的诊断逻辑

本文深入解析汽车诊断故障码(DTC)的格式与逻辑,对比了OBD-II标准(如ISO 15031-6)的5字符格式与UDS协议(ISO 14229-1)下更丰富的3字节格式。文章从国际标准出发,结合实战案例,阐述了DTC如何作为汽车电子系统的“体检报告”,帮助工程师和维修技师精准定位故障,并详细解读了UDS 19服务如何读取和管理DTC状态。

berry的博客 711

IBM System x3650 M5 IMM配置

1、IMM基本介绍 IMM,全称是Intel Mobile Module是IBM服务器上的集成管理模块,该模块是独立于服务器系统,可以通过一个单独的IP地址,使用Web和虚拟端口方式直接启动、停止和管理远程服务器,即使主板、处理器或者内存故障导致主机无法启动,也依然可以远程管理服务器,可以远程直接操作启动画面和服务器工作界面。 2、IP地址配置 2.1 通过Web方式修改IP地址 IBM服...

血饮渊虹的博客 4万+

STL源码分析目录

SIG STL源码分析 前言 本专栏主要以STL源码剖析分析路线来分析SIGSTL3.0源码. 整个模块准备对学习STL源码剖析之后做一个系统的总结, 这些都是我个人的理解, 如果分析有什么问题欢迎各位大佬们指出. 也很感谢作者以及网络中各个大佬的总结, 让我也能更容易更深刻的理解到STL强大和方便, 也让我对template感受深刻. 以下是我自己对STL版块进行分析. 总共分为六个版块 : 空...

啦啦啦 3637

6.5 构网型储能系统的协同控制策略

本文系统阐述了构网型储能系统的协同控制策略,重点分析了多机组群协同运行面临的功率分配不均、动态响应失配等挑战。研究提出了改进型下垂控制与虚拟阻抗法、基于一致性算法的分布式协同控制等解决方案,探讨了构网型储能与同步发电机在惯性响应、一次调频等方面的协同机制,以及与跟网型电源在电压支撑、阻抗重塑等方面的互补作用。文章构建了分层控制架构,为实现多类型电源的全局优化运行提供了技术路径,对提升高比例新能源电力系统的稳定性具有重要意义。

技术工作者 1002

C++ stl库 手写 源码分析

C++ stl库 手写前言序列式关联式容器适配器ListVector 函数dequestringstack queuebitset关联式容器 set multisetmultiset算法库仿函数 前言 stl版本 abcd,四个版本, 接口肯定是一样的 代码复用性强,效率高,通用性高,vector deque 他有六个组件,空间配置器,容器,迭代器,算法,仿函数,容器适配器 容器和算法中间,靠迭代器连接 算法为了通用性,有辅助的东西,让算法通用,也就是使用仿函数 仿函数就是一个对象 容器通过适配器,可以相

hxhxhxhxx的博客 2859

mojoPortal 路径穿越漏洞复现(CVE-2025-28367)(附脚本)

 在 mojoPortal CMS 版本 <=2.9.0.1 中发现了一个导致 ViewState 反序列化的目录遍历漏洞。通过利用此问题,未经身份验证的攻击者可以泄露 Web 根目录中的敏感文件,包括应用程序的文件。此配置文件包含用于验证和解密 ViewState 数据的文件。知道此密钥后,网络攻击者可以构建恶意 ViewState 有效负载,从而导致在底层服务器上执行远程代码。(CVE-2025-28367)

iSee857的博客 500

IMSL CNL 7.0.0 (x86-64)Crack

IMSL CNL 7.0.0 (x86-64)Crack intel的算法库破解文件,这是C++版本的破解文件

C++ STL:hashtable源码分析

当hashtable中插入的元素个数大于当前vector的容量时,会新建一个vector,新vector的容量是之前vector容量所在质数表里的下一个质数,如53的后一个是97,新vector的容量为97。函数将不同类型的key数据转换成统一的数值格式(如:const char *转换成特定的数值),以便hash函数进行取模处理,取模用的模值就是桶的数量值,也就是vector的容量。m不应该是进制数的幂,比如十进制的时候,m如果是10^n,那么结果总是和原始值的后n位相关的,这样冲突的概率会更大。

_ 1476

Probability and Statistics - 4th edition

Probability and Statistics - 4th edition

STL 源码分析 # stl_number #

STL 源码分析 # stl_number # /*********************************************************** Programmer : EOF e-mail : jasonleaster@gmail.com Date : 2015.04.04 File : 6number.cpp ********************

Jason Leaster | Rebuilding the tower of babel 934

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

OV9734 DATASHEET,完整规格书

OV9734完整规格书,包括电气参数,尺寸规格,寄存器配置表等

OpenCascade中读取STL文件的相同节点合并器(源码分析)

OpenCascade相同节点合并源码,在读取stl的文件的时候会遇到相同节点的问题,需要处理,而opencascade中使用了基于哈希表的处理办法,非常的巧妙

sswai的博客 1020

STL源码剖析

STL源码剖析——空间配置器 STL源码剖析——Traits编程技术 STL源码剖析——迭代器 STL源码剖析——全局函数 STL源码剖析——序列容器之vector STL源码剖析——list容器的排序算法sort() STL源码剖析——序列容器之list STL源码剖析——序列容器之deque STL源码剖析——容器配接器之stack STL源码剖析——容器配接器之queue STL源码剖析——...

zzxiaozhao的博客 477

STL源码分析:Containers

STL容器分两种:序列式容器,关联式容器。 ​ 上图以内缩方式来表达基层与衍生层的关系。 heap内含一个vector,priority-queue内含一个heap、stack和queue都含一个deque,set/map/multiset/multimap都内含一个RB-tree,hash_x都内含一个hastable。 序列式容器 所谓序列式容器,其中的元素都可序(o...

a857351839的博客 118

泛型算法之count与count_if

1. difference_type count (InputIterator beg, InputIterator end, const T&amp; value); 2. difference_type count_if (InputIterator beg, InputIterator end, UnaryPredicate op); 1式返回beg-end区间内等于value的值,2式...

张小染的博客 336
上一篇: STL源码分析之rotate算法
下一篇: STL源码分析之stl_algo.h中的基本算法
Function_18
博客等级 码龄10年 193粉丝 239原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值