2014-01-06 53 views
0

你好嗎?我想編寫程序,但它給我帶有屬性的錯誤。我是新的python和幫助將不勝感激。 進口pylab,隨機Pylab和隨機屬性錯誤

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' 

回答

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))