預測2020年天貓雙十一銷量 線性迴歸

# 認爲天貓銷量和年份之間存在函數關係 一元二次,一元三次
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)
# weight 權重
w = lr.coef_[0]
# bias 偏差
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)
# 假定函數是一元二次f(x) = w1*x**2 + w2*x + b

lr = LinearRegression(fit_intercept=True)

X2 = np.concatenate([X**2,X],axis= 1)

lr.fit(X2,y)
# weight 權重
w1,w2 = lr.coef_
# bias 偏差
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')

# 2009 -----1
# 2010 -----2
# 2020 -----12
print('2020年天貓雙十一銷量預測:',np.round(f(12),1))
30.21558275058275



-95.27672027972024



72.33896969696934


2020年天貓雙十一銷量預測: 3280.1

在這裏插入圖片描述

# 假定函數是一元二次f(x) = w1*x**2 + w2*x + b

lr = LinearRegression(fit_intercept=True)

X3 = np.concatenate([X**3,X**2,X],axis= 1)

lr.fit(X3,y)
# weight 權重
w1,w2,w3 = lr.coef_
# bias 偏差
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')

# 2009 -----1
# 2010 -----2
# 2020 -----12
print('2020年天貓雙十一銷量預測:',np.round(f(12),1))
2020年天貓雙十一銷量預測: 3294.2

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章