You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
42 lines
1.4 KiB
Python
42 lines
1.4 KiB
Python
11 years ago
|
#!/usr/bin/python2.7
|
||
|
from __future__ import division, print_function
|
||
11 years ago
|
from sympy import Symbol, diff, solve, lambdify, simplify
|
||
11 years ago
|
import matplotlib.pyplot as plt
|
||
|
import numpy as np
|
||
|
|
||
|
# Model parameters: We look for a line y = b1*x + b2.
|
||
|
b1 = Symbol('b1')
|
||
|
b2 = Symbol('b2')
|
||
|
|
||
|
# Data points
|
||
11 years ago
|
data = [(1, 14), (2, 13), (3, 12), (4, 10), (5, 9), (7, 8), (9, 5)]
|
||
11 years ago
|
|
||
|
# S is the function to minimize:
|
||
|
#
|
||
|
# For each data point the vertical error/residual is x*b1 + b2 - y. We want to
|
||
|
# minimize the sum of the squared residuals (least squares).
|
||
11 years ago
|
S = sum((p[0] * b1 + b2 - p[1]) ** 2 for p in data)
|
||
11 years ago
|
S = simplify(S)
|
||
11 years ago
|
print("Function to minimize: S = {}".format(S))
|
||
11 years ago
|
|
||
|
# Minimize S by setting its partial derivatives to zero.
|
||
|
d1 = diff(S, b1)
|
||
|
d2 = diff(S, b2)
|
||
|
solutions = solve([d1, d2], [b1, b2])
|
||
11 years ago
|
print("S is minimal for b1 = {}, b2 = {}".format(solutions[b1], solutions[b2]))
|
||
11 years ago
|
|
||
|
# Construct fitted line from the solutions
|
||
|
x = Symbol('x')
|
||
|
fitted_line = solutions[b1] * x + solutions[b2]
|
||
11 years ago
|
print("Fitted line: y = {}".format(fitted_line))
|
||
11 years ago
|
|
||
|
# Construct something we can plot with matplotlib
|
||
|
fitted_line_func = lambdify(x, fitted_line, modules=['numpy'])
|
||
11 years ago
|
x_plot = np.linspace(min(p[0] for p in data),
|
||
|
max(p[0] for p in data), 100)
|
||
11 years ago
|
|
||
|
# Plot data points and fitted line
|
||
11 years ago
|
plt.scatter([p[0] for p in data], [p[1] for p in data], marker="+")
|
||
11 years ago
|
plt.plot(x_plot, fitted_line_func(x_plot), 'r')
|
||
|
plt.show()
|