生活随笔
收集整理的這篇文章主要介紹了
python分析双十一销量
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
python分析雙十一銷量
import numpy
as np
import matplotlib
.pyplot
as pltyear
= np
.array
([year
for year
in range(2009,2021)])
sales
= np
.array
([0.5, 9.36, 52, 191, 352, 571, 912, 1207, 1682.69, 2135, 2684, 4982])plt
.plot
(year
, sales
, 'ro')z
= np
.polyfit
(year
, sales
, 1)
z
[0]
z
[1]
yhat
= z
[0]* year
+ z
[1]plt
.plot
(year
, yhat
, 'g-')plt
.text
(2010, 3000, "y={:0.2f}*year{:0.2f}".format(z
[0], z
[1]), size
=18)
結果如下圖:
當然還可以用二次項回歸
z
= np
.polyfit
(year
, sales
, 2)
z
z
[0]
z
[1]
z
[2]yhat
= z
[0]*year
*year
+ z
[1]*year
+ z
[2]plt
.plot
(year
, sales
, 'ro')
plt
.plot
(year
, yhat
, 'b-')
plt
.text
(2010, 3000, "{:0.2f}*year^2 + {:0.2f}*year + {:0.2f}".format(z
[0], z
[1], z
[2] ))
也可以用對數回歸
lnsales
= np
.log
(sales
)z
= np
.polyfit
(year
, lnsales
, 1)yhat
= z
[0]*year
+ z
[1]plt
.plot
(year
, lnsales
, 'ro')
plt
.plot
(year
, yhat
)
plt
.text
(2010, 1, "ln(sales)={:0.2f}*year+{:0.2f}".format(z
[0], z
[1]))
感覺多項式回歸比較好一些:
from sklearn
.linear_model
import LinearRegression
model
= LinearRegression
()X
= year
.reshape
(-1, 1)
model
.fit
(X
, sales
)model
.intercept_
model
.coef_model
.get_params
()
model
.score
(X
, sales
)
Xx2
= np
.hstack
([X
, X
**2])
x2L2
= LinearRegression
()
L2
.fit
(x2
, sales
)
L2
.intercept_
L2
.coef_L2
.score
(x2
,sales
)
結果二次項回歸R2 =0.94513, 一元線性回歸,R2 = 0.7853
單純做統計分析的話還是statsmodel庫比較好一點。輸出美觀一些。
import numpy
as np
import statsmodels
.api
as sm
import statsmodels
.formula
.api
as smf
import pandas
as pddf
= pd
.read_json
('{"year ":{"0":2009,"1":2010,"2":2011,"3":2012,"4":2013,"5":2014,"6":2015,"7":2016,"8":2017,"9":2018,"10":2019,"11":2020}," sales":{"0":0.5,"1":9.36,"2":52.0,"3":191.0,"4":352.0,"5":571.0,"6":912.0,"7":1207.0,"8":1682.69,"9":2135.0,"10":2684.0,"11":4982.0}}')
dfresults
= smf
.ols
("sales ~ year ", data
=df
).fit
()
results
.summary
()results
= smf
.ols
("sales ~ year + np.square(year) ", data
=df
).fit
()results
= smf
.ols
("np.log(sales) ~ year", data
=df
).fit
()
results
.summary
()
總結
以上是生活随笔為你收集整理的python分析双十一销量的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。