boost:unordered_map和std::map的使用详解和性能比较

boost之unordered_map unordered_map的使用#include <iostream> #include <boost/assign.hpp> #include <hash_map> #include <boost/unordered_map.hpp> #include <boost/typeof/typeof.hpp> using namespace std; using namespace boost; int 阅读详情


今天看到 boost::unordered_map, 它与 stl::map的区别就是,stl::map是按照operator<比较判断元素是否相同,以及比较元素的大小,然后选择合适的位置插入到树中。所以,如果对map进行遍历(中序遍历)的话,输出的结果是有序的。顺序就是按照operator< 定义的大小排序。

而boost::unordered_map是计算元素的Hash值,根据Hash值判断元素是否相同。所以,对unordered_map进行遍历,结果是无序的。


用法的区别就是,stl::map 的key需要定义operator< 。 而boost::unordered_map需要定义hash_value函数并且重载operator==。对于内置类型,如string,这些都不用操心。对于自定义的类型做key,就需要自己重载operator< 或者hash_value()了。 


最后,说,当不需要结果排好序时,最好用unordered_map。


其实,stl::map对于与java中的TreeMap,而boost::unordered_map对应于java中的HashMap //Java我不是很熟,这个不确定是否正确

stl::map

[cpp]
  1. #include<string>  
  2. #include<iostream>  
  3. #include<map>  
  4.   
  5. using namespace std;  
  6.   
  7. struct person  
  8. {  
  9.     string name;  
  10.     int age;  
  11.   
  12.     person(string name, int age)  
  13.     {  
  14.         this->name =  name;  
  15.         this->age = age;  
  16.     }  
  17.   
  18.     bool operator < (const person& p) const  
  19.     {  
  20.         return this->age < p.age;  
  21.     }  
  22. };  
  23.   
  24. map<person,int> m;  
  25. int main()  
  26. {  
  27.     person p1("Tom1",20);  
  28.     person p2("Tom2",22);  
  29.     person p3("Tom3",22);  
  30.     person p4("Tom4",23);  
  31.     person p5("Tom5",24);  
  32.     m.insert(make_pair(p3, 100));  
  33.     m.insert(make_pair(p4, 100));  
  34.     m.insert(make_pair(p5, 100));  
  35.     m.insert(make_pair(p1, 100));  
  36.     m.insert(make_pair(p2, 100));  
  37.       
  38.     for(map<person, int>::iterator iter = m.begin(); iter != m.end(); iter++)  
  39.     {  
  40.         cout<<iter->first.name<<"\t"<<iter->first.age<<endl;  
  41.     }  
  42.       
  43.     return 0;  
  44. }  
#include<string>
#include<iostream>
#include<map>

using namespace std;

struct person
{
	string name;
	int age;

	person(string name, int age)
	{
		this->name =  name;
		this->age = age;
	}

	bool operator < (const person& p) const
	{
		return this->age < p.age;
	}
};

map<person,int> m;
int main()
{
	person p1("Tom1",20);
	person p2("Tom2",22);
	person p3("Tom3",22);
	person p4("Tom4",23);
	person p5("Tom5",24);
	m.insert(make_pair(p3, 100));
	m.insert(make_pair(p4, 100));
	m.insert(make_pair(p5, 100));
	m.insert(make_pair(p1, 100));
	m.insert(make_pair(p2, 100));
	
	for(map<person, int>::iterator iter = m.begin(); iter != m.end(); iter++)
	{
		cout<<iter->first.name<<"\t"<<iter->first.age<<endl;
	}
	
	return 0;
}

output:

Tom1    20
Tom3    22
Tom4    23
Tom5    24


operator<的重载一定要定义成const。因为map内部实现时调用operator<的函数好像是const。

由于operator<比较的只是age,所以因为Tom2和Tom3的age相同,所以最终结果里面只有Tom3,没有Tom2


boost::unordered_map

