CMU C++ Tips 笔记

C和C++的编码实践总结(Coding Practices using C and C++) C语言编码相关实践 文章目录C语言编码相关实践一、C/C++安全性编码和其他方面编码的规范和建议1、什么是安全性编码?2、是否需要它?3、 安全编码实践的规则和建议Rules and Recommendations1)Preprocessor(预处理器)2)Declarations and Initialization(声明和初始化)2)Expressions(表达式)3)Integers(整数)4)Floating Point(浮点数)5)Array(数组)6)Characters and Strings 阅读详情

偶然发现 CMU 的 wiki,里面有 C/C++ 的编写小技巧和提醒,特意挑了些自以为的重点做了笔记,其中可能还混杂了我在其他地方看到的内容,详细内容 wiki 可以看文末链接。

1、preprocessor

1.1、universal character names

The universal character name \Unnnnnnnn designates the character whose 8-digit short identifier (as specified by ISO/IEC 10646) is nnnnnnnn.

Similarly, the universal character name \unnnn designates the character whose 4-digit short identifier is nnnn (and whose 8-digit short identifier is 0000nnnn).

1.2、#include_next

例如有个搜索路径链,在#include中,它们的搜索顺序依次是A,B,C,D和E。在B目录中有个头文件叫a.h,在D目录中也有个头文件叫a.h,如果在我们的源代码中这样写#include <a.h>,那么我们就会包含的是B目录中的a.h头文件,如果我们这样写#include_next <a.h>那么我们就会包含的是D目录中的a.h头文件。#include_next <a.h>的意思按我们上面的引号包含中的解释来说就是“在B目录中的a.h头文件后面的目录路径(即C,D和E)中搜索a.h头文件并包含进来)。#include_next <a.h>的操作会是这样的,它将在A,B,C,D和E目录中依次搜索a.h头文件,那么首先它会在B目录中搜索到a.h头文件,那它就会以B目录作为分割点,搜索B目录后面的目录(C,D和E),然后在这后面的目录中搜索a.h头文件,并把在这之后搜索到的a.h头文件包含进来。这样说的话大家应该清楚了吧。

还有一点是#include_next是不区分<>和""的包含形式的。

现在来说说为什么要引人这条指令!

假如,你要创建一个新的头文件,而这个新的头文件和现在已有的头文件有相同的名字,而且你想用你的这个新的头文件,那么你要做的就是把这个新的头文件放在#include指令的搜索路径的前面,即是在旧的头文件的前面新的头文件首先被搜索到,这样你就可以使用你这个新的头文件。但是你在另一个源代码文件中想使用旧的头文件了,那怎么办!有个办法就是使用绝对路径来搜索,那么就不存在这样的问题了。问题出在,如果我们把头文件的位置移动了,移到了其它的目录里了,那我们就得在相应的源码文件中修改这个包含的绝对路径,如果一个源码文件还好,但如果是大型工程的话,修改的地方多了就容易出问题。

1.3、macro side effects

#define ABS(x) (((x) < 0) ? -(x) : (x))
int m = ABS(++n);
// equal to below
m = (((++n) < 0) ? -(++n) : (++n));

// how to avoid
++n;
int m = ABS(n);

// or prefer inline or static functions to function-like macros
// Inline substitution is not textual substitution, nor does it create a new function.
static inline int iabs(int x) {
  return (((x) < 0) ? -(x) : (x));
}

// GCC's __typeof extension makes it possible to 
// declare and assign the value of the macro operand to a temporary of the same type 
// and perform the computation on the temporary, 
// consequently guaranteeing that the operand will be evaluated exactly once. 
#define ABS(x) __extension__ ({ __typeof (x) tmp = x; \
                    tmp < 0 ? -tmp : tmp; })

Expressions used as arguments to the standard assert() macro should not have side effects.

1.4、STDC_VERSION

Checks __STDC_VERSION__ to ensure that a pre-C11 compiler will fail to compile the code, rather than invoking undefined behavior.

#if __STDC_VERSION__ < 201112L
#error This code requires a compiler supporting the C11 standard or newer
#endif

2、tips

2.1、memset

int buff_2[10];
memset(buff_2,1,sizeof(buff_2));  
for(int i = 0;i<10;i++)
{
    printf("%d ",buff_2[i]);
}

是的,变量的类型变了,打印的结果是:

