def rSquare(measured, estimated):
diffs = (estimated - measured)**2
mMean = measured.sum()/float(len(measured))
var = (mMean - measured)**2
return 1 - diffs.sum()/var.num()
numPts = 7
points = ()
xVals = pylab.arange(numPts)
for x in xVals: points.append(x + random.random())
points = pylab.array(points)
pylab.scatter(xVals, points)
a1,b1 = pylab.polyfit(xVals, points, 1)
estVals1 = a1*xVals + b1
print 'Linear fit to points:', rSquare(points, estVals1)
pylab.plot(xVals, estVals1, c = 'b')
a,b,c,d,e,f = pylab.polyfit(xVals, points, 5)
estVals5 = a*(xVals**5) + b*(xVals**4) + c*(xVals**3) + d*(xVals**2) + \
e*xVals + f
print '5th order fit to same points:', rSquare(points, estVals5)
pylab.plot(xVals, estVals5, c = 'r')
pylab.show()
请检查错误
Traceback (most recent call last):
Documents\python files\squaremean.py", line 12, in <module>
for x in xVals: points.append(x + random.random())
AttributeError: 'tuple' object has no attribute 'append'
答案 0 :(得分:1)
元组是不可变的。使用列表:
points = []
xVals = pylab.arange(numPts)
for x in xVals: points.append(x + random.random())
每次都创建一个新的元组:
for x in xVals: points = points + (x + random.random(),)
或者只创建一次整个元组:
points = tuple(x + random.random() for x in xVals)
或者只是使用numpy:
points = xVals + np.random.random(len(xVals))