[cpp]
  1. #include<string>  
  2. #include<iostream>  
  3.   
  4. #include<boost/unordered_map.hpp>  
  5.   
  6. using namespace std;  
  7.   
  8. struct person  
  9. {  
  10.     string name;  
  11.     int age;  
  12.   
  13.     person(string name, int age)  
  14.     {  
  15.         this->name =  name;  
  16.         this->age = age;  
  17.     }  
  18.   
  19.     bool operator== (const person& p) const  
  20.     {  
  21.         return name==p.name && age==p.age;  
  22.     }  
  23. };  
  24.   
  25. size_t hash_value(const person& p)  
  26. {  
  27.     size_t seed = 0;  
  28.     boost::hash_combine(seed, boost::hash_value(p.name));  
  29.     boost::hash_combine(seed, boost::hash_value(p.age));  
  30.     return seed;  
  31. }  
  32.   
  33. int main()  
  34. {  
  35.     typedef boost::unordered_map<person,int> umap;  
  36.     umap m;  
  37.     person p1("Tom1",20);  
  38.     person p2("Tom2",22);  
  39.     person p3("Tom3",22);  
  40.     person p4("Tom4",23);  
  41.     person p5("Tom5",24);  
  42.     m.insert(umap::value_type(p3, 100));  
  43.     m.insert(umap::value_type(p4, 100));  
  44.     m.insert(umap::value_type(p5, 100));  
  45.     m.insert(umap::value_type(p1, 100));  
  46.     m.insert(umap::value_type(p2, 100));  
  47.       
  48.     for(umap::iterator iter = m.begin(); iter != m.end(); iter++)  
  49.     {  
  50.         cout<<iter->first.name<<"\t"<<iter->first.age<<endl;  
  51.     }  
  52.       
  53.     return 0;  
  54. }  
#include<string>
#include<iostream>

#include<boost/unordered_map.hpp>

using namespace std;

struct person
{
	string name;
	int age;

	person(string name, int age)
	{
		this->name =  name;
		this->age = age;
	}

	bool operator== (const person& p) const
	{
		return name==p.name && age==p.age;
	}
};

size_t hash_value(const person& p)
{
	size_t seed = 0;
	boost::hash_combine(seed, boost::hash_value(p.name));
	boost::hash_combine(seed, boost::hash_value(p.age));
	return seed;
}

int main()
{
	typedef boost::unordered_map<person,int> umap;
	umap m;
	person p1("Tom1",20);
	person p2("Tom2",22);
	person p3("Tom3",22);
	person p4("Tom4",23);
	person p5("Tom5",24);
	m.insert(umap::value_type(p3, 100));
	m.insert(umap::value_type(p4, 100));
	m.insert(umap::value_type(p5, 100));
	m.insert(umap::value_type(p1, 100));
	m.insert(umap::value_type(p2, 100));
	
	for(umap::iterator iter = m.begin(); iter != m.end(); iter++)
	{
		cout<<iter->first.name<<"\t"<<iter->first.age<<endl;
	}
	
	return 0;
}


输出

Tom1    20
Tom5    24
Tom4    23
Tom2    22
Tom3    22


必须要自定义operator==和hash_value。 重载operator==是因为,如果两个元素的hash_value的值相同,并不能断定这两个元素就相同,必须再调用operator==。 当然,如果hash_value的值不同,就不需要调用operator==了。


以上抄之 http://blog.csdn.net/orzlzro/article/details/7099231,自己也跑过,无误!


下边谈谈boost::unorder_map和std::map在插入和查找方面的性能

