您的位置:首页 > 编程语言 > Go语言

Coefficient of Determination(R Squared)(How to determine goodness of fit)?

2015-07-24 09:38 441 查看
# quote from 'introduction to computation and programming
# using Python, revised, MIT press
import pylab

def getTrajectoryData(fileName):
dataFile = open(fileName, 'r')
distances = []
heights1, heights2, heights3, heights4 = [], [], [], []
discardHeader = dataFile.readline()
for line in dataFile:
d, h1, h2, h3, h4 = line.split()
distances.append(float(d))
heights1.append(float(h1))
heights2.append(float(h2))
heights3.append(float(h3))
heights4.append(float(h4))
dataFile.close()
return (distances, [heights1, heights2, heights3, heights4])

def processTrajectories(fileName):
distances, heights = getTrajectoryData(fileName)
numTrials = len(heights) #heights is a 'list of lists'
distances = pylab.array(distances)
#Get array containing mean height at each distances
totHeights = pylab.array([0]*len(distances))
for h in heights:
totHeights = totHeights + pylab.array(h)
meanHeights = totHeights/len(heights)
pylab.title('Trajectory fo Projectile (Mean of '\
+ str(numTrials) + ' Trials)')
pylab.xlabel('Inches from Launch Point')
pylab.ylabel('Inches Above Launch Point')
pylab.plot(distances, meanHeights, 'bo')

#linear fit
a,b = pylab.polyfit(distances, meanHeights, 1)
altitudes = a*distances + b
pylab.plot(distances, altitudes, 'b', label = 'Linear Fit')
print 'RSquare of linear fit =', rSquared(meanHeights, altitudes)

#quadratic fit
a,b,c = pylab.polyfit(distances, meanHeights, 2)
altitudes = a*(distances**2) + b*distances + c
pylab.plot(distances, altitudes, 'b:', label = 'Quadratic Fit')
print 'RSquare of quadratic fit =', rSquared(meanHeights, altitudes)

pylab.legend()

def rSquared(measured, predicted):
"""Assumes measured a one-dimensional array of measured values
predicted a one-dimensional array of predicted values
Returns coefficient of determination"""
#square error(cost function)
estimateError = ((predicted - measured)**2).sum()
meanOfMeasured = measured.sum()/float(len(measured))
variability = ((measured - meanOfMeasured)**2).sum()
return 1 - estimateError/variability




%run "C:\Users\Administrator\test.py"

RSquare of linear fit = 0.0177433205441

RSquare of quadratic fit = 0.985765369287
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: