c++数据类型

C++ 数据类型 作用:将不同类型的数据组合为一个整体,用于表示复杂对象。struct Student { // 定义结构体类型int id;// 创建结构体变量cout << tom.name << "的成绩是:" << tom.score;// 访问成员进阶特性:结构体可包含函数成员(C++ 中与 class 的区别主要在于默认访问权限)。 阅读详情

C++ 数据类型

使用编程语言进行编程时,需要用到各种变量来存储各种信息。变量保留的是它所存储的值的内存位置。这意味着,当您创建一个变量时,就会在内存中保留一些空间。

您可能需要存储各种数据类型(比如字符型、宽字符型、整型、浮点型、双浮点型、布尔型等)的信息,操作系统会根据变量的数据类型,来分配内存和决定在保留内存中存储什么。

基本的内置类型

C++ 为程序员提供了种类丰富的内置数据类型和用户自定义的数据类型。下表列出了七种基本的 C++ 数据类型:

类型关键字
布尔型bool
字符型char
整型int
浮点型float
双浮点型double
无类型void
宽字符型

wchar_t

其实 wchar_t 是这样来的:

typedef short int wchar_t;

所以 wchar_t 实际上的空间是和 short int 一样。

一些基本类型可以使用一个或多个类型修饰符进行修饰:

  • signed
  • unsigned
  • short
  • long

下表显示了各种变量类型在内存中存储值时需要占用的内存,以及该类型的变量所能存储的最大值和最小值。

注意:不同系统会有所差异,一字节为 8 位。

注意:默认情况下,int、short、long都是带符号的,即 signed。

注意:long int 8 个字节,int 都是 4 个字节,早期的 C 编译器定义了 long int 占用 4 个字节,int 占用 2 个字节,新版的 C/C++ 标准兼容了早期的这一设定。

类型位范围
char1 个字节-128 到 127 或者 0 到 255
unsigned char1 个字节0 到 255
signed char1 个字节-128 到 127
int4 个字节-2147483648 到 2147483647
unsigned int4 个字节0 到 4294967295
signed int4 个字节-2147483648 到 2147483647
short int2 个字节-32768 到 32767
unsigned short int2 个字节0 到 65,535
signed short int2 个字节-32768 到 32767
long int8 个字节-9,223,372,036,854,775,808 到 9,223,372,036,854,775,807
signed long int8 个字节-9,223,372,036,854,775,808 到 9,223,372,036,854,775,807
unsigned long int8 个字节0 到 18,446,744,073,709,551,615
float4 个字节精度型占4个字节(32位)内存空间,+/- 3.4e +/- 38 (~7 个数字)
double8 个字节双精度型占8 个字节(64位)内存空间,+/- 1.7e +/- 308 (~15 个数字)
long long8 个字节双精度型占8 个字节(64位)内存空间,表示 -9,223,372,036,854,775,807 到 9,223,372,036,854,775,807 的范围
long double16 个字节长双精度型 16 个字节(128位)内存空间,可提供18-19位有效数字。
wchar_t2 或 4 个字节1 个宽字符

注意,各种类型的存储大小与系统位数有关,但目前通用的以64位系统为主。

以下列出了32位系统与64位系统的存储大小的差别(windows 相同):

从上表可得知,变量的大小会根据编译器和所使用的电脑而有所不同。

下面实例会输出您电脑上各种数据类型的大小。

实例

#include<iostream> #include <limits> using namespace std; int main() { cout << "type: \t\t" << "************size**************"<< endl; cout << "bool: \t\t" << "所占字节数:" << sizeof(bool); cout << "\t最大值:" << (numeric_limits<bool>::max)(); cout << "\t\t最小值:" << (numeric_limits<bool>::min)() << endl; cout << "char: \t\t" << "所占字节数:" << sizeof(char); cout << "\t最大值:" << (numeric_limits<char>::max)(); cout << "\t\t最小值:" << (numeric_limits<char>::min)() << endl; cout << "signed char: \t" << "所占字节数:" << sizeof(signed char); cout << "\t最大值:" << (numeric_limits<signed char>::max)(); cout << "\t\t最小值:" << (numeric_limits<signed char>::min)() << endl; cout << "unsigned char: \t" << "所占字节数:" << sizeof(unsigned char); cout << "\t最大值:" << (numeric_limits<unsigned char>::max)(); cout << "\t\t最小值:" << (numeric_limits<unsigned char>::min)() << endl; cout << "wchar_t: \t" << "所占字节数:" << sizeof(wchar_t); cout << "\t最大值:" << (numeric_limits<wchar_t>::max)(); cout << "\t\t最小值:" << (numeric_limits<wchar_t>::min)() << endl; cout << "short: \t\t" << "所占字节数:" << sizeof(short); cout << "\t最大值:" << (numeric_limits<short>::max)(); cout << "\t\t最小值:" << (numeric_limits<short>::min)() << endl; cout << "int: \t\t" << "所占字节数:" << sizeof(int); cout << "\t最大值:" << (numeric_limits<int>::max)(); cout << "\t最小值:" << (numeric_limits<int>::min)() << endl; cout << "unsigned: \t" << "所占字节数:" << sizeof(unsigned); cout << "\t最大值:" << (numeric_limits<unsigned>::max)(); cout << "\t最小值:" << (numeric_limits<unsigned>::min)() << endl; cout << "long: \t\t" << "所占字节数:" << sizeof(long); cout << "\t最大值:" << (numeric_limits<long>::max)(); cout << "\t最小值:" << (numeric_limits<long>::min)() << endl; cout << "unsigned long: \t" << "所占字节数:" << sizeof(unsigned long); cout << "\t最大值:" << (numeric_limits<unsigned long>::max)(); cout << "\t最小值:" << (numeric_limits<unsigned long>::min)() << endl; cout << "double: \t" << "所占字节数:" << sizeof(double); cout << "\t最大值:" << (numeric_limits<double>::max)(); cout << "\t最小值:" << (numeric_limits<double>::min)() << endl; cout << "long double: \t" << "所占字节数:" << sizeof(long double); cout << "\t最大值:" << (numeric_limits<long double>::max)(); cout << "\t最小值:" << (numeric_limits<long double>::min)() << endl; cout << "float: \t\t" << "所占字节数:" << sizeof(float); cout << "\t最大值:" << (numeric_limits<float>::max)(); cout << "\t最小值:" << (numeric_limits<float>::min)() << endl; cout << "size_t: \t" << "所占字节数:" << sizeof(size_t); cout << "\t最大值:" << (numeric_limits<size_t>::max)(); cout << "\t最小值:" << (numeric_limits<size_t>::min)() << endl; cout << "string: \t" << "所占字节数:" << sizeof(string) << endl; // << "\t最大值:" << (numeric_limits<string>::max)() << "\t最小值:" << (numeric_limits<string>::min)() << endl; cout << "type: \t\t" << "************size**************"<< endl; return 0; }

本实例使用了 endl,这将在每一行后插入一个换行符,<< 运算符用于向屏幕传多个值,sizeof() 运算符用来获取各种数据类型的大小。

当上面的代码被编译和执行时,它会产生以下的结果,结果会根据所使用的计算机而有所不同:

type:         ************size**************
bool:         所占字节数:1    最大值:1        最小值:0
char:         所占字节数:1    最大值:        最小值:?
signed char:     所占字节数:1    最大值:        最小值:?
unsigned char:     所占字节数:1    最大值:?        最小值:
wchar_t:     所占字节数:4    最大值:2147483647        最小值:-2147483648
short:         所占字节数:2    最大值:32767        最小值:-32768
int:         所占字节数:4    最大值:2147483647    最小值:-2147483648
unsigned:     所占字节数:4    最大值:4294967295    最小值:0
long:         所占字节数:8    最大值:9223372036854775807    最小值:-9223372036854775808
unsigned long:     所占字节数:8    最大值:18446744073709551615    最小值:0
double:     所占字节数:8    最大值:1.79769e+308    最小值:2.22507e-308
long double:     所占字节数:16    最大值:1.18973e+4932    最小值:3.3621e-4932
float:         所占字节数:4    最大值:3.40282e+38    最小值:1.17549e-38
size_t:     所占字节数:8    最大值:18446744073709551615    最小值:0
string:     所占字节数:24
type:         ************size**************

typedef 声明

您可以使用 typedef 为一个已有的类型取一个新的名字。下面是使用 typedef 定义一个新类型的语法:

typedef type newname; 

例如,下面的语句会告诉编译器,feet 是 int 的另一个名称:

typedef int feet;

现在,下面的声明是完全合法的,它创建了一个整型变量 distance:

feet distance;

枚举类型

枚举类型(enumeration)是C++中的一种派生数据类型,它是由用户定义的若干枚举常量的集合。

如果一个变量只有几种可能的值,可以定义为枚举(enumeration)类型。所谓"枚举"是指将变量的值一一列举出来,变量的值只能在列举出来的值的范围内。

创建枚举,需要使用关键字 enum。枚举类型的一般形式为:

enum 枚举名{ 
     标识符[=整型常数], 
     标识符[=整型常数], 
... 
    标识符[=整型常数]
} 枚举变量;
    

如果枚举没有初始化, 即省掉"=整型常数"时, 则从第一个标识符开始。

例如,下面的代码定义了一个颜色枚举,变量 c 的类型为 color。最后,c 被赋值为 "blue"。

enum color { red, green, blue } c;
c = blue;

默认情况下,第一个名称的值为 0,第二个名称的值为 1,第三个名称的值为 2,以此类推。但是,您也可以给名称赋予一个特殊的值,只需要添加一个初始值即可。例如,在下面的枚举中,green 的值为 5。

enum color { red, green=5, blue };

在这里,blue 的值为 6,因为默认情况下,每个名称都会比它前面一个名称大 1,但 red 的值依然为 0。

类型转换

类型转换是将一个数据类型的值转换为另一种数据类型的值。

C++ 中有四种类型转换:静态转换、动态转换、常量转换和重新解释转换。

静态转换(Static Cast)

静态转换是将一种数据类型的值强制转换为另一种数据类型的值。

静态转换通常用于比较类型相似的对象之间的转换,例如将 int 类型转换为 float 类型。

静态转换不进行任何运行时类型检查,因此可能会导致运行时错误。

实例

int i = 10; float f = static_cast<float>(i); // 静态将int类型转换为float类型

动态转换(Dynamic Cast)

动态转换通常用于将一个基类指针或引用转换为派生类指针或引用。动态转换在运行时进行类型检查,如果不能进行转换则返回空指针或引发异常。

实例

class Base {}; class Derived : public Base {}; Base* ptr_base = new Derived; Derived* ptr_derived = dynamic_cast<Derived*>(ptr_base); // 将基类指针转换为派生类指针

常量转换(Const Cast)

常量转换用于将 const 类型的对象转换为非 const 类型的对象。

常量转换只能用于转换掉 const 属性,不能改变对象的类型。

实例

const int i = 10; int& r = const_cast<int&>(i); // 常量转换,将const int转换为int

重新解释转换(Reinterpret Cast)

重新解释转换将一个数据类型的值重新解释为另一个数据类型的值,通常用于在不同的数据类型之间进行转换。

重新解释转换不进行任何类型检查,因此可能会导致未定义的行为。

实例

int i = 10; float f = reinterpret_cast<float&>(i); // 重新解释将int类型转换为float类型

C++语言的数据类型 C++允许程序员定义自己的数据类型,这使得开发者可以为特定问题创建更具表达力的结构。用户自定义数据类型主要包括类、结构体、枚举和联合体。C++中的数据类型是程序设计的基础,选择合适的数据类型可以有效提升程序的执行效率和可读性。从基本数据类型到复合数据类型,每种类型都有其特定的用途和场景。在深入理解数据类型的基础上,开发者可以更好地运用C++进行高效编程。在实际开发中,合理组织和使用数据类型,不仅能够减小内存的使用,确保程序的效率,还能够提高代码的可读性和可维护性。 阅读详情

相关推荐

C++万能数据结构,适当扩展可以自由组合表达几乎所有的数据类型

// Example program #include < iostream > #include < complex > #include < string > #include < list > #include < vector > #include < sstream > using namespa...

拔剑—浆糊的传说 617

C++数据类型总结,看这一篇就够了

C++数据类型总结

Jasmine-Lily的博客 3857

【C++】数据类型

菜鸟教程传送门菜鸟教程里讲的太全面了,很多数据类型我们平常都用不上,因此写一篇笔记记录常用的数据类型。C++需要在变量被定义时就赋予其类型——为它开辟一部分内存空间。

Dust的博客 1181

C++基础一:基本数据类型

C++基础一:基本数据类型

weixin_63026364的博客 9848

[C++数据类型 cpp]——揭秘C++丰富多彩的数据类型系统

C++被誉为高级编程语言中的“萝卜白菜”,因其不仅继承了C语言的基本特性,同时还具有面向对象、泛型编程、高效能等特点。作为一门通用编程语言,C++拥有丰富多彩的数据类型系统,包括基本数据类型、复合数据类型、指针类型等,这些数据类型为C++提供了强大的数据处理能力和灵活的代码编写方式。C++的数据类型系统是其编程语言中的重要组成部分,为程序员提供了强大的数据处理能力和灵活的代码编写方式。掌握C++的数据类型,对于编写高效、可靠的程序具有重要的意义。指针类型包括基本类型指针、数组指针、函数指针等。

TechBlitzZ的博客 146

[C++其他数据类型 cpp]——探究C++中的其他数据类型

在C++编程中,我们经常使用的主要是基本数据类型,如整型、浮点型、字符型等。但是,C++中还有其他不太常见但非常有用的数据类型,它们可以帮助我们更好地解决某些特定的问题。除了以上几种,C++中还有位字段类型、自定义类型等其他数据类型。布尔型是C++中最简单的数据类型之一,它只有两个取值:true和false。指针类型变量存储的是另一个变量的内存地址。枚举类型可以将一组具有相同特征的常量定义为一个枚举类型,枚举量是枚举类型的变量。空类型不表示任何值,用于表示函数的返回值为空或者指针没有指向特定类型的对象。

2301_79325657的博客 140

[cpp]c++中的 _t 类的数据类型

文章目录1. 简介2.例子3.Reference 1. 简介 _t 类的数据结构大都是用 typedef 来定义的,主要用于跨平台时,平台字长不一,会造成代码不好维护的情况。 2.例子 一般整型对应的 *_t 类型有: unit8_t – 1 byte unit16_t – 2 byte unit32_t – 4 byte unit64_t – 8 byte 下面是一个与 c99标准中的一个...

Be patient! Think twice! Word harder! 1673

【C++类的定制 cpp】——打造专属于你的数据类型

例如,在上面的示例代码中,我们设计了一个字符串类 MyString,可以用来代替 char* 类型,这样就可以更加安全、方便地处理字符串问题。在上面的代码中,我们以 MyString 类为例,实现了该类中的构造函数、析构函数、复制构造函数、赋值操作符等函数成员。上面的代码中,我们定义了一个名为 MyString 的类,并且定义了它的构造函数、析构函数、复制构造函数、赋值操作符等函数成员。C++ 类的定制是 C++ 语言中的重要特性之一,让我们可以自由地定义和控制数据类型,更好地适应不同的场景和需求。

CodeRoarX的博客 114

初识Cpp之 四、数据类型

​ 结构体是C++的OOP基础,结构体是用户定义的类型,而结构声明定义了这种类型的数据熟悉,定义了类型后,便可以创建这种类型的变量。函数来进行字符串的比较,详见C语言。​ C++将大括号初始化器作为一种通用的初始化方式,可用于所有类型,同样这种方式可以适用于数组,并且可以省略。​ 因此,在C++中有两种风格的字符串,一种是延续了C语言风格的字符串,另一种是C++风格的字符串。函数,使用这种方式,需要时刻注意不能超过数组的容量,否则会出错。​ 结构体的声明,结构体的声明和定义结构体变量可以组合成一个步骤。

Shen Mu Xin's Blog 2215

gdb对dwarf调试信息的解析和使用

gdb的对dwarf的调试信息的解析到使用的过程分析

JS072110的专栏 9568

HX720数据采集实战:从硬件连接到姿态解析(含避坑指南)

本文详细介绍了HX720高精度ADC芯片在数据采集与姿态解析项目中的实战应用。内容涵盖从硬件电路设计、驱动源码编写与优化,到原始数据处理、校准以及最终姿态角度计算的完整流程,并提供了关键的避坑指南和调试技巧,帮助开发者高效完成从传感器信号到可用姿态数据的转换。

i8j9k0l1的博客 488

C++基本数据类型大小和范围

https://docs.microsoft.com/en-us/cpp/cpp/data-type-ranges?view=vs-2019 https://www.geeksforgeeks.org/c-data-types/ Data Type Size (in bytes) Range short int 2 -32,768 to 32,767(-2^15~~...

一面之媛 5466

什么是Merkle树?用“文件柜”类比理解区块链的核心技术

Merkle树是一种用于区块链的数据结构,像一个高效的“文件柜”,用于存储和验证大量交易数据。比特币通过Merkle树将交易哈希组织成树状结构,层层汇总,最终生成一个唯一的根哈希,存储在区块头中。这种设计大幅减少数据存储和验证成本,支持快速校验交易的完整性和存在性。Merkle树通过密码学保证数据不可篡改,广泛应用于比特币、区块链及其他分布式系统。它的优势在于高效、轻量和安全,尤其适合轻节点验证和数据同步。理解Merkle树就像掌握区块链的“索引秘籍”,是Web3世界的关键技术。

在路上的专栏 1193

【C++从入门到入门】C++基础:.cpp 基本结构,基本数据类型,引用,指针,函数

c++基础:.cpp 基本结构,基本数据类型,引用,指针,函数

android_zyf的博客 1153

Jenkins+docker 微服务实现自动化部署安装和部署过程

本文详细介绍了如何使用Docker部署Jenkins自动化服务器。主要内容包括:1)拉取Jenkins官方或BlueOcean镜像;2)创建容器并配置端口映射、数据卷挂载;3)设置防火墙规则;4)配置清华大学镜像加速;5)安装必要插件;6)SSH密钥配置;7)构建触发器设置;8)编写自动化构建脚本。通过Docker部署Jenkins可以简化安装流程,确保环境一致性,并利用容器特性实现快速启动和管理。文章提供了完整的配置步骤和注意事项,帮助用户快速搭建CI/CD环境。

qq_33665793的博客 1693

配置oem 13c以监控管理数据库

使用oem13c监控数据库

雅冰石的专栏 1812

cpp基本数据类型大小

C++ 标准定义了每种基本数据类型的最小大小,具体大小取决于编译器和硬件平台。使用 sizeof 运算符可以确定在特定平台上的实际大小。理解这些基本数据类型和它们的大小对于编写高效和可移植的 C++ 代码至关重要。在 64 位系统上的 Windows 和 Linux 平台上,C++ 基本数据类型的大小通常会有所不同。这些差异主要是由于编译器的实现和操作系统的架构。

heeheeai的博客 898

内存|内存的概念、内存的作用、内存的物理结构及内存使用

内存是硬件,是用于存放数据的硬件。程序执行前需要先放到内存中才能被CPU处理。内存是与CPU沟通的桥梁,计算机中所有程序的运行都要依靠内存,内存对计算机的影响非常大。本文简单介绍了内存的概念、作用、物理结构以及使用,内存远不止如此,后续文章会逐步深入讲解。

qq_59938293的博客 2万+

CPP学习备忘[2] 数据类型

【1】C++中的数据类型,有语言既定的内部数据类型,也有程序员自定义的外部数据类型,其中内部数据类型有:int、char、bool、float、double;   【2】在C++中有两种字符串,一种是从C沿袭过来的,称为C-串。C-串是以一个全0位字节作为结束符的字符序列。     C-串的类型为char*,说得更精确一点是const char*。由于C-串类型是字符指针,因此比较两个相同的

我的读书笔记(2011-2013) 368

【即插即用模块】卷积篇 | TGRS 2025 | HLKConv:小核+空洞=大核,感受野一致,但更轻更准!

本文介绍了分层大核卷积模块HLKConv,该模块通过动态大核+空洞卷积实现高效感受野扩展,将超大核卷积分解为小核+空洞卷积(如53×53核用17×17+dilation=3实现),计算量仅为普通大核的1/10。模块采用双分支设计:基础卷积分支捕捉局部细节,大核空洞分支捕捉长距离关联,通过1×1卷积融合。实验表明HLKConv在红外小目标检测中优于传统大核卷积,适用于高分辨率视觉任务。代码实现了不同核尺寸的配置,输入输出特征维度保持不变,计算效率显著提升。

主要更新底层视觉(去噪、超分等)相关的科研内容,形式为【论文精读】+【论文复现】 347

基于混合智能框架的景区边界范围预测与补全系统

摘要 本文提出一种混合智能框架,结合随机森林模型和GIS规则约束,解决景区边界缺失问题。系统基于Python和ArcGIS平台,利用多源地理空间数据训练随机森林分类器预测景区范围,并集成地形、水文、道路等GIS规则进行优化。实验结果表明,该方法能有效预测15000个景区的边界,精度优于单一模型。创新点在于: 1)数据驱动与知识驱动相结合的混合智能范式; 2)面向全国尺度的大规模边界补全; 3)提供完整的Python+ArcGIS实现方案。该系统为景区精细化管理提供了技术支撑,具有实用价值。

huanghm88的专栏 284

【C++】详细讲解C++的数据类型~

C++规定在创建一个变量或者常量时,必须要指定出相应的数据类型,否则无法给变量分配内存。

知识记录 4616

jdk-8u144-linux-x64.tar.gz.

该资源为搭建Linux系统Java环境用,资源的后缀为tar.gz格式的压缩包

C++中所有数据类型

本文详细介绍了C++中的数据结构

2501_90255623的博客 798

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

ET2012新版免狗免安装绿色软件

ET2012新版免狗免安祖昂绿色软件。,新界面,新视觉,

上一篇: c++基本语法
下一篇: c++变量类型
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值