int main(int argc,int** argv)
{
 time_t beginTime_1 = time(0);

 boost::unordered_map<int, int> test_hash;
 for (int i = 0; i < 5000000; i++)
  {
     test_hash.insert(std::pair<int, int>(i, i));
     }
 std::cout << test_hash.size() << std::endl;
 
 time_t endTime_1 = time(0);

 for (int i = 0; i< 5000001; ++i)
  {
  boost::unordered_map<int, int>::iterator iter = test_hash.find(i);
  if (iter == test_hash.end())
  {
   std::cout << "false" << std::endl;
  }
 }

 time_t endTime_2 = time(0);

 std::cout << "unorderMap insert 50000000 cost time: " << endTime_1 - beginTime_1 << std::endl;
 std::cout << "unorderMap find 50000000 cost time " << endTime_2 - endTime_1 << std::endl;

 {
  time_t first_time = time(0);
  std::map<int, int> test_hash;
  for (int i = 0; i < 5000000; i++)
  {
   test_hash.insert(std::pair<int, int>(i, i));
  }
  std::cout << test_hash.size() << std::endl;
  time_t second_time = time(0);

  for (int i = 0; i< 5000001; ++i)
     {
   std::map<int, int>::iterator iter = test_hash.find(i);
   if (iter == test_hash.end())
   {
    std::cout << "false" << std::endl;
   }
  }
  time_t third_time = time(0);
  std::cout << "std::map insert 50000000 cost time: " << second_time - first_time << std::endl;
  std::cout << "std::map find 50000000 cost time " << third_time - second_time << std::endl;
 }
 system("pause");
 return 0;

}


结果:





boost::unordered_map 和 std::map 的效率,内存比较 // Test_Boost_Unordered.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include "boost/unordered_map.hpp" #include #include #include "time.h" using namespace std; int _tmain(int argc, _TCHA 阅读详情

相关推荐

在c++11 的unordered_set和unordered_map中插入pair或tuple作为键值

C++的std::pair是无法std::hash的,为了在unordered_set和unordered_map中使用std::pair,有如下方法。还有个前提,pair 和 tuple 中的元素本身得是可以 std::hash 哈希的。注意:上面的代码使用的异或(XOR),由于x^x == 0并且x^y == y^x,所以应该配合一些位运算的shift或rotate来做。方法一:专门写个可用于std::pair的std::hash。方法二:使用boost::hash。想完成的任务 与 遇到的问题。

GXQ的博客 1571

C++ STL系列之 boost:unordered_map和 std::map区别详解 (***)

C++ STL系列之 boost:unordered_map和 std::map区别详解 (***)C++ STL系列之 boost:unordered_map和 std::map区别详解 (***)C++ STL系列之 boost:unordered_map和 std::map区别详解 (***)开发C++时,选择合适的数据结构是一个十分重要的步骤。因此,必须对每一个数据结构的原理及应用场景都有所了解。boost::unordered_map和 std::map都是一种关联。

ken2232的博客 1112

C++键值对实现:从std::map到自定义哈希表的性能优化与实战

键值对是计算机科学中一种基础且核心的数据结构,它通过唯一的键来快速访问对应的值,其底层原理基于高效的查找算法。在C++编程实践中,标准库提供了`std::map`和`std::unordered_map`两种主要实现,分别基于红黑树和哈希表,它们在有序性、查找速度及内存开销上各有侧重。理解其技术价值在于能够根据应用场景(如配置管理、缓存系统或高频查找服务)做出最优选择,从而显著提升程序性能。例如,通过预分配空间(reserve)和利用移动语义等工程技巧,可以进一步优化`std::unordered_map`

weixin_34111790的博客 468

STL map与Boost unordered_map

今天看到 boost::unordered_map, 它与 stl::map的区别就是,stl::map是按照operator<比较判断元素是否相同,以及比较元素的大小,然后选择合适的位置插入到树中。所以,如果对map进行遍历(中序遍历)的话,输出的结果是有序的。顺序就是按照operator< 定义的大小排序。 而boost::unordered_map是计算元素的Hash值,根据Hash值

orzlzro的专栏 4万+

c++ map 查找性能测试

最近在为推荐服务作性能调优,这个服务的主要逻辑是用离线计算的模型数据给请求中的每个广告打分,再返回这些广告的排序结果,这里面打分的过程其实就用请求中的数据拼成各种key,去查一个大的 map,这种计算非常多,成为了主要的性能瓶颈,代码比较老,使用的是 boost::unordered_map,为了解决这个问题,找了一些第三方库和标准库对比了一下 下面是在一台 aws r4.xlarge 机器上的...