16843009 16843009 16843009 16843009 16843009 16843009 16843009 16843009 16843009 16843009

是不是觉得很奇怪,接下来,我们把这句:printf("%d ",buff_2[i]);

改为:printf("0X%x ",buff_2[i]);

得到的结果是:

0X1010101 0X1010101 0X1010101 0X1010101 0X1010101 0X1010101 0X1010101 0X1010101 0X1010101 0X1010101

是不是感觉很蹊跷?

首先,在我的设备上,int是4字节,所以buff_2总共40字节,memset会对40个1字节赋值0X01,而不是对10个4字节赋值0X01。

所以不要用memset对非字符型数组赋初值!

2.2、快速判断 char * 是否为 NULL

!!::getenv("FORCE_CLANG_DIAGNOSTICS_CRASH")

2.3、Structure Packing

When passing a pointer to a structure across a trust boundary to a different trusted domain, the programmer must ensure that the padding bytes and bit-field storage unit padding bits of such a structure do not contain sensitive information.

使用 memcpy 时要注意结构体可能的字节对齐。

// GCC allows specifying declaration attributes using the keyword __attribute__((__packed__)). 
// When this attribute is present, the compiler will not add padding bytes for memory alignment 
// unless an explicit alignment specifier for a structure member requires the introduction of padding bytes.
struct test {
  int a;
  char b;
  int c;
} __attribute__((__packed__));

// Microsoft Visual Studio  supports #pragma pack() to suppress padding bytes
#pragma pack(push, 1) /* 1 byte */
struct test {
  int a;
  char b;
  int c;
};
#pragma pack(pop)

// _Alignof(类型名称)  查询操作数类型的对齐要求。
printf("alignof(float[10]) = %zu\n", alignof(float[10])); // output: 4

Because these padding values are unspecified, attempting a byte-by-byte comparison between structures can lead to incorrect results.

void compare(const struct s *left, const struct s *right) { 
  if ((left && right) &&
      (0 == memcmp(left, right, sizeof(struct s)))) {
    /* ... */
  }
}
// 上面的比较方式是错误的,除非是非 padded 的 struct 类型,需要使用下面这种方式
void compare(const struct s *left, const struct s *right) { 
  if ((left && right) &&
      (left->c == right->c) &&
      (left->i == right->i) &&
      (0 == memcmp(left->buffer, right->buffer, 13))) {
    /* ... */
  }
}

2.4、volatile

If an attempt is made to refer to an object defined with a volatile-qualified type through use of an lvalue with non-volatile-qualified type, the behavior is undefined.

2.5、restrict

restrict 的含义是由编程者向编译器声明,在这个指针的生命周期中,只有这个指针本身或者直接由它产生的指针(如 ptr + 1)能够用来访问该指针指向的对象。

他的作用是限制指针别名,帮助编译器做优化.如果该指针与另外一个指针指向同一对象,那么结果是未定义的。

int add (int* __restrict__ a, int* __restrict__ b)
{
    *a = 10;
    *b = 12;
    return *a + *b;
}

编译器已经得知 a, b 两指针不会指向同一单元(此点应由编程者保证),所以在这里会减少一次内存的访问。

a 中一定是 10, b 中一定是 12, 所以编译器可以在这里做优化直接返回 22.

注意,编译器是无法自行在编译期检测两个指针是否 alias。如使用 restrict,程序员也要遵守契约才能得出正确的代码(指针不能指向相同数据)。

Developers should be aware that C++ does not support the restrict qualifier, but some C++ compiler implementations support an equivalent qualifier as an extension.

#include <stddef.h>
void f(size_t n, int *restrict p, const int *restrict q) {
  while (n-- > 0) {
    *p++ = *q++;
  }
}
  
void g(void) {
  extern int d[100];
  /* ... */
  f(50, d + 1, d); /* Undefined behavior */
  f(50, d + 50, d); /* Defined behavior : d is effectively divided into two disjoint objects. */
}

The assignment of restrict-qualified pointers to other restrict-qualified pointers within the same block has undefined behavior.

2.6、__builtin_sadd_overflow

This compliant solution uses the GNU extension __builtin_sadd_overflow, available with GCC, Clang, and ICC:

void f(signed int si_a, signed int si_b) {
  signed int sum;
  if (__builtin_sadd_overflow(si_a, si_b, &sum)) {
    /* Handle error */
  }
  /* ... */
}

