C++实现Chi-square 特征词选择算法

特征选择算法之 chisquare 算法 chisquare特征选择算法: 通过计算各个特征的卡方值,进行排序后得到。 步骤如下: 1. 假设该特征与目标特征无关。 2. 计算卡方值,若卡方值较小,则相关性较小; 若较大,则相关性较大。 每个特征的卡方值计算应如下:              X^2 = ∑ ((YA - YB)^ 2 / YB) 其中,YA是每个样本中,YA的实际值,而YB为理想值,即假设无关成立时 阅读详情

作者:finallyliuyu(转载请标明原作者与出处)

在文本分类问题中,离不开特征词选择模块。特征选择是特征降维的关键步骤。

  1. 首先我们给出一般性的特征词选择模块的伪代码描述:

特征词选择算法一般框架图

(此图摘自 C.D. Maning Introduction to InformationRetrieval 原版p251页 或者王斌译版p188页)

此处仅赘述两点,其他还劳请读者自己去看书

1。 上面的伪代码给出的是算法是针对某一个类别,按照某种测度(如IG,CHI-square)遴选出 top k个特征词;伪代码中的 ComputeFeatureUtility(D,t,c)。就是在计算上文提到的“某种测度”

2。针对某个分类问题,如何遴选出全部的特征词?

方法有很多,这里仅指出一种:假设有N个类别,共需要选取K个特征词,那么每个类别需要选取的特征词数目为K/N。

 

下面给出Chi-square的计算公式(出处同上,原版书p256页,王斌译作p192页):

chi-square 公式

上面的公式和下面的公式是等价的,可以由下面的公式推导出上面的公式,在计算机实现上,我们通常采用上面的公式。

chi-square原公式

 

可以说上面的两个公式,通通是在构造一个chi-square 分布的检测统计量(test statistic)(在数理统计中 chi-square 常常用于检测两个事件之间的独立性,如果独立则 chi-square=0 相关知识请查阅 数理统计关于 假设检验的相关章节)

  1. 下面开始讲解chi-square特征词选择法的具体实现

主流的contingency table的定义。

针对某一个term t 和类别c

主流contingency

N11:该词出现在该类的多少篇文章中;

N10:该词出现的文章有多少篇不再该类中;

N01:该类别中有多少篇文章不含有该词;

N00:训练语料库中共有多少篇文章即不含该词,也不包含在该类中。

 

 

在给出实现代码之前,先来看一段对程序实现会有启发作用的话:

contigencyTable

(出处同上,p257页)

这段话引出了一个数据结构:它保存了一个词在每个类别中出现和不出现的情况:比如有n个类别,那么这个数据结构的每一行保存的是:N11,N01。 在我的代码中,我把这个数据结构亦称作是contingency table和主流的contingency table定义可能会稍有区别,不过既然有了N11,N01,在根据程序中其他的数据结构很容易能够得到主流定义模式下的contingency table。

下面开始给出实现代码(如果程序中的一些函数的代码我没有给出,请参阅《K-means文本聚类系列(已经完成)》里面的相关函数)

用到的主要数据结构:

1。词典:保存一个词在训练语料集合中的每篇文章中出现的次数   数据类型map<string,vector<pair<int,int>> >

2。contingency table(功能见上面叙述) 数据类型:map<pair<string,string>,pair<int,int> >

map的键由两个部分组成第一个string代表term, 第二个string代表类别, 值中的第一个int 是 N11,第二个int 是N01

获得contingency table的函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/************************************************************************/
/* 获得每个词的ContingencyTable 
*顶层map的键值为词的(term Text,classLabel)
内层map的键值为类别名称
pair<int,int>的第一个int表示某一类别c中含有term t的文章数目,第二个int表示该类别中不含有term t的文章数目
*/
/************************************************************************/
map<pair<string,string>,pair< int , int > >Preprocess::GetContingencyTable(map<string,vector<pair< int , int >> > &mymap, vector<string> classLabels)
{  
     clock_t  start,finish;
     double  totaltime;
     start= clock ();
      map<string,vector< int > >articleIdsEachClass=GetArticleIdinEachClass(classLabels);
      map<pair<string,string>,pair< int , int > >EntireContigencytable;
     //对于词袋子模型中的每个词
     for (map<string,vector<pair< int , int > > >::iterator it=mymap.begin();it !=mymap.end();++it)
     {   //对于每个类别
         if (it->first!= "" ||it->first!= " " )
         {
             for (map<string,vector< int > >::iterator it1=articleIdsEachClass.begin();it1!=articleIdsEachClass.end();it1++)
             {  
                 int  cntTheClass=(it1->second).size(); //该类别共有文章数目
                 int  termInTheClass=0; //该词在该类中出现的次数
                 for (vector<pair< int , int > >::iterator it2=(it->second).begin();it2!=(it->second).end();it2++)
                 {
                     termInTheClass+=count((it1->second).begin(),it1->second.end(),it2->first);
 
                 }
                 int  termAbsentInTheClass=cntTheClass-termInTheClass;
                 pair<string,string> compoundKey=make_pair(it->first,it1->first);
                 pair< int , int > valueInfo=make_pair(termInTheClass,termAbsentInTheClass);
                 EntireContigencytable[compoundKey]=valueInfo;
                 termInTheClass=0; //清空计数;
 
             }
 
         }
         
         
     }
     finish= clock ();
     totaltime=( double )(finish-start)/CLOCKS_PER_SEC;
     cout<< "建立contingencyTable的时间为" <<totaltime<<endl;
 
 
     return  EntireContigencytable;
 
 
}

