Buscar..


Introducción

Ajustar una línea (u otra función) a un conjunto de puntos de datos.

Utilizando np.polyfit

Creamos un conjunto de datos que luego ajustamos con una línea recta $ f (x) = mx + c $.

npoints = 20
slope = 2
offset = 3
x = np.arange(npoints)
y = slope * x + offset + np.random.normal(size=npoints)
p = np.polyfit(x,y,1)           # Last argument is degree of polynomial

Para ver lo que hemos hecho:

import matplotlib.pyplot as plt
f = np.poly1d(p)                # So we can call f(x)
fig = plt.figure()
ax  = fig.add_subplot(111)
plt.plot(x, y, 'bo', label="Data")
plt.plot(x,f(x), 'b-',label="Polyfit")
plt.show()

Nota: este ejemplo sigue la documentación numpy en https://docs.scipy.org/doc/numpy/reference/generated/numpy.polyfit.html muy de cerca.

Usando np.linalg.lstsq

Usamos el mismo conjunto de datos que con polyfit:

npoints = 20
slope = 2
offset = 3
x = np.arange(npoints)
y = slope * x + offset + np.random.normal(size=npoints)

Ahora, intentamos encontrar una solución minimizando el sistema de ecuaciones lineales A b = c minimizando | cA b | ** 2

import matplotlib.pyplot as plt # So we can plot the resulting fit
A = np.vstack([x,np.ones(npoints)]).T
m, c = np.linalg.lstsq(A, y)[0] # Don't care about residuals right now
fig = plt.figure()
ax  = fig.add_subplot(111)
plt.plot(x, y, 'bo', label="Data")
plt.plot(x, m*x+c, 'r--',label="Least Squares")
plt.show()

Nota: este ejemplo sigue la documentación numpy en https://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.lstsq.html muy de cerca.



Modified text is an extract of the original Stack Overflow Documentation
Licenciado bajo CC BY-SA 3.0
No afiliado a Stack Overflow