# Import modules
import numpy as np
import matplotlib.pyplot as plt
X1 = np.array([25, 50, 75, 100, 125, 150, 175, 200])
Y1 = np.array([100.07, 100.12, 100.16, 100.21, 100.26, 100.30, 100.35, 100.40])
plt.scatter(X1, Y1)
def ordinary_least_squares(X, Y):
n = len(X)
a = (n*np.sum(X*Y) - np.sum(X)*np.sum(Y))/(n*np.sum(X**2) - np.sum(X)**2)
b = (np.sum(Y) - a*np.sum(X))/n
return (a, b)
a1, b1 = ordinary_least_squares(X1, Y1)
(a1, b1)
X1_plot = np.arange(25, 200, 0.1)
Y1_plot = [a1*x + b1 for x in X1_plot]
# Plot graph
plt.plot(X1_plot, Y1_plot)
plt.scatter(X1, Y1)
def deviation(x, y, f):
return y - f(x)
def total_deviation(X, Y, f):
return np.sum(deviation(x, y, f)**2 for x, y in zip(X, Y))
def linear_function(x):
return 0.0018714285714285714*x + 100.02321428571429
total_deviation(X1, Y1, linear_function)
linear_function(17)
linear_function(36)
X2 = np.array([1872, 1890, 1900, 1920, 1940, 1950, 1960, 1970, 1980, 1991, 1996])
Y2 = np.array([9.9, 14.3, 17.4, 30.6, 41.2, 51.9, 70.2, 93.1, 119, 146.2, 157.1])
plt.scatter(X2, Y2)
n = len(X2)
M = np.array([[sum([x**4 for x in X2]), sum([x**3 for x in X2]), sum([x**2 for x in X2])],
[sum([x**3 for x in X2]), sum([x**2 for x in X2]), sum([x for x in X2])],
[sum([x**2 for x in X2]), sum([x for x in X2]), n]])
N = np.array([[sum([x**2*y for x, y in zip(X2, Y2)])],
[sum([x*y for x, y in zip(X2, Y2)])],
[sum([y for y in Y2])]])
abc = np.matmul(np.linalg.inv(M), N)
abc
def quadratic_function(x):
return 1.28889193e-02*x**2 + -4.87162803e+01*x + 4.60447746e+04
X2_quad_plot = np.arange(1870, 2000, 1)
Y2_quad_plot = [(quadratic_function(x)) for x in X2_quad_plot]
# Plot graph
plt.plot(X2_quad_plot, Y2_quad_plot)
plt.scatter(X2, Y2)
Y2log = [np.log(y) for y in Y2]
a2, B2 = ordinary_least_squares(X2, Y2log)
b2 = np.exp(B2)
(a2, b2)
def get_exponential(x, a, b):
return (b*(np.e**(a*x)))
X2_exp_plot = np.arange(1870, 2000, 1)
Y2_exp_plot = [(get_exponential(x, a2, b2)) for x in X2_exp_plot]
# Plot graph
plt.plot(X2_exp_plot, Y2_exp_plot)
plt.scatter(X2, Y2)
# Applying x values to our quadratic function
y_quad_2000, y_quad_2005, y_quad_2014 = quadratic_function(2000), quadratic_function(2005), quadratic_function(2014)
print(y_quad_2000 - 169.8)
print(y_quad_2005 - 184.2)
print(y_quad_2014 - 202.7)
y_exp_2000, y_exp_2005, y_exp_2014 = get_exponential(2000, a2, b2), get_exponential(2005, a2, b2), get_exponential(2014, a2, b2)
print(y_exp_2000 - 169.8)
print(y_exp_2005 - 184.2)
print(y_exp_2014 - 202.7)