由于构造contingency table 要远比 将构造好的contingency table序列化到硬盘,然后需要的时候读取到内存的时间长(我的机器上:建立contingency table 历时233.41sec,将contingency table从硬盘序列化到内存的时间为0.954 sec)所有这里给出了针对contingency table序列化和反序列化的函数

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/************************************************************************/
/* 将关联表保存到本地硬盘                                                                     */
/************************************************************************/
void  Preprocess::SaveContingencyTable(map<pair<string,string>,pair< int , int > >&contingencyTable)
{ 
     ofstream outfile( "F:\\Cluster\\contingency.dat" ,ios::binary);
     for (map<pair<string,string>, pair< int , int > >::iterator it=contingencyTable.begin();it!=contingencyTable.end();it++)
     {
         outfile<<(it->first).first<< " " <<(it->first).second<< " " <<(it->second).first<< " " <<(it->second).second<<endl;
     }
     outfile.close();
 
 
}
/************************************************************************/
/* 将关联表信息从硬盘加载到内存                                                                     */
/************************************************************************/
void  Preprocess::LoadContingencyTable(map<pair<string,string>,pair< int , int > >&contingencyTable)
{ 
     clock_t  start,finish;
     double  totaltime;
     start= clock ();
     ifstream infile( "F:\\Cluster\\contingency.dat" ,ios::binary);
     string termtext= "" ;
     string classLabel= "" ;
     int  presentNum=0; //该term 在该classLabel下的文章中出现的次数(不计算出现重数)
     int  absentNum=0; //该classLabel下的文章中不含有该term的文章数目
     while (!infile.eof())
     {
         infile>>termtext;
         infile>>classLabel;
         infile>>presentNum;
         infile>>absentNum;
         pair<string, string> compoundKey=make_pair(termtext,classLabel);
         pair< int , int > valinfo=make_pair(presentNum,absentNum);
         contingencyTable[compoundKey]=valinfo;
     }
     infile.close();
     finish= clock ();
     totaltime=( double )(finish-start)/CLOCKS_PER_SEC;
     cout<< "将contingencyTable加载到内存的时间为" <<totaltime<<endl;
 
}

 

计算chi-square值的函数:

1
2
3
4
5
6
7
8
9
/************************************************************************/
/* 计算CHI-square 值                                                */
/************************************************************************/
double  Preprocess:: CalChiSquareValue( double  N11, double  N10, double  N01, double  N00)
{
     double  chiSquare=0;
     chiSquare=(N11+N10+N01+N00)* pow ((N11*N00-N10*N01),2)/((N11+N01)*(N11+N10)*(N10+N00)*(N01+N00));
     return  chiSquare;
}

 

针对每个类别计算所有词的chi-square并按照chi-square值按从高到低排列:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
计算词袋子中的每一个词对某一类别的卡方值
/************************************************************************/
vector<pair<string, double > > Preprocess::ChiSquareFeatureSelectionForPerclass(map<string,vector<pair< int , int >> >&mymap,map<pair<string,string>,pair< int , int > > &contingencyTable,string classLabel)
{   int  N=endIndex-beginIndex+1; //总共的文章数目
     vector<string>tempvector; //词袋子中的所有词
     vector<pair<string, double > > chisquareInfo;
     for (map<string,vector<pair< int , int >>>::iterator it=mymap.begin();it!=mymap.end();++it)
     {
         tempvector.push_back(it->first);
     }
     //计算卡方值
     for (vector<string>::iterator ittmp=tempvector.begin();ittmp!=tempvector.end();ittmp++)
     {
         int  N1=mymap[*ittmp].size();
         pair<string,string> compoundKey=make_pair(*ittmp,classLabel);
         double  N11= double (contingencyTable[compoundKey].first);
         double  N01= double (contingencyTable[compoundKey].second);
         double  N10= double (N1-N11);
         double  N00= double (N-N1-N01);
         double  chiValue=CalChiSquareValue(N11,N10,N01,N00);
         chisquareInfo.push_back(make_pair(*ittmp,chiValue));
 
         
 
     }
     //按照卡方值从大到小将这些词排列起来
     stable_sort(chisquareInfo.begin(),chisquareInfo.end(),isLarger);
     /*ofstream outfile("F:\\Cluster\\other.dat");
     int finalKeyWordsCount=0;
     for(vector<pair<string,double> >::size_type j=0;j<chisquareInfo.size();j++)
     {
         outfile<<chisquareInfo[j].first<<";"<<chisquareInfo[j].second<<endl;
         finalKeyWordsCount++;
     }
     outfile.close();*/
 
 
     return  chisquareInfo;
 
 
}

针对整个分类问题的chi-square特征词选择法。在本例中,共有三个类别

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/************************************************************************/
/* 卡方特征词选择算法                                                                     */
/************************************************************************/
void  Preprocess::ChiSquareFeatureSelection(map<string,vector<pair< int , int >> > &mymap,map<pair<string,string>,pair< int , int > > &contingencyTable, int  N)
{
     clock_t  start,finish;
     double  totaltime;
     start= clock ();
     int  N1=18693;
     int  N2=23822;
     int  N3=15717;
     int  threshold1=N1*N/(N1+N2+N3);
     int  threshold2=N2*N/(N1+N2+N3);
     int  threshold3=N3*N/(N1+N2+N3);
     string classlabel1= "xxxx" ;
     string classlabel2= "yyyy" ;
     string classlabel3= "zzzz" ;
     vector<string> classLabels;
     classLabels.push_back( "xxxx" );
     classLabels.push_back( "yyyy" );
     classLabels.push_back( "zzzz" );
     vector<pair<string, double >>chisquareInfo1;
     vector<pair<string, double >>chisquareInfo2;
     vector<pair<string, double >>chisquareInfo3;
     chisquareInfo1=ChiSquareFeatureSelectionForPerclass(mymap,contingencyTable,classlabel1);
     chisquareInfo2=ChiSquareFeatureSelectionForPerclass(mymap,contingencyTable,classlabel2);
     chisquareInfo3=ChiSquareFeatureSelectionForPerclass(mymap,contingencyTable,classlabel3);
     
     //stable_sort(chisquareInfo2.begin(),chisquareInfo2.end(),isLarger);
     //stable_sort(chisquareInfo3.begin(),chisquareInfo3.end(),isLarger);
     cout<< "finish ChiSquare Calculation" <<endl;
     set<string>finalKeywords;
     for (vector<pair<string, double > >::size_type j=0;j<threshold1;j++)
     {
         finalKeywords.insert(chisquareInfo1[j].first);
 
     }
     for (vector<pair<string, double > >::size_type j=0;j<threshold2;j++)
     {
         finalKeywords.insert(chisquareInfo2[j].first);
     }
     for (vector<pair<string, double > >::size_type j=0;j<threshold2;j++)
     {
         finalKeywords.insert(chisquareInfo3[j].first);
     }
     ofstream outfile(featurewordsAddress);
     int  finalKeyWordsCount=finalKeywords.size();
     for  (set<string>::iterator it=finalKeywords.begin();it!=finalKeywords.end();it++)
     {
         outfile<<*it<<endl;
         
     }
     outfile.close();
     cout<< "最后共选择特征词" <<finalKeyWordsCount<<endl;
     finish= clock ();
     totaltime=( double )(finish-start)/CLOCKS_PER_SEC;
     cout<< "遴选特征词共有了" <<totaltime<<endl;
     
     
 
 
 
}
C++实现Chi-square 特征词选择 在文本分类问题中,离不开特征词选择模块。特征选择是特征降维的关键步骤。本文介绍了C++实现Chi-square 特征词选择方法。 立即下载

相关推荐

java通过括特征选取、特征降维、分类模型学习三个步骤完成自动智能分类

