时间:2024/2/17来源:本站原创作者:佚名
免费多视频网站vip会员账号 http://m.360xh.com/202109/23/66346.html
今天,我给大家带来C#与人工智能的第4讲——创建朴素贝叶斯分类器。#人工智能#本文先实现一个简单的贝叶斯分类器,输入二进制,判断0-7。后续文章会讲述它的高级应用——贝叶斯推理机。C#与人工智能(第3讲)创建神经网络C#与人工智能(第2讲)创建WinForm程序C#与人工智能(第1讲)安装C#编程环境托马斯·贝叶斯是18世纪英国数学家,概率论、贝叶斯统计的创立者。贝叶斯方法基于贝叶斯原理,对样本数据集进行分类。它综合了先验概率、后验概率,避免仅用先验概率产生的主观偏见。朴素贝叶斯分类器首先,按第1讲所述,安装VisualStudio编码工具。然后,按第2讲所述,创建一个WindowsForm应用程序。然后,按第3讲所述,下载安装Accord插件。准备好工具后,编写如下代码:usingAccord.MachineLearning.Bayes;usingAccord.Statistics.Filters;usingSystem;usingSystem.Data;usingSystem.Windows.Forms;namespaceWindowsFormsApp3{publicpartialclassForm1:Form{publicForm1(){InitializeComponent();}privatevoidAdd(DataTabledata,string参数1,string参数2,string参数3,string结果){//新增一条记录DataRowdr=data.NewRow();//向字段赋值dr[参数1]=参数1;dr[参数2]=参数2;dr[参数3]=参数3;dr[结果]=结果;//把新记录加到表里data.Rows.Add(dr);}privatevoidbutton1_Click(objectsender,EventArgse){//创建一个DataTable实例。它就是一张数据表,但不用接入任何数据库,直接在内存里使用!DataTabledata=newDataTable(二进制运算);//创建参数1字段,字符串类型data.Columns.Add(参数1,typeof(string));//创建参数2字段,字符串类型data.Columns.Add(参数2,typeof(string));//创建参数3字段,字符串类型data.Columns.Add(参数3,typeof(string));//创建结果字段,字符串类型data.Columns.Add(结果,typeof(string));//通过Add()方法,插入8条记录,对应着二进制0-7,完成样本库的构建Add(data,0,0,0,0);Add(data,0,0,1,1);Add(data,0,1,0,2);Add(data,0,1,1,3);Add(data,1,0,0,4);Add(data,1,0,1,5);Add(data,1,1,0,6);Add(data,1,1,1,7);//对DataTable样本库进行编码Codificationcodebook=newCodification(data,参数1,参数2,参数3,结果);DataTablesymbols=codebook.Apply(data);int[][]inputData=newint[8][];//输入的样本for(intr=0;rsymbols.Rows.Count;r++){DataRowdr=symbols.Rows[r];inputData[r]=newint[3];inputData[r][0]=Convert.ToInt32(dr[0]);inputData[r][1]=Convert.ToInt32(dr[1]);inputData[r][2]=Convert.ToInt32(dr[2]);}int[]outputData=newint[8];//对应的输出for(intr=0;rsymbols.Rows.Count;r++){DataRowdr=symbols.Rows[r];outputData[r]=Convert.ToInt32(dr[3]);}//创建朴素贝叶斯分类器NaiveBayesLearninglearner=newNaiveBayesLearning();//对样本库进行学习NaiveBayesnb=learner.Learn(inputData,outputData);//创建一个新样本(假设它是不在样本库里的陌生样本)int[]instance=codebook.Translate(1,1,0);intc1=nb.Decide(instance);//返回分类结果(result=6)stringresult=codebook.Translate(结果,c1);//查看每种可能性的概率值double[]probs=nb.Probabilities(instance);MessageBox.Show(result);}}}朴素贝叶斯的分类结果如上图所示,probs数组列出样本库里每个样本的概率,对于输入的1、1、0来讲,分类器认为概率最大的结果是6。您可以删除“Add(data,1,1,0,6);”那行代码(注意要把inputData、outputData的数组长度从8改成7)。然后,再运行程序,分类器返回7,此时最接近的结论是1、1、1。如果喜欢,请
转载请注明原文网址:http://www.helimiaopu.com/hjpz/hjpz/13027.html
------分隔线----------------------------