gpt4 book ai didi

python - 试图做一个相关系数,但返回高得离谱的值

转载 作者:太空宇宙 更新时间:2023-11-04 01:47:05 26 4
gpt4 key购买 nike

所以在我开始之前,这里是代码:

from math import sqrt

def Summation(valueList):
outValue = 0
for item in valueList:
outValue += item
return outValue
def multSummation(vOne, vTwo):
outValue = 0
for item in range(0, len(vOne)):
outValue += vOne[item] * vTwo[item]
return outValue
def Correlator(xList=[],yList=[]):
#r = n(Exy)-(Ex)(Ey) / sqrt([nEx^2-(Ex)^2][nEy^2-(Ey)^2])#God help me

r = (len(xList) * multSummation(xList,yList)) - (Summation(xList) * Summation(yList)) / (sqrt((len(xList) * (multSummation(xList,xList)) - (multSummation(xList,xList) * multSummation(xList,xList))) * ((len(xList) * multSummation(yList,yList)) - (multSummation(yList,yList) * multSummation(yList,yList)))))
return r

valOne = {1950:5,1955:9,1960:8,1965:3,1970:6,1975:7,1980:6}
valTwo = {1950:2,1956:5,1960:4,1965:1,1968:2,1975:3,1980:3}
matchingKeysList = []
for x in valOne.keys():
for y in valTwo.keys():
if x == y:
matchingKeysList.append(x)
valOneCleaned = {}
valTwoCleaned = {}
for x in valOne:
if x in matchingKeysList:
valOneCleaned[x] = valOne[x]
for y in valTwo:
if y in matchingKeysList:
valTwoCleaned[y] = valTwo[y]

valOneList = []
valTwoList = []
for x in valOneCleaned:
valOneList.append(valOneCleaned[x])
for y in valTwoCleaned:
valTwoList.append(valTwoCleaned[y])


#MAIN LOOP HERE
print(valOneList)
print(valTwoList)
print(Correlator(valOneList, valTwoList))

这不是大学项目。它基本上需要两个字典,valOne 和 valTwo 并清理数据,因此只有两者之间的匹配年份。完成此操作后,它会获取值并将它们放入列表中,然后将其提供给相关函数,该函数接收两个列表并计算两者之间的相关系数。该值应该在 -1 和 1 之间,但它最终给我的数字高得离谱,比如 419.9。请帮助我可怜的未受过教育的大脑。

最佳答案

相关公式中的括号不正确。在您的代码中,实际上只有一部分分子除以分母。此外,分母的公式不太正确。试试这个:

r = ((len(xList) * multSummation(xList,yList)) - (Summation(xList) * Summation(yList))) / (sqrt((len(xList) * (multSummation(xList,xList)) - (Summation(xList) * Summation(xList))) * ((len(xList) * multSummation(yList,yList)) - (Summation(yList) * Summation(yList)))))

使用多行重写等式会更容易阅读和调试。除了使用 Summation 函数,您还可以使用内置的 sum

n = len(xList)
Ex = sum(xList)
Ey = sum(yList)
Exx = multSummation(xList,xList)
Exy = multSummation(xList,yList)
Eyy = multSummation(yList,yList)
numerator = n * Exy - Ex * Ey
denominator = sqrt(n * Exx - Ex * Ex) * sqrt(n * Eyy - Ey * Ey)
r = numerator / denominator

关于python - 试图做一个相关系数,但返回高得离谱的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58863816/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com