java标准差的代码 标准差编程( 二 )


{
int count=0;
for(ArrayListDouble element:elements) //依次取labels中的所有元祖
{
if(element.get(i).equals(features[i])) //如果这个元祖的第index数据和b相等 , 那么就count就加1
count++;
}
if(count==0)
{
pro.add(1/(double)(elements.size()+1));
}
else
pro.add(count/(double)elements.size()); //统计完所有之后计算概率值 并加入
}
else
{
double Sdev;
double Mean;
double probi=1.0;
Mean=countlblPro.getMean(elements, i);
Sdev=countlblPro.getSdev(elements, i);
if(Sdev!=0)
{
probi*=((1/(Math.sqrt(2*Math.PI)*Sdev))*(Math.exp(-(features[i]-Mean)*(features[i]-Mean)/(2*Sdev*Sdev))));
pro.add(probi);
}
else
pro.add(1.5);
}
}
for(double pi:pro)
probility*=pi; //将所有概率相乘
probility*=lblProba.get(index);//最后再乘以一个 Yi
pro_.add(probility);// 放入pro_ 至此 一个循环结束,
index++;
}
double max_pro=pro_.get(0);
max_index=0;
for(int i=1;ipro_.size();i++)
{
if(pro_.get(i)=max_pro)
{
max_pro=pro_.get(i);
max_index=i;
}
}
returnlblClass.get(max_index);
}
public class CountProbility
{
boolean []isCatory;
double[][]features;
private double[]labels;
public CountProbility(boolean[] isCategory, double[][] features, double[] labels)
{
this.isCatory=isCategory;
this.features=features;
this.labels=labels;
}
//获取label中取值情况
public void getlblClass(ArrayList DoublelblClass,ArrayListIntegerlblCount,ArrayListFloatlblProba)
{
int j=0;
for(double i:labels)
{
//如果当前的label不存在于lblClass则加入
if(!lblClass.contains(i))
{
lblClass.add(j,i);
lblCount.add(j++,1);
}
else //如果label中已经存在,就将其计数加1
{
int index=lblClass.indexOf(i);
int count=lblCount.get(index);
lblCount.set(index,++count);
}
}
for(int i=0;ilblClass.size();i++)
{
//System.out.println("值为"+lblClass.get(i)+"的个数有"+lblCount.get(i)+"概率是"+lblCount.get(i)/(float)labels.length);
lblProba.add(i,lblCount.get(i)/(float)labels.length);
}
}
//将label[]和features[][]合并
public ArrayListArrayListDoubleUnionFeaLbl(double[][] features, double[] labels)
{
ArrayListArrayListDoubletraingList=newArrayListArrayListDouble();
for(int i=0;ifeatures.length;i++)
{
ArrayListDoubleelements=new ArrayListDouble();
for(int j=0;jfeatures[i].length;j++)
{
elements.add(j,features[i][j]);
}
elements.add(features[i].length,labels[i]);
traingList.add(i,elements);
}
return traingList;
}
/*将测试数组按label的值分类存储*/
public ArrayListArrayListArrayListDouble getClassListBasedLabel (ArrayList DoublelblClass,ArrayListArrayListDoubletrainingList)
{
ArrayListArrayListArrayListDouble ClassListBasedLabel=new ArrayListArrayListArrayListDouble () ;
for(double num:lblClass)
{
ArrayListArrayListDouble elements=new ArrayListArrayListDouble();
for(ArrayListDoubleelement:trainingList)
{
if(element.get(element.size()-1).equals(num))
elements.add(element);
}
ClassListBasedLabel.add(elements);
}
return ClassListBasedLabel;
}
public double getMean(ArrayListArrayListDouble elements,int index)
{
double sum=0.0;
double Mean;
for(ArrayListDouble element:elements)
{
sum+=element.get(index);
}
Mean=sum/(double)elements.size();
returnMean;
}
public double getSdev(ArrayListArrayListDouble elements,int index)
{

推荐阅读