📄 识别练习.cpp
字号:
#include <stdio.h>
#include <iostream.h>
#include <iomanip.h>
#include <math.h>
#include"stdlib.h"
//定义PI的大小
#define pi 3.1415926
double AverageRandom(double min,double max);
double Normal(double x,double mean,double variance);
void NormalRandom(double mean, double variance,double min,double max,int number,double* sample);
void Estimate(double* mean,double* variance,double* sample,int number);
void Distinguish(double x,double mean_1,double variance_1,double mean_2,double variance_2);
void main()
{
double sample_1[200];//训练样本1
double sample_2[200];//训练样本2
double mean_1;//样本1的均值
double variance_1;//样本1的方差
double mean_2;//样本2的均值
double variance_2;//样本2的方差
cout<<"样本数据:\n";
NormalRandom(72,25,62,82,200,sample_1);//用于产生200个均值为72,方差为25的样本放于sample_1中
NormalRandom(184,36,172,196,200,sample_2);//用于产生200个均值为184,方差为36的样本放于sample_2中
Estimate(& mean_1,& variance_1,& sample_1[0],200);//用于估计样本1的均值与方差
Estimate(& mean_2,& variance_2,& sample_2[0],200);//用于估计样本2的均值与方差
cout<<"两类的均值和方差的估计值分别为:\n";
cout<<setw(10)<<mean_1<<setw(10)<<variance_1<<endl;//输出样本1的均值与方差
cout<<setw(10)<<mean_2<<setw(10)<<variance_2<<endl;//输出样本2的均值与方差
double x=1;
while(x!=NULL)
{
cout<<"请输入待识别数x:\n";
cin>>x;
cout<<"x="<<x<<endl;
Distinguish(x,mean_1,variance_1,mean_2,variance_2);//调用分类器函数判别属于哪一类
}
}
double AverageRandom(double min,double max)
{
long minInteger = (int)(min*10000);
long maxInteger = (int)(max*10000);
long randInteger = rand()*rand();
long diffInteger = maxInteger - minInteger;
long resultInteger = randInteger % diffInteger + minInteger;
return resultInteger/10000.0;
}
double Normal(double x,double mean,double variance)
{
return 1.0/sqrt(2*pi*variance) * exp(-1*(x-mean)*(x-mean)/(2*variance));
}
//用于产生测试序列放在SAMPLE数组中
void NormalRandom(double mean, double variance,double min,double max,int number,double* sample)
{
for (int i=0;i<number;i++)
{
double x;
double dScope;
double y;
do
{
x = AverageRandom(min,max);
y = Normal(x, mean, variance);
dScope = AverageRandom(0, Normal(mean,mean,variance));
}while( dScope > y);
sample[i]=x;
cout<<x<<endl;
}
}
//用于估计样本的均值和方差
void Estimate(double* mean,double* variance,double* sample,int number)
{
*mean=0;
*variance=0;
for (int i=0;i<number;i++)
{
*mean=*mean+1.0/number*sample[i];
}
for (int j=0;j<number;j++)
{
*variance=*variance+1.0/number*(sample[j]-*mean)*(sample[j]-*mean);
}
}
//分类器函数
void Distinguish(double x,double mean_1,double variance_1,double mean_2,double variance_2)
{
double P_w1,P_w2,P_x_w1,P_x_w2,P_w1_x;
P_w1=0.4;//先验概率
P_w2=0.6;//先验概率
P_x_w1=Normal(x,mean_1,variance_1);
P_x_w2=Normal(x,mean_2,variance_2);
P_w1_x=P_x_w1*P_w1/(P_x_w1*P_w1+P_x_w2*P_w2);
if (P_w1_x>=0.5)
{
cout<<"x属于第一类\n";
}
else
{
cout<<"x属于第二类\n";
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -