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
相关文章推荐
- product_category
- Golang实例001
- django 1.8 官方文档翻译: 2-4-4 编写迁移
- django 1.8 官方文档翻译: 2-3-2 关联对象参考
- 解读Django框架中的低层次缓存API
- 详解Django缓存处理中Vary头部的使用
- 简介Django中内置的一些中间件
- 将Django框架和遗留的Web应用集成的方法
- VIEWGOOD(远古)视频点播软件
- golang 静态文件服务器
- HDU 2955 Robberies (01背包)
- codeforces 560 C Gerald's Hexagon
- hdu 3635 Dragon Balls
- Codeforces Round #313 (Div. 2) C. Gerald's Hexagon
- dJANGO RESTFRAMEWORK
- django 1.8 官方文档翻译: 2-1-3 元选项 (初稿)
- CF560C Gerald's Hexagon 六边形能切成多少正三角形
- golang
- hdoj 1824 Let's go home 【2-sat 简单题目】
- MangoDB基本操作