c
! www.simula.no/˜hpl
AtasteofNumPy:aleast-squaresprocedure
x=linspace(0.0,1.0,n) #coordinates
y_line = -2
*
x+3
y=y_line+random.normal(0,0.25,n) #linewithnoise
#goal:fitalinetothedatapointsx,y
#createandsolveleastsquaressystem:
A=array([x,ones(n)])
A=A.transpose()
result = linalg.lstsq(A, y)
#resultisa4-tuple,thesolution(a,b)isthe1stentry:
a, b = result[0]
plot(x, y, ’o’, # data points w/noise
x, y_line, ’r’, # original line
x, a
*
x+b,’b’) #fittedlines
legend(’data points’, ’original line’, ’fitted line’)
hardcopy(’myplot.png’)
Numerical Python – p. 239/728
Comentarios a estos manuales