代码如下;
let XGX= {
correlationCoefficient(pA, pB) {
let covXY = -pA * pB
let varX = pA * (1-pA)
let varY = (1-pB)* pB
let res = covXY / (Math.sqrt(varX*varY, 2))
return res
},
correlation(x,y){
x=[0.3,50.2,99.5,199.3,299,398];
y=[0.1,50,99.9,200,300,400];
// 计算均值
const avgX=x.reduce((a,b)=>a+b,0)/x.length;
const avgY=y.reduce((a,b)=>a+b,0)/y.length;
//计算差值
const diffX=x.map((value,index)=>value-avgX);
const diffY=y.map((value,index)=>value-avgY);
//计算乘积
const product =diffX.map((value,index)=>value*diffY[index]);
//计算相关系数
const sumProduct=product.reduce((a,b)=>a+b,0);
const correlation=sumProduct/(x.length*y.length);
return correlation
},
/**
* 计算皮尔逊相关系数
* @list1:数字列表1
* @list2:数字列表2
* @return number
* */
pearson(list1,list2){
let newList = [];
let len = list1.length;
for(let i=0;i<len;i++){newList.push(list1[i]*list2[i]);}
let mean1 = this.mean(list1),mean2=this.mean(list2);
let cov = this.mean(newList)-mean1*mean2;
return cov/(this.std(list1,mean1)*this.std(list2,mean2))
},
/**
* 计算平均值
* @list:数字列表
* @return number
* */
mean(list){
let sum = 0;
list.forEach((item)=>{sum+=item})
return sum/list.length;
},
/**
* 计算标准差
* @list:数字列表
* @mean:列表list的平均值
* @return number
* */
std(list,mean){
let sum =0;
list.forEach((item)=>{sum+=Math.pow(item-mean,2)})
return Math.sqrt(sum/list.length)
}
};
export default XGX
调用:
?效果: