scipy
In [2]:
import numpy as np
import matplotlib.pyplot as plt
from scipy import optimize
In [3]:
x = np.linspace(0,10, 21)
x
Out[3]:
array([ 0. , 0.5, 1. , 1.5, 2. , 2.5, 3. , 3.5, 4. , 4.5, 5. , 5.5, 6. , 6.5, 7. , 7.5, 8. , 8.5, 9. , 9.5, 10. ])
In [4]:
y = 3*x+4
y
Out[4]:
array([ 4. , 5.5, 7. , 8.5, 10. , 11.5, 13. , 14.5, 16. , 17.5, 19. , 20.5, 22. , 23.5, 25. , 26.5, 28. , 29.5, 31. , 32.5, 34. ])
In [5]:
fig = plt.figure()
plt.scatter(x,y)
plt.plot(x,y)
Out[5]:
[<matplotlib.lines.Line2D at 0x244c6135cd0>]
In [6]:
y1 = np.random.uniform(low=-1, high=1, size=y.shape)*3
y1 = y1 +y
y1
Out[6]:
array([ 6.98245789, 6.39828999, 7.42999128, 10.67198849, 10.12670086, 8.87342056, 11.38121752, 14.23830957, 14.95388992, 18.95111325, 19.13128516, 19.59811703, 21.30199945, 21.37804087, 23.53440182, 25.56723397, 29.02377325, 28.20930885, 29.07300015, 33.53222 , 31.74146698])
In [7]:
plt.scatter(x,y1)
Out[7]:
<matplotlib.collections.PathCollection at 0x244c6248610>
In [8]:
p, cov = optimize.curve_fit(lambda x, m, l: x*m+l, x, y)
print(p, cov)
[3. 4.] [[ 0. -0.] [-0. 0.]]
In [9]:
p, cov = optimize.curve_fit(lambda x, m, l: x*m+l, x, y1)
print(p, cov)
[2.77383748 4.80215674] [[ 0.01004133 -0.05020664] [-0.05020664 0.34307871]]
In [10]:
y_fit = x*p[0] + p[1]
plt.figure(1, figsize=(5,5))
plt.scatter(x,y1, color="teal")
plt.plot(x,y_fit, color='orange' )
Out[10]:
[<matplotlib.lines.Line2D at 0x244c695e5b0>]
In [18]:
y_fit = x*p[0] + p[1]
fig ,ax= plt.subplots( figsize=(5,10))
plt.title("Linear regression", fontsize=25)
plt.scatter(x,y1, color="teal", s=30,label = 'Input values')
plt.plot(x,y_fit, color='orange',linewidth=1, label = 'Curve fit' )
plt.legend(loc = 'upper left')
plt.xlabel('values x', fontsize=18)
plt.ylabel('values y', fontsize=18)
ax.set_aspect('equal')
plt.grid(axis='y', color='lightgrey')
plt.grid(axis='x', color='lightgrey')
#ax.set_xlim(0,35)
# ax.set_yticks(np.arange(0,37, 2))
# ax.set_xticks(np.arange(0,12, 2))
# ax.set_ylim(0,35)
plt.savefig( 'Exemplo_reg_lin' + '.png', format ='png', bbox_inches='tight')