THUCTC(THU Chinese Text Classification)是由清华大学自然语言处理实验室推出的中文文本分类工具包,能够自动高效地实现用户自定义的文本分类语料的训练、评测、分类功能。文本分类通常包括特征选取、特征降维、分类模型学习三个步骤。如何选取合适的文本特征并进行降维,是中文文本分类的挑战性问题。我组根据多年在中文文本分类的研究经验,在THUCTC中选取二字串bigram作为特征单元,特征降维方法为Chi-square,权重计算方法为tfidf,分类模型使用的是LibSVM或LibLinear。THUCTC对于开放领域的长文本具有良好的普适性,不依赖于任何中文分词工具的性能,具有准确率高、测试速度快的优点。 开源协议: THUCTC面向国内外大学、研究所、企业以及个人研究者免费开放源。 如有机构或个人拟将THUCTC用于商业目的,请发邮件至thunlp@gmail.com洽谈技术许可协议。 欢迎对该工具包的任何宝贵意见和建议,请发邮件至thunlp@gmail.com。 如果您在THUCTC基础上发表论文或取得科研成果,请您在发表论文和申报成果时声明“使用了清华大学THUCTC”,并按如下格式引用:

菜鸟进阶:C++实现Chi-square 特征词选择算法

  作者:finallyliuyu(转载请标明原作者与出处) 在文本分类问题中,离不开特征词选择模块。特征选择是特征降维的关键步骤。 首先我们给出一般性的特征词选择模块的伪代码描述: (此图摘自 C.D. Maning Introduction to InformationRetrieval 原版p251页 或者王斌译版p188页) 此处仅赘述两点,其他还劳请读者自己去看书 1...

weixin_34221775的博客 222

chi2算法源程序

chi2算法源代码,非常实用,可以直接运行,可操作性强

人工智能之机器学习常见算法

人工智能之机器学习常见算法

qq_45290171的博客 116

M系列芯片MacBook上UTM虚拟机部署达梦DM8的避坑指南

本文详细介绍了在M系列芯片MacBook上使用UTM虚拟机部署达梦数据库DM8的完整流程与避坑指南。针对ARM架构环境,重点解决了虚拟机选择、麒麟系统安装、系统调优及DM8命令行安装中的常见问题,为开发者提供了稳定可靠的国产数据库本地测试方案。

weixin_28455801的博客 456

Spring Authorization Server实战:从零搭建OAuth2.1授权中心(含数据库改造)

本文详细介绍了如何从零开始使用Spring Authorization Server搭建符合OAuth2.1规范的授权中心,并完成关键的数据库持久化改造。内容涵盖微服务架构下的统一认证需求、基础配置、数据库表设计、高级特性(如令牌自定义、性能优化)以及与现有系统(如SSO、Gateway网关)的集成实战,为构建生产级授权服务提供完整指南。

weixin_29315091的博客 254

C++中的函数

1、C++内联函数 内联函数是C++为提高运行速度所做的一项改进。内联函数在函数声明前加上关键字inline,在函数定义前加上关键字inline。 1.1 内联函数与宏 inline工具是C++新增的特性。C语言使用预处理器语句#define来提供宏——内联代码的原始实现。 定义一个宏:#define SQUARE(X) X*X 这并不是通过传递参数实现的,而是通过文本替换来实现的——X是“参数”的符号标记。 a=SQUARE(5.0); 替换成 a=5.0*5.0; b=SQUAR...

qq_41455814的博客 369

告别单一查询!MultiQueryRetriever在LangChain中的高级用法解析

本文深入解析了LangChain中的MultiQueryRetriever高级用法,该工具通过大语言模型自动生成多样化查询,显著提升文档检索的召回率和准确性。文章详细介绍了其核心机制、高级配置调优策略以及在多语言和专业领域中的实际应用,为开发者提供了优化知识库问答系统的实用方案。

weixin_28730927的博客 271

C/C++数方格(square)

C/C++数方格(square) 在比赛中,经常会有(放水题),今天,我正好碰上了T1难度的水题! 先看题目: 题目描述 中山市要新建一个广场,为了美观,要求完全是正方形。目前正在规划当中,正方形的大小和位置都在热烈的讨论之中。假设将可用于造广场的区域看成一个矩形,由11的单位正方形构成。如下图:这是一个46的矩形区域。 广场要求必须在这个矩形范围内,广场边线不能跨过任意一个单位正方形内部,只能...

Tudou_Pika的博客 4204

DC-DC电源芯片SY8303电路设计

SY8303高效率同步降压DC-DC转换器。这款芯片特别适用于需要较大负载电流(高达3A)的应用。SY8303在较宽的输入电压范围(4.5V至40V)内工作,能够将输入电能高效地转换为输出电能。此外,为使运行更为稳定,SY8303集成了主要的开关和同步开关,其导通电阻(RDS(ON))非常低,可以最大限度地减少导通损耗。一些特性,如短路保护、热关断以及自动恢复等,也有助于增强其可靠性和耐用性。

LuDvei的博客 9677

MFC Windows 程序设计[122]之树形下拉列表框(附源码)

MFC是微软公司提供的一个类库(class libraries),用以减少应用程序开发人员的工作量。其中包含大量Windows句柄封装类和很多Windows的内建控件和组件的封装类。有很多初学MFC的小伙伴们都觉得MFC比较难学,看书吧,看了就忘了,网上的一些教程又是写的含糊不清,故而学习起来很吃力...... 故此,本专栏亲自研究,实践,由易到难,层层深入,将调试过程中所遭所遇进行详细讲解,注意事项进行一一列举,希望能够帮助到各位初学MFC的小伙伴,避免走弯路,费时费力。.........

hnjzfwy的博客 459

针对特征词选择法的验证实验“各种特征词选择算法对文本分类性能的影响”:纸上得来终觉浅,觉知此事要躬行...

 (注:博文转载请注明作者和出处 作者:finallyliuyu 出处:博客园)  本博文旨在通过实践验证各种特征词选择算法对文本分类性能的影响。 根据Yi ming yang 1999年的论文《A comparision of feature selection algorithms in Text Categorization》中的论断: DF,IG,CHI-square法性能差不多,po...

weixin_33910385的博客 422

【GameFramework框架】三、快速启动

这篇文章就带领大家如何快速启动GameFramework框架。

优快云博客专家,Unity3D高级软件工程师,《Unity 3D从入门到实战》作者。 4427

卡方检验(Chi square statistic)

卡方检验是一种检验两个变量独立性的方法。本文将介绍其理论并给出其应用在LBP特征匹配中的例子。 卡方检验最基本的思想就是通过观察实际值与理论值的偏差来确定理论的正确与否。具体做的时候常常先假设两个变量确实是独立的(行话就叫做“原假设”),然后观察实际值(也可以叫做观察值)与理论值(这个理论值是指“如果两者确实独立”的情况下应该有的值)的偏差程度,如果偏差足够小,我们就认为误差是很自然的样...

架构设计 2221

2026年全国青少年信息素养大赛算法应用主题赛(C++赛项复赛模拟卷1:文末附答案)

2026年全国青少年信息素养大赛算法应用主题赛(C++赛项复赛模拟卷1:文末附答案)

王老师青少年编程 1616

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

区间开方和(Square)

4∼9 的算术平方根下取整分别为 2,2,2,2,2,3和为 13。对于 100% 的数据,0≤l≤r≤10^14。输出一个整数,即算数平方根之和。

weixin_58205611的博客 552

IEM模型,地表粗糙度模拟

利用微波反演土壤水分时候,利用IEM模型可以实现对随机地表的模拟

特征选择方法之CHI、IG、TF-IDF

1)TF-IDF在特征选择时的误区。 TF-IDF(term frequency–inverse document frequency)是一种用于信息检索与数据挖掘的常用加权技术。TF意思是词频(Term Frequency),IDF意思是逆文本频率指数(Inverse Document Frequency)。TF-IDF是一种统计方法,用以评估一字词对于一个文件集或一个语料库中的其中一份文件的...

时光、疏离了记忆づ童话的博客 2754

锂电池充电器电路设计 里面有电路

锂电池充电器电路设计 里面有电路 3.7V升压到5V电路设计。

温度PID控制PLC程序

温度PID稳定控制程序,适用于欧姆龙PLC,对其他PLC也具有很大参考价值

C++常用特性

C++常用新特性,持续更新…… 1. std::for_each、std::mem_fn #include &amp;amp;amp;amp;amp;amp;amp;amp;lt;algorithm&amp;amp;amp;amp;amp;amp;amp;amp;gt; // std::for_each #include &amp;amp;amp;amp;amp;amp;amp;amp;lt;functional&amp;amp;amp;amp;amp;amp;amp;

liugan528的博客 579

卡方分布

以上讲了一种称为服从正态分布的概率密度函数。今天,将一将

zhanghongxian123的专栏 3万+

从文本分类问题中的特征词选择算法追踪如何将数学知识,数学理论迁移到实际工程中去...

博文转载请注明作者和出处(作者:finallyliuyu :出处博客园) 附:《卡方特征词选择算法》   《DF特征词选择算法》 一.数学背景 将数学知识、数学理论以及数学思想迁移到实际工程问题中,经常会促进工程问题的圆满解决。 可是如何将数学知识引入工程问题中呢?首先需要有“数学思维”例如理解数学公式所刻画的内涵;其次需要有“建模”能力:从不同的视角来看待同一个问题,最后抽象出的数学模...

weixin_34290390的博客 109
上一篇: C++Vector用法
下一篇: 支持向量机(SVM)基础
cucmakeit
博客等级 码龄14年 30粉丝 11原创
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值