import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
years = np.arange(2009,2020)
years
array([2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019])
sales = np.array([0.5,9.36,52,191,352,571,912,1207,1682.69,2135,2684])
sales
array([5.00000e-01, 9.36000e+00, 5.20000e+01, 1.91000e+02, 3.52000e+02,
5.71000e+02, 9.12000e+02, 1.20700e+03, 1.68269e+03, 2.13500e+03,
2.68400e+03])
plt.scatter(years,sales,c = 'red',marker='*',s = 80)
<matplotlib.collections.PathCollection at 0x1ecdbb03da0>
X = (years - 2008).reshape(-1,1)
X
array([[ 1],
[ 2],
[ 3],
[ 4],
[ 5],
[ 6],
[ 7],
[ 8],
[ 9],
[10],
[11]])
y = sales
y
array([5.00000e-01, 9.36000e+00, 5.20000e+01, 1.91000e+02, 3.52000e+02,
5.71000e+02, 9.12000e+02, 1.20700e+03, 1.68269e+03, 2.13500e+03,
2.68400e+03])
from sklearn.linear_model import LinearRegression
lr = LinearRegression(fit_intercept=True)
lr.fit(X,y)
w = lr.coef_[0]
b = lr.intercept_
display(w,b)
plt.scatter(years -2008,sales,c = 'red',marker='*',s = 80)
x = np.linspace(1,12,50)
plt.plot(x,w*x + b,c = 'green')
267.3102727272729
-713.266181818183
[<matplotlib.lines.Line2D at 0x1ecec259fd0>]
X2 = np.concatenate([X**2,X],axis= 1)
X2.shape
(11, 2)
lr = LinearRegression(fit_intercept=True)
X2 = np.concatenate([X**2,X],axis= 1)
lr.fit(X2,y)
w1,w2 = lr.coef_
b = lr.intercept_
display(w1,w2,b)
plt.scatter(years -2008,sales,c = 'red',marker='*',s = 80)
x = np.linspace(1,12,50)
f = lambda x :w1*x**2 + w2*x + b
plt.plot(x,f(x),c = 'green')
print('2020年天貓雙十一銷量預測:',np.round(f(12),1))
30.21558275058275
-95.27672027972024
72.33896969696934
2020年天貓雙十一銷量預測: 3280.1
lr = LinearRegression(fit_intercept=True)
X3 = np.concatenate([X**3,X**2,X],axis= 1)
lr.fit(X3,y)
w1,w2,w3 = lr.coef_
b = lr.intercept_
plt.scatter(years -2008,sales,c = 'red',marker='*',s = 80)
x = np.linspace(1,12,50)
f = lambda x :w1*x**3 + w2*x**2 + w3*x + b
plt.plot(x,f(x),c = 'green')
print('2020年天貓雙十一銷量預測:',np.round(f(12),1))
2020年天貓雙十一銷量預測: 3294.2