1. 程式人生 > >marchine learning 之 皮爾遜相關係數

marchine learning 之 皮爾遜相關係數

/**皮爾遜相關係數
 *
ρ =(∑xy - ∑x∑y/n)/(∑x^2 - (∑x)^2/n)(∑y^2-(∑y)^2/n)^0.5
 */
public class PersonCorrelationCoefficient {

    public double personCoefficient(Instance a,Instance b){
        if (a.noAttributes() != b.noAttributes())
            throw new RuntimeException("兩個資料例項的屬性數目不一致");
        double xy =0;
        double
sumX = 0; double sumY = 0; double xTo = 0; double yTo =0; for (int i=0;i<a.noAttributes();i++){ xy += a.value(i) * b.value(i); sumX += a.value(i); sumY += b.value(i); xTo += a.value(i) * a.value(i); yTo += b.value
(i) * b.value(i); } int n = a.noAttributes(); return (xy - (sumX * sumY) / n) / Math.sqrt((xTo-(sumX * sumX)/n)*(yTo - (sumY * sumY) / n)); } }