Java实现皮尔逊相关系数(Pearson)及T检验

目的

皮尔逊相关系数(r)可以反映两个变量之间的相关性大小,如果想要量化这种相关性,可以使用T检验。当根据r计算出的p值小于指定的显著性水平时,就可以认为这两个变量是显著相关的。

术语及定义

1、皮尔逊相关

测量两个变量间线性关系的程度和方向。

2、皮尔逊相关系数

皮尔逊相关用r表示,也称作皮尔逊相关系数。

3、决定系数

r 2 的值被称为决定系数,因为它测量了一个变量的变异中由另个一个变量的变异而决定的概率。 r^2 的值被称为决定系数,因为它测量了一个变量的变异中由另个一个变量的变异而决定的概率。 r2的值被称为决定系数,因为它测量了一个变量的变异中由另个一个变量的变异而决定的概率。

4、相关检验的自由度

皮尔逊相关的假设检验的自由度为df=n-2。因为如果一个样本中只有2个数据点,是没有自由度的,只可能是一条直线。

公式

皮尔逊相关系数r和T分数的关系为:
t = r n − 2 1 − r 2 t=r\sqrt{\frac{n-2}{1-r^2}} t=r1r2n2
其中n为样本的大小。

maven依赖

	
		net.sf.jsci
		jsci
		1.2
	
	
	
		org.apache.commons
		commons-math3
		3.6.1
	

实现代码

package com.math.statistics;

import org.apache.commons.math3.stat.correlation.PearsonsCorrelation;

import JSci.maths.statistics.TDistribution;
/***
 * 
 * @author miaoyibo
 *
 */
public class Pearson {
	
	private double[] x;

	private double[] y;
	PearsonsCorrelation p=new PearsonsCorrelation();

	public Pearson(double[] x, double[] y) {
		this.x = x;
		this.y = y;
	}
	
	public double getR() {
		
		return p.correlation(x, y);
	}
	public double getTValue() {
		double up=x.length-2;
		double r=getR();
		double down=1-(r*r);
		return r*Math.sqrt(up/down);
	}
	/***
	 * 
	 * @param flag:true=双侧,false=单侧
	 * @return
	 */
	public double getPValue(boolean flag) {
		TDistribution td=new TDistribution(x.length-2);
		double t=getTValue();
		double cumulative = td.cumulative(t);
		double p=t>0?1-cumulative:cumulative;
		return flag?p*2:p;
	}
}


DEMO

public static void main(String[] args) {
		double[] d1= {0,10,4,8,8};
		double[] d2= {2,6,2,4,6};
		Pearson p=new Pearson(d1,d2);
		System.out.println(p.getPValue(true));
	}


}

参考资料

https://en.wikipedia.org/wiki/Pearson_correlation_coefficient#Testing_using_Student.27s_t-distribution

https://stats.stackexchange.com/questions/48983/p-value-for-hypothesis-test-with-given-correlation-sample-size

你可能感兴趣的:(统计学,java,线性回归,后端,回归)