1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| import random
import numpy as np
from scipy.optimize import fmin
import matplotlib.pyplot as plt
def linear_law(x, slope, scale):
return slope*x + scale
def evaluate(x, *args):
"""Function computing square error"""
x_data = args[0]
y_data = args[1]
y_estimated = linear_law(x_data, x[0], x[1])
return np.sum(np.square(y_data - y_estimated))
# Generate pseudo random data
slope, scale = 2.0, 10.0
x_data = np.arange(1, 100, 1)
y_data = np.array([slope*i+scale+random.randrange(-10,10) for i in x_data])
# x0 = [slope, scale]
x0 = [1., 1,]
slope_est, scale_est = fmin(evaluate, x0, args=(x_data, y_data), xtol=1e-8, disp=True)
print slope_est, scale_est
y_est = linear_law(x_data, slope_est, scale_est)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.scatter(x_data, y_data, color='red', label='Raw data')
ax.plot(x_data, y_est, color='blue', label='Fitted law')
ax.legend(loc='lower right')
plt.grid()
plt.show() |
Partager