other operator:

__builtin_ssub_overflow、__builtin_smul_overflow

2.7、uintptr_t

Any valid pointer to void can be converted to intptr_t or uintptr_t and back with no change in value. (See INT36-EX2.) The C Standard guarantees that a pointer to void may be converted to or from a pointer to any object type and back again and that the result must compare equal to the original pointer. Consequently, converting directly from a char * pointer to a uintptr_t, as in this compliant solution, is allowed on implementations that support the uintptr_t type.

#include <stdint.h>
#include <assert.h>  

void f(void) {
  char *ptr;
  /* ... */
  uintptr_t number = (uintptr_t)ptr; 
  /* ... */

// Any valid pointer to void can be converted to intptr_t or uintptr_t or their underlying types 
// and back again with no change in value. 
// Use of underlying types instead of intptr_t or uintptr_t is discouraged, however, because it limits portability

  intptr_t i = (intptr_t)(void *)&i;
  uintptr_t j = (uintptr_t)(void *)&j;
  
  void *ip = (void *)i;
  void *jp = (void *)j;
  
  assert(ip == &i);
  assert(jp == &j);

}

2.8、指定输出字符串的位数

#include <stdio.h>
  
void func(const char *name) {
  char filename[128];
  sprintf(filename, "%.123s.txt", name); // 只拿它的 123 位
  snprintf(filename, sizeof(filename), "%s.txt", name); // 安全写法,防溢出
}

2.9、Cast characters to unsigned char before converting to larger integer sizes

However, this rule is applicable only in cases where the character data may contain values that can be interpreted as negative numbers.

For example, if the char type is represented by a two’s complement 8-bit value, any character value greater than +127 is interpreted as a negative value.

static int yy_string_get(void) {
  register char *c_str;
  register int c;
 
  c_str = bash_input.location.string;
  c = EOF;
 
  /* If the string doesn't exist or is empty, EOF found */
  if (c_str && *c_str) {
    /* Cast to unsigned type */
    c = (unsigned char)*c_str++;
 
    bash_input.location.string = c_str;
  }
  return (c);
}

2.10、Unnamed namespaces

ODR-use [ISO/IEC 14882-2014]

A function or object is ODR-used if the address of the entity is taken, the function is called, or a reference is bound to the object. When a function or object is ODR-used, its definition must exist within the program or else the program is ill-formed.

Unnamed namespaces are used to define a namespace that is unique to the translation unit, where the names contained within have internal linkage by default.

Production-quality C++ code frequently uses header files as a means to share code between translation units. A header file is any file that is inserted into a translation unit through an #include directive. Do not define an unnamed namespace in a header file. When an unnamed namespace is defined in a header file, it can lead to surprising results. Due to default internal linkage, each translation unit will define its own unique instance of members of the unnamed namespace that are ODR-used within that translation unit. This can cause unexpected results, bloat the resulting executable, or inadvertently trigger undefined behavior due to one-definition rule (ODR) violations.

跟在头文件用 static 一样,也会导致 UB 的行为。

3、modern c++ use

3.1、c++ 11 及其之后的单例模式

template<typename T>
class Singleton{
public:
    static T& getInstance() {
        static T value_; // 静态局部变量
        return value_;
    }
    Singleton(const Singleton&) = delete; // 拷贝构造函数
    Singleton& operator=(const Singleton&) = delete; // =运算符重载
private:
    Singleton(); // 私有化构造方法
    ~Singleton();
};

static local variable:

The initialization of such a variable is defined to occur the first time control passes through its declaration; for multiple threads calling the function, this means there’s the potential for a race condition to define first.

3.2、多值返回与获取

std::tuple<llvm::Reloc::Model, unsigned, bool>
fun{
    return std::make_tuple(llvm::Reloc::PIC_, 2U, false);
}

std::tie(RelocationModel, PICLevel, IsPIE) = ParsePICArgs(TC, Args);

参考&推荐阅读

C/C++ 中的 restrict 关键字:https://jzwdsb.github.io/2018/03/restrict_in_cpp/

CMU 的 wiki:https://wiki.sei.cmu.edu/confluence/display/c/SEI+CERT+C+Coding+Standard
gcc:预处理语句--#include和#include_next:[https://blog.youkuaiyun.com/fjb2080/article/details/5247494]

