R平方值python实现

import numpy as np

from astropy.units import Ybarn

import math

def computeCorrelation(x, y):
xBar = np.mean(x)
ybar = np.mean(y)
SSR = 0
varX = 0
varY = 0
for i in range(0, len(x)): #多少实例
diffxxBar = x[i] - xBar
diffyyBar = y[i] - ybar
SSR += (diffxxBar * diffyyBar)
varX += diffxxBar ** 2 # 求平方然后累计起来
varY += diffyyBar ** 2 # 求平方然后累计起来

SST = math.sqrt(varX * varY)
return SSR / SST

def polyfit(x, y, degree):

result = {}     # 定义一个字典
coeffs = np.polyfit(x, y, degree)   # 直接求出b0 b1 b2 b3 ..的估计值
result["polynomial"] = coeffs.tolist()

p = np.poly1d(coeffs)   # 返回预测值
yhat = p(x)         # 传入x 返回预测值
ybar = np.sum(y) / len (y)  # 求均值
ssreg = np.sum((yhat -ybar)**2)
sstot = np.sum((y - ybar)**2)
result["determination"] = ssreg / sstot

return result

testX = [1, 3, 8, 7, 9]
testY = [10, 12, 24, 21, 34]

print(“r:”, computeCorrelation(testX, testY))
print(“r**2:”, (computeCorrelation(testX, testY)**2))

print(“r**2”, polyfit(testX, testY, 1)[“determination”]) # degree=1 一次
print(polyfit(testX, testY, 1)[“polynomial”]) # 打印除斜率和截距

  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值