hatlonely的专栏 5807

C++自定义类型哈希实现:从std::hash特化到unordered_map高效应用

哈希函数是计算机科学中用于数据快速检索的核心技术,它将任意长度的输入映射为固定长度的输出值。其原理基于散列算法,通过数学变换为每个数据对象生成唯一的“指纹”。在C++编程中,哈希技术的价值在于支撑std::unordered_map等关联容器的O(1)平均时间复杂度操作,是实现高性能查找的关键。实际应用场景广泛,从数据库索引到缓存系统都依赖高效的哈希实现。本文聚焦于C++自定义类型的哈希处理,针对std::unordered_map等容器要求,详细解析如何通过特化std::hash模板或提供自定义哈希函数对

weixin_30386713的博客 376

测试std::map与boost::unordered_map性能

测试方法:加载文件,将数据分别插入到std::map和boost::unordered_map中,分别保存string作为key和int作为key的map数据,计算插入时间,根据列表分别在对应的map中查找一次所有的key值,计算查找耗时: 测试结果:插入耗时boost::unordered_map是std map的一半左右,查找耗时是std map的1/3左右 测试代码: #include <boost/unordered/unordered_map.hpp> #include &lt

XiaoWhy的专栏 706

boost::unordered_map使用详解

1、特点: (1)、unordered_map中的元素是无序的,其插入位置由根据键计算出的Hash值决定; (2)、unordered_map中的元素键是不能相同的; (3)、使用[]插入时,如果键不存在,会直接插入,如果键已存在,会更改键所对应的值。使用()插入时,如果键不存在,会发出异常,如果键存在,会更改键对应的值; (4)、使用自定义的类型作为键,必须重写==操作符,同时必须自己实...

小米的修行之路 3227

C++ std::map与std::unordered_map深度对比:红黑树与哈希表的工程选型指南

在C++编程中,关联容器是处理键值对数据结构的核心组件,其底层实现原理直接决定了程序的性能表现。红黑树作为一种自平衡二叉搜索树,通过严格的排序规则和旋转操作保证了O(log n)的稳定时间复杂度,适用于需要有序遍历和范围查询的场景。哈希表则利用哈希函数将键映射到桶中,理想情况下可实现O(1)的常数级访问速度,但需要处理哈希冲突和重哈希问题。理解这两种数据结构的差异对于优化程序性能至关重要,特别是在处理大规模数据或高并发场景时。本文聚焦于C++标准库中的std::map(基于红黑树)和std::unorder

weixin_34353714的博客 461

使用Boost::mpl模块实现Map的测试程序

在上面的代码中,我们定义了一个具有两个键值对的Boost::mpl::map对象my_map,其中第一个键值对的键为int类型的0,值为float类型的0.0,第二个键值对的键为double类型的1.0,值为char类型的’a’。其中包括一个非常有用的模块——Boost::mpl::map,该模块实现了一个字典容器,可以通过键值对存储数据。总之,Boost::mpl::map是一个非常方便和实用的元编程工具,可以大大提高程序的效率和可维护性。使用Boost::mpl模块实现Map的测试程序。

持续更新 135

全球最大光伏电池缺陷异常检测数据集PVELAD【发布】

下载地址 1:GitHub - binyisu/PVEL-AD 下载地址 2:http://aihebut.com/col.jsp?id=118 下载地址 3:NAVEDownload 竞赛测试系统:Photovoltaic cell anomaly detection | Kaggle 一、简介 PVEL-AD 数据集又叫做EL2021数据集是用于对光伏电池异常缺陷检测方法进行基准测试的数据集,重点是光伏电池工业检测。PVEL-AD包含 36,543 张具有各种内部缺陷和异构背...

苏打水的杯子的博客 2万+

boost::unordered_map 和 std::map 的对比(包括速度和内存消耗)

背景: 最近处理的单个文件,大概有13GB,数量条数约5000万。一次性读人到内存需要选择合适的数据结构对其进行存储。本文对比boost::unordered_map 和 std::map 这两种数据结构在该使用情景下的效率。 代码: #include "boost/unordered_map.hpp" #include #include #include "time.h" us

ljp1919的专栏 8471

NOC片上网络设计解析:从总线瓶颈到拓扑、路由与QoS实践

随着SoC中主设备数量激增,传统共享总线与交叉开关在带宽、时序和可扩展性上逐渐力不从心。片上网络(NOC)借鉴计算机网络的分组交换思想,将芯片内部互连视为分布式子系统,通过节点、路由器、链路与网络接口的协同,实现高效的并行数据传输。本文从NOC的基本组成出发,深入对比Mesh、Torus、Ring等拓扑的适用场景,剖析XY路由与Credit流控的工作机制,并探讨AXI/CHI协议适配、QoS调度及低功耗设计的工程实践。掌握这些核心概念,有助于工程师在AI芯片、多核处理器及Chiplet互连设计中精准构建高带

weixin_29190651的博客 246

C++ STL系列之boost:unordered_map和std::map区别详解

开发C++时,选择合适的数据结构是一个十分重要的步骤。因此,必须对每一个数据结构的原理及应用场景都有所了解。 boost::unordered_map和std::map都是一种关联式容器,且原理类似,通过存储key-value键值对,可通过key快速检索到value,并且key是不重复的。但是,它们之间有一些区别,下面将逐一介绍。 排序区别: map是有序的:按照operator&lt;比较...

Yummy 4341

通过CN3口直接控制台达伺服电机A2-M(二)

既然可以通过RS485与伺服驱动器进行通讯,那么就肯定可以控制转速 首先,需要了解下 ‘控制模式及控制命令输入源设定’ 依据以上资料,速度控制模式有两种,S和SZ模式,分别对应模式选择中的02和04,对P1-01的地址0102进行写地址操作即可实现,一开始我使用了S模式,但是这个模式在寸动模式下会自动运转,不符合我控制的要求,后面改用SZ模式,就可以实现零速度。 使用串口工具发送命令:“01 06 01 02 00 04 28 35”即可以实现设置,设置完成后可以手动在伺服驱动器的按键面板上进行确

HKing_evil的博客 6828

Vcenter虚拟机磁盘转换实战:如何用StarWind V2V将vmdk转为qcow2(附空间优化技巧)

本文详细介绍了如何使用StarWind V2V Converter将Vcenter中的vmdk虚拟机磁盘高效转换为qcow2格式,并提供了空间优化技巧。从准备工作、导出vmdk文件到转换过程中的性能调优,帮助管理员在迁移虚拟机时减少资源消耗,确保数据完整性和性能。

dell8的博客 206

C++哈希表实战:unordered_set与unordered_map深度解析与性能优化

哈希表是一种基于键值对存储的数据结构,通过哈希函数将键映射到数组索引实现快速访问。其核心原理是通过哈希函数计算键的哈希值,再通过取模运算定位到数组中的桶位置,理想情况下实现O(1)时间复杂度的查找、插入和删除操作。哈希表的技术价值在于解决了传统线性查找O(n)和树结构O(log n)的性能瓶颈,特别适合需要极速键值查找的场景。在实际工程中,哈希表广泛应用于缓存系统、词频统计、数据去重和快速成员检查等场景。C++标准库中的unordered_set和unordered_map正是基于哈希表实现的无序关联容器,

weixin_30271335的博客 356

别再死记硬背了!一张图搞懂无刷电机半桥与全桥驱动的核心差异(附避坑指南)

本文深入解析无刷直流电机的半桥与全桥驱动方式的核心差异,提供直观对比与选型指南。半桥驱动结构简单、成本低,适合低要求场景;全桥驱动性能优越但复杂,适用于高精度控制。文章还包含实战避坑指南,帮助工程师优化驱动方案选择与应用。

weixin_29290947的博客 326

c++11:unordered_map和pair合用的坑

事情是这样的, 今天在编译的时候报错,很长,报错的地方是std::ordered_map的insert操作,但换成stdmap就没问题, 大概是跟std::unordered_map和std::pair有关,我截取几段, error: no matching function for call to ‘std::pair<key, std::_List_iterator<long long int> >::pair(const key&, std::_List_ite

8701

OpenClaw 在 Docker 容器中的部署实战——零配置启动

本文介绍了OpenClaw在Docker容器中的快速部署方法,对比了本地部署与容器化部署的优势。通过官方镜像和Docker Compose两种方式,5分钟即可完成部署,并详细讲解了配置管理方案(挂载配置文件和环境变量)。文章还提供了飞书集成配置方法,以及生产环境下的日志管理、资源限制、健康检查等优化建议。最后包含常见问题排查指南,帮助开发者快速实现OpenClaw的容器化部署。

刘一说的IT专栏 922

【大模型+知识图谱】哈工大版chinese-roberta-wwm-ext模型介绍、下载部署和GPU显卡配置

RoBERTa模型的一个重要改进版本,由阿里云的研究团队提出。而Chinese RoBERTa-wwm-ext则是针对中文文本的预训练模型,它在哈工大的研究团队手中进一步优化,特别适用于中文自然语言处理任务。

知识靠谱的博客 2780

thread 线程安全 unordered_map

C++11:基于std::unordered_map和共享锁构建线程安全的map https://blog.csdn.net/10km/article/details/52072061 https://blog.csdn.net/10km/article/details/52067929 程序中经常需要缓存一些数据, 但是std::map 不是线程安全的 https://blog.c...

BlueBirdssh的专栏 3934

《测控仪器设计课后习题答案-浦昭邦-王宝光

《测控仪器设计课后习题答案-浦昭邦-王宝光 1.1. 测控仪器的概念是什么? 测控仪器则是利用测量和控制的理论,采用机、电、光各种计量测试原理及控制系统与计算机相结合的一种范围广泛的测量仪器。 1.2. 为什么说测控仪器的发展与科学技术发展密切相关? 仪器仪表的用途和重要性— 遍及国民经济各个部门,深入到人民生活的各个角落,仪器仪表中的计量测试仪器与控制仪器统称为测控仪器,可以说测控仪器的水平是科学技术现代化的重要标志。 仪器仪表的用途: 在机械制造业中:对产品的静态与动态性能测试;加工过程的控制与监测;设

无名何许人的博客 2982

把boost::bind的返回值插入到std::unordered_map中

只能以insert的形式插入,不能以[]的形式插入。(可能是因为boost::bind的结果不是copyalbe的?) #include <iostream> #include <unordered_map> #include <boost/bind.hpp> using namespace std; struct A { void print(int ...

已迁移至 https://seekstar.github.io/ 352

全球国家地区城市数据

MySQL全球国家地区城市数据报。。。。。。。。。。。。

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

C++ unordered_map 哈希表原理、性能优化与实战避坑指南

哈希表是一种基于键值对存储数据的高效数据结构,其核心原理是通过哈希函数将键映射到数组索引,从而实现平均接近 O(1) 的快速查找、插入和删除。哈希函数的质量和负载因子的控制是决定其性能的关键,良好的设计能有效减少哈希碰撞,避免性能退化为 O(n)。在 C++ 工程实践中,std::unordered_map 作为标准库的哈希表实现,广泛应用于需要快速数据检索的场景,如游戏数据映射、服务器会话管理和高频配置查询。然而,其性能优势的实现依赖于对底层机制的理解,包括哈希函数定制、迭代器失效规则以及内存布局对缓存的

weixin_30847939的博客 357

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

上一篇: map和hash_map的比较
下一篇: std::auto_ptr的使用方法
ksperfect
博客等级 码龄15年 1粉丝 11原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值