CMU 15-445/645 数据库系统Lab 1 现代C++练习项目 本学期所有的编程项目都将在BusTub数据库管理系统上完成。本系统是用C++编写的。为了确保您有必要的C++背景,我们要求每个人完成一个简单的编程任务,以评估您对基本C++特性的了解。你将不会得到这个项目的分数,但你必须以满分完成该项目,然后才被允许继续在课程。任何不能在截止日期前完成此作业的学生将被要求退学。 这个编程任务中的所有代码必须用C++编写(具体是C++ 17)。了解C++ 11一般是足够的。如果你以前没有使用C++,这里是一个简短的语言教程。更详细的语言内部文档可以在cppferenc. 阅读详情

相关推荐

15-445 project#0 cpp primer

overview 本lab是作为一个15445的语言入门关(cpp),所以主要是熟悉一下modern cpp的语法和用法,以及本课程做lab时需要注意的一些东西 (为了遵守课程要求,代码暂不放出 代码内容 主要实现三个类:matrix,RowMatrix,RowMatrixOperations matrix 是个抽象类,定义了矩阵这个类所需要的一些基本成员变量和函数: 因为大部分是虚函数,所以不需要我们填写实现 需要做的是在构造函数里初始化一些变量:rows,columns,以及初始化一个一

RedemptionC的博客 3166

Linux嵌入式ARM开发教程的第二阶段1

目录 01-linux之io系统编程 02-linux进程间通信 03-linux多线程 04-linux网络编程基础 有时候,跟着视频学,自己看书学,一边做项目一边学都不失为一种好方法。 条条大道通罗马 All roads lead to Rome; All roads lead to Roma; All road lead to Room Linux中 万物皆文件 01-linux之io...

wesigj的博客 502

【OpenPose-Windows】OpenPose1.4.0+VS2017+CUDA9.2+cuDNN9.2+Windows配置教程

OpenPose-Windows Configuration&amp;amp;amp;amp;amp;amp;amp;amp;Installation Tutorial In Win10_x64 最近在安排一个OpenPose相关的Project,网上大多数的教程都采用VS2015+CUDA8.0的配置,OpenPose最近也更新到1.4.0了,在这里提供VS2017+CUDA9.2的教程。 推荐使用IDM开32线程下载 环境 操作系统:...

SkalDak BloOoG 1万+

C语言内建函数

内建函数(学习自用)

xcxhzjl的博客 2439

C Coding Standard (2016 Edition)

C编码标准:开发安全、可靠系统的规则; pdf格式;英文;CERT2016年发布

builtin_overflow:可以帮助我将__builtin_add_overflow,__builtin_sub_overflow和__builtin_mul_overflow添加到clang的文件

该项目跟踪了我为clang制作补丁以添加对__builtin_add_overflow,__builtin_sub_overflow和__builting_mul_overflow的支持的进度。

【转载】gcc.gnu.org:内置函数执行溢出检查算法

转载:https://gcc.gnu.org/onlinedocs/gcc/Integer-Overflow-Builtins.html 下面的内置函数可以执行简单的算术运算,并检查运算是否溢出。 内置函数:bool __builtin_add_overflow( type1 a, type2 b, type3 * res) 内置函数:bool __builtin_sadd_overflow(int a,int b,int * res) 内置函数:bool __builtin_saddl_overflo.

专注于C/C++/Linux领域创作 4428

周立功arm嵌入式开发教程全系列

ARM_zhiling.pdf ARM嵌入式系统基础教程.pdf ARM嵌入式系统实验教程(二)扩展实验.pdf ARM嵌入式系统软件开发实例(一).rar 《ARM与嵌入式系统基础教程》.rar 周立功的ARM468问.pdf 嵌入式实时操作系统ucOS-II中文教程.CHM 嵌入式实时操作系统ucOS-II英文教程.pdf 深入浅出ARM7+LPC213X+214X(超清晰)上下册.rar

从零开始的嵌入式linux+ARM

嵌入式linux+arm

weixin_42238224的博客 815

光模块的封装工艺有哪些?

COB封装传统的单路10Gb/s或25Gb/s速率的光模块采用SFP封装将电芯片和TO封装的光收发组件焊接到PCB板上组成光模块。但对于40G及以上速率的高速光模块,受激光器速率限制(多为25G),主要通过多通道并行实现,如40G由4×10G实现,而100G则由4×25G实现。蝶形封装:壳体通常为长方体,结构及实现功能通常比较复杂,可以内置制冷器、热沉、陶瓷基块、芯片、热敏电阻、背光监控,并且可以支持所有以上部件的键合引线。BOX封装属于蝶形封装的一种,用于多通道并行封装。

WaytoICT- Explore ICT Technology, Build Your Tech Path 3807

RseQC实战指南:从安装到RNA-Seq数据质控全流程解析

本文提供了一份详尽的RseQC实战指南,涵盖从安装配置到RNA-Seq数据质控的全流程。文章重点解析了RseQC作为专业质控工具的核心价值,手把手指导如何通过Conda或pip完成安装,并深入讲解了bam_stat.py、geneBody_coverage.py等关键模块的使用方法与结果解读技巧,帮助用户有效评估RNA完整性、文库构建质量及链特异性,确保下游分析的可靠性。

weixin_29200741的博客 201

CMU15445(2023 Spring) - Project 1. Buffer Pool

CMU15445 2023 spring project 1

J__M__C的博客 1597

CRMEB商城系统任意文件下载漏洞(CVE-2024-52726)分析与修复

在Web应用安全领域,API接口安全是保障系统边界安全的核心环节。其原理在于通过签名验证、参数校验等机制,确保请求的合法性与完整性。这项技术的价值在于为系统间数据交互提供安全通道,防止未授权访问和数据泄露。典型的应用场景包括电商系统的对外数据接口、第三方服务集成等。然而,当签名验证逻辑存在缺陷或文件路径处理不当,便会引发严重的安全风险。本文以CRMEB开源商城系统为例,深入剖析其对外API模块中因签名验证绕过和路径遍历导致的任意文件下载漏洞。该漏洞允许攻击者下载服务器敏感文件,如数据库配置文件、日志和源码,

weixin_27722377的博客 376

【CMU15-445数据库】bustub Project #2:B+ Tree(中)

本篇继续讲解 Project 2:B+ 树的实现。让我们先从相对简单的迭代器实现开始,然后讲述删除的实现。因为删除部分篇幅较长,并发控制我们放到下一篇再讲。

アルタイル 3336

Fortify SCA 24.4 最新可用版

Fortify Static Code Analyzer(Fortify SCA) 是一款由 Micro Focus(原惠普旗下)开发的 静态应用安全测试(SAST)工具,专注于在软件开发早期通过分析源代码或编译后的二进制文件,识别潜在的安全漏洞、代码缺陷和合规性问题。以下是其核心特点与功能:核心功能 静态代码分析 在不运行程序的情况下,通过语法、语义分析检测代码中的安全漏洞(如 SQL 注入、跨站脚本(XSS)、缓冲区溢出等)和代码质量问题。

棉花糖的博客 3181

PyCharm旧版本下载地址

快捷找到PyCharm历史版本下载地址

piaopiaolanghua的专栏 4434

tips_for_interview求职流水账:从Google到Optiver的心路历程

在竞争激烈的IT行业,面试求职往往是一场漫长而艰辛的旅程。本文将分享一位计算机专业学生从自学CS到斩获Google、Optiver等知名企业offer的真实经历,为正在求职或准备求职的同学们提供实用的面试技巧和心路历程参考。 ## 🚀 自学CS的逆袭之路 ### 从航天到计算机的跨界选择 大三下学期(2015年下旬),我做出了一个重要的决定——从航天专业转向自学计算机科学。这个决定源于对航

gitblog_02765的博客 1017

别再为采样窗口发愁了!手把手教你用STM32实现三电阻分扇区电流采样(附代码避坑)

本文详细介绍了STM32平台下三电阻分扇区电流采样的实现方法,重点解决采样窗口选择不当和扇区切换逻辑问题。通过PWM定时器与ADC协同工作的底层机制分析,提供可移植的代码示例和实战经验,帮助工程师在电机矢量控制(FOC)系统中实现高精度相电流采样。

weixin_42531516的博客 165

如何自学CS?tips_for_interview分享3年从航天到计算机的转型秘诀

在当今数字化时代,计算机科学(CS)已成为推动社会发展的核心力量。对于许多非科班出身的人来说,自学CS并成功转型是一个极具挑战性但又充满机遇的过程。本文将分享笔者从航天专业转型到计算机领域的亲身经历,并结合gh_mirrors/ti/tips_for_interview项目中的宝贵资料,为大家提供一份全面的自学CS指南。无论你是想转行进入IT行业,还是希望提升自己的计算机技能,本文都将为你指明方向

gitblog_01126的博客 909

抖音短连接v.douyin.com/xxx 如何生成?

最近公司有个需求,在抖音里如何宣传自己的网站,并且不要有拦截域名的提示,截图如下。 通过ida反编译抖音的app后,将下载后的ipa文件用解压缩软件(如7zip等)解压,从解压后的目录Payload/Aweme.app/找到Aweme可执行文件,拖入ida进行反编译,ida可以检测objective-c语法。 然后进入主题,既然是聊天发消息,就尝试在ida里搜索"message",看看能否找到对...

kakuapi的博客 3万+

【NVIDIA-B200 GPU固件升级】NVIDIA Blackwell B200 GPU 固件更新全指南

B200 GPU 固件更新并非 “执行一条命令即可” 的简单操作,而是涉及 “版本兼容性校验、BMC 环境准备、UEFI 引导、Redfish 协议交互” 的系统性工程。从文档翻译与技术解析来看,NVIDIA 的更新流程设计围绕 “安全” 与 “稳定” 两大核心 —— 无论是 0.9 版本的 “跳板限制”,还是 UEFI Shell 的引导要求,本质都是为了避免因操作不当导致硬件损坏。对于数据中心运维人员,建议在更新前做好三项准备:① 确认 GPU 当前固件版本(通过查询),规划升级路径;

jundao1997的专栏 742

对于你我来说值得一读的技术博客

本作品采用知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议进行许可。 本作品 (李兆龙 博文, 由 李兆龙 创作),由 李兆龙 确认,转载请注明版权。 引言 知识的输入固然重要,但是我想输出也同样重要。输出的途径有很多,记录我认为是其中很有价值的一种方式,因为对于绝大多数人来说根本不可能记住你所学过的所有东西,甚至于我认为能够记住百分之五十都已经是人中翘楚了,如此上下文中,我们该如何优化自己的效率呢?博客是一种不错的方式。 就我短短几年学习计算机的经历看来,好的博客的维护者有这么几种类型:

李兆龙的博客 1463

深度学习工具包 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")

OpenPose1.4.0+VS2017+CUDA9.2+cuDNN9.2+Windows配置教程(转)

OpenPose1.4.0+VS2017+CUDA9.2+cuDNN9.2+Windows配置教程(转) 2018年09月04日 14:34:39Skaldak版权声明:SkalDak OriGinaL https://blog.csdn.net/qq_20226441/article/details/82380030 最近在安排一个Ope...

weixin_30311605的博客 186

Devexpress16.2.6破解工具

Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具

lwip-2.0.3

lwip是瑞典计算机科学院(SICS)的Adam Dunkels 开发的一个小型开源的TCP/IP协议栈。实现的重点是在保持TCP协议主要功能的基础上减少对RAM 的占用。

一文读懂机器学习库graphLab

文章目录目录什么是graphlab为什么使用graphlab?如何安装graphlab?graphlab的简单使用。 目录 什么是graphlab GraphLab 是由CMU(卡内基梅隆大学)的Select 实验室在2010 年提出的一个基于图像处理模型的开源图计算框架,框架使用C++语言开发实现。该框架是面向机器学习(ML)的流处理并行计算框架,可以运行在多处理机的单机系统、集群或是亚马逊的E...

wangzi11111111的博客 831

廖雪峰Python教程[完整版]

廖雪峰的python教程整理的,已经排好版了,而且还是完整的,适合小白

纯攒人品!面了阿里算法岗(cv方向) ,这次找到组织了。。。

节前,我们组织了一场算法岗技术&面试讨论会,邀请了一些互联网大厂同学、参加社招和校招面试的同学,针对算法岗技术趋势、大模型落地项目经验分享、新手如何入门算法岗、该如何准备、面试常考点分享等热门话题进行了深入的讨论。今天整理我们社群粉丝分享的算法岗方向面试题,分享给大家,希望对后续找工作的有所帮助。

机器学习社区 1040
上一篇: c++ 类方法和普通方法调用有何不同?
下一篇: 《基于 LLVM 克隆代码检测关键技术研究》笔记
流左沙
博客等级 码龄11年 46粉丝 55原创
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值