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.00000000e-01, 9.36000000e+00, 5.20000000e+01,
1.91000000e+02, 3.52000000e+02, 5.71000000e+02,
9.12000000e+02, 1.20700000e+03, 1.68269000e+03,
2.13500000e+03, 2.68400000e+03])
plt. scatter( years, sales, c= 'red' , marker= '*' , s= 80 )
<matplotlib.collections.PathCollection at 0x23114df3a58>
X = ( years- 2008 ) . reshape( - 1 , 1 )
X
array([[ 1],
[ 2],
[ 3],
[ 4],
[ 5],
[ 6],
[ 7],
[ 8],
[ 9],
[10],
[11]])
y = sales
y
array([ 5.00000000e-01, 9.36000000e+00, 5.20000000e+01,
1.91000000e+02, 3.52000000e+02, 5.71000000e+02,
9.12000000e+02, 1.20700000e+03, 1.68269000e+03,
2.13500000e+03, 2.68400000e+03])
from sklearn. linear_model import LinearRegression
lr = LinearRegression( fit_intercept= True )
lr. fit( X, y)
w = lr. coef_
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' )
array([ 267.31027273])
-713.26618181818299
[<matplotlib.lines.Line2D at 0x231177ae400>]
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.215582750582751
-95.276720279720209
72.338969696969116
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