據(jù)Python爬蟲(chóng)不靠譜預(yù)測(cè)可知今年雙十一銷(xiāo)售額將超過(guò)6000億元
不知不覺(jué),雙十一到今年已經(jīng)是13個(gè)年頭,每年大家都在滿心期待看著屏幕上的數(shù)字跳動(dòng),年年打破記錄。而 2019 年的天貓雙11的銷(xiāo)售額卻被一位微博網(wǎng)友提前7個(gè)月用數(shù)據(jù)擬合的方法預(yù)測(cè)出來(lái)了。他的預(yù)測(cè)值是2675.37或者2689.00億元,而實(shí)際成交額是2684億元。只差了5億元,誤差率只有千分之一。
但如果你用同樣的方法去做預(yù)測(cè)2020年的時(shí)候,發(fā)現(xiàn)預(yù)測(cè)是3282億,實(shí)際卻到了 4982億。原來(lái)2020改了規(guī)則,實(shí)際上統(tǒng)計(jì)的是11月1到11日的銷(xiāo)量,理論上已經(jīng)不能和歷史數(shù)據(jù)合并預(yù)測(cè),但咱們就為了圖個(gè)樂(lè),主要是為了練習(xí)一下 Python 的多項(xiàng)式回歸和可視化繪圖。
把預(yù)測(cè)先發(fā)出來(lái):今年雙十一的銷(xiāo)量是 9029.688 億元!坐等雙十一,各位看官回來(lái)打我的臉。歡迎文末技術(shù)交流學(xué)習(xí),喜歡點(diǎn)贊支持。
NO.1 統(tǒng)計(jì)歷年雙十一銷(xiāo)量數(shù)據(jù)
從網(wǎng)上搜集來(lái)歷年淘寶天貓雙十一銷(xiāo)售額數(shù)據(jù),單位為億元,利用 Pandas 整理成 Dataframe,又添加了一列'年份int',留作后續(xù)的計(jì)算使用。
import pandas as pd
# 數(shù)據(jù)為網(wǎng)絡(luò)收集,歷年淘寶天貓雙十一銷(xiāo)售額數(shù)據(jù),單位為億元,僅做示范
double11_sales = {'2009年': [0.50],
'2010年':[9.36],
'2011年':[34],
'2012年':[191],
'2013年':[350],
'2014年':[571],
'2015年':[912],
'2016年':[1207],
'2017年':[1682],
'2018年':[2135],
'2019年':[2684],
'2020年':[4982],
}
df = pd.DataFrame(double11_sales).T.reset_index()
df.rename(columns={'index':'年份',0:'銷(xiāo)量'},inplace=True)
df['年份int'] = [[i] for i in list(range(1,len(df['年份'])+1))]
df
.dataframe tbody tr th {
vertical-align: top;
}
.dataframe thead th {
text-align: right;
}

NO.2 繪制散點(diǎn)圖
利用 plotly 工具包,將年份對(duì)應(yīng)銷(xiāo)售量的散點(diǎn)圖繪制出來(lái),可以明顯看到2020年的數(shù)據(jù)立馬飆升。
# 散點(diǎn)圖 import plotly as py import plotly.graph_objs as go import numpy as np year = df[:]['年份'] sales = df['銷(xiāo)量'] trace = go.Scatter( x=year, y=sales, mode='markers' ) data = [trace] layout = go.Layout(title='2009年-2020年天貓?zhí)詫氹p十一歷年銷(xiāo)量') fig = go.Figure(data=data, layout=layout) fig.show()

NO.3引入 Scikit-Learn 庫(kù)搭建模型
一元多次線性回歸
我們先來(lái)回顧一下2009-2019年的數(shù)據(jù)多么美妙。先只選取2009-2019年的數(shù)據(jù):
df_2009_2019 = df[:-1] df_2009_2019
.dataframe tbody tr th {
vertical-align: top;
}
.dataframe thead th {
text-align: right;
}

通過(guò)以下代碼生成二次項(xiàng)數(shù)據(jù):
from sklearn.preprocessing import PolynomialFeatures poly_reg = PolynomialFeatures(degree=2) X_ = poly_reg.fit_transform(list(df_2009_2019['年份int']))
1.第一行代碼引入用于增加一個(gè)多次項(xiàng)內(nèi)容的模塊 PolynomialFeatures
2.第二行代碼設(shè)置最高次項(xiàng)為二次項(xiàng),為生成二次項(xiàng)數(shù)據(jù)(x平方)做準(zhǔn)備
3.第三行代碼將原有的X轉(zhuǎn)換為一個(gè)新的二維數(shù)組X_,該二維數(shù)據(jù)包含新生成的二次項(xiàng)數(shù)據(jù)(x平方)和原有的一次項(xiàng)數(shù)據(jù)(x)
X_ 的內(nèi)容為下方代碼所示的一個(gè)二維數(shù)組,其中第一列數(shù)據(jù)為常數(shù)項(xiàng)(其實(shí)就是X的0次方),沒(méi)有特殊含義,對(duì)分析結(jié)果不會(huì)產(chǎn)生影響;第二列數(shù)據(jù)為原有的一次項(xiàng)數(shù)據(jù)(x);第三列數(shù)據(jù)為新生成的二次項(xiàng)數(shù)據(jù)(x的平方)。
X_
array([[ 1.,1.,1.], [ 1.,2.,4.], [ 1.,3.,9.], [ 1.,4., 16.], [ 1.,5., 25.], [ 1.,6., 36.], [ 1.,7., 49.], [ 1.,8., 64.], [ 1.,9., 81.], [ 1., 10., 100.], [ 1., 11., 121.]])
from sklearn.linear_model import LinearRegression regr = LinearRegression() regr.fit(X_,list(df_2009_2019['銷(xiāo)量']))
LinearRegression()
1.第一行代碼從 Scikit-Learn 庫(kù)引入線性回歸的相關(guān)模塊 LinearRegression;
2.第二行代碼構(gòu)造一個(gè)初始的線性回歸模型并命名為 regr;
3.第三行代碼用fit() 函數(shù)完成模型搭建,此時(shí)的regr就是一個(gè)搭建好的線性回歸模型。
NO.4 模型預(yù)測(cè)
接下來(lái)就可以利用搭建好的模型 regr 來(lái)預(yù)測(cè)數(shù)據(jù)。加上自變量是12,那么使用 predict() 函數(shù)就能預(yù)測(cè)對(duì)應(yīng)的因變量有,代碼如下:
XX_ = poly_reg.fit_transform([[12]])
XX_
array([[ 1., 12., 144.]])
y = regr.predict(XX_) y
array([3282.23478788])
這里我們就得到了如果按照這個(gè)趨勢(shì)2009-2019的趨勢(shì)預(yù)測(cè)2020的結(jié)果,就是3282,但實(shí)際卻是4982億,原因就是上文提到的合并計(jì)算了,金額一下子變大了,繪制成圖,就是下面這樣:
# 散點(diǎn)圖 import plotly as py import plotly.graph_objs as go import numpy as np year = list(df['年份']) sales = df['銷(xiāo)量'] trace1 = go.Scatter( x=year, y=sales, mode='markers', name="實(shí)際銷(xiāo)量" # 第一個(gè)圖例名稱(chēng) ) XX_ = poly_reg.fit_transform(list(df['年份int'])+[[13]]) regr = LinearRegression() regr.fit(X_,list(df_2009_2019['銷(xiāo)量'])) trace2 = go.Scatter( x=list(df['年份']), y=regr.predict(XX_), mode='lines', name="擬合數(shù)據(jù)", # 第2個(gè)圖例名稱(chēng) ) data = [trace1,trace2] layout = go.Layout(title='天貓?zhí)詫氹p十一歷年銷(xiāo)量', xaxis_title='年份', yaxis_title='銷(xiāo)量') fig = go.Figure(data=data, layout=layout) fig.show()

NO.5 預(yù)測(cè)2021年的銷(xiāo)量
既然數(shù)據(jù)發(fā)生了巨大的偏離,咱們也別深究了,就大力出奇跡。同樣的方法,把2020年的真實(shí)數(shù)據(jù)納入進(jìn)來(lái),二話不說(shuō)擬合一樣,看看會(huì)得到什么結(jié)果:
from sklearn.preprocessing import PolynomialFeatures poly_reg = PolynomialFeatures(degree=5) X_ = poly_reg.fit_transform(list(df['年份int']))
## 預(yù)測(cè)2020年 regr = LinearRegression() regr.fit(X_,list(df['銷(xiāo)量']))
LinearRegression()
XXX_ = poly_reg.fit_transform(list(df['年份int'])+[[13]])
# 散點(diǎn)圖 import plotly as py import plotly.graph_objs as go import numpy as np year = list(df['年份']) sales = df['銷(xiāo)量'] trace1 = go.Scatter( x=year+['2021年','2022年','2023年'], y=sales, mode='markers', name="實(shí)際銷(xiāo)量" # 第一個(gè)圖例名稱(chēng) ) trace2 = go.Scatter( x=year+['2021年','2022年','2023年'], y=regr.predict(XXX_), mode='lines', name="預(yù)測(cè)銷(xiāo)量" # 第一個(gè)圖例名稱(chēng) ) trace3 = go.Scatter( x=['2021年'], y=[regr.predict(XXX_)[-1]], mode='markers', name="2021年預(yù)測(cè)銷(xiāo)量" # 第一個(gè)圖例名稱(chēng) ) data = [trace1,trace2,trace3] layout = go.Layout(title='天貓?zhí)詫氹p十一歷年銷(xiāo)量', xaxis_title='年份', yaxis_title='銷(xiāo)量') fig = go.Figure(data=data, layout=layout) fig.show()

NO.6多項(xiàng)式預(yù)測(cè)的次數(shù)到底如何選擇
在選擇模型中的次數(shù)方面,可以通過(guò)設(shè)置程序,循環(huán)計(jì)算各個(gè)次數(shù)下預(yù)測(cè)誤差,然后再根據(jù)結(jié)果反選參數(shù)。
df_new = df.copy() df_new['年份int'] = df['年份int'].apply(lambda x: x[0]) df_new
.dataframe tbody tr th {
vertical-align: top;
}
.dataframe thead th {
text-align: right;
}

# 多項(xiàng)式回歸預(yù)測(cè)次數(shù)選擇
# 計(jì)算 m 次多項(xiàng)式回歸預(yù)測(cè)結(jié)果的 MSE 評(píng)價(jià)指標(biāo)并繪圖
from sklearn.pipeline import make_pipeline
from sklearn.metrics import mean_squared_error
train_df = df_new[:int(len(df)*0.95)]
test_df = df_new[int(len(df)*0.5):]
# 定義訓(xùn)練和測(cè)試使用的自變量和因變量
train_x = train_df['年份int'].values
train_y = train_df['銷(xiāo)量'].values
# print(train_x)
test_x = test_df['年份int'].values
test_y = test_df['銷(xiāo)量'].values
train_x = train_x.reshape(len(train_x),1)
test_x = test_x.reshape(len(test_x),1)
train_y = train_y.reshape(len(train_y),1)
mse = [] # 用于存儲(chǔ)各最高次多項(xiàng)式 MSE 值
m = 1 # 初始 m 值
m_max = 10 # 設(shè)定最高次數(shù)
while m <= m_max:
model = make_pipeline(PolynomialFeatures(m, include_bias=False), LinearRegression())
model.fit(train_x, train_y) # 訓(xùn)練模型
pre_y = model.predict(test_x) # 測(cè)試模型
mse.append(mean_squared_error(test_y, pre_y.flatten())) # 計(jì)算 MSE
m = m + 1
print("MSE 計(jì)算結(jié)果: ", mse)
# 繪圖
plt.plot([i for i in range(1, m_max + 1)], mse, 'r')
plt.scatter([i for i in range(1, m_max + 1)], mse)
# 繪制圖名稱(chēng)等
plt.title("MSE of m degree of polynomial regression")
plt.xlabel("m")
plt.ylabel("MSE")
MSE 計(jì)算結(jié)果: [1088092.9621201046, 481951.27857828484, 478840.8575107471, 477235.9140442428, 484657.87153138855, 509758.1526412842, 344204.1969956556, 429874.9229308078, 8281846.231771571, 146298201.8473966]
Text(0, 0.5, 'MSE')

從誤差結(jié)果可以看到,次數(shù)取2到8誤差基本穩(wěn)定,沒(méi)有明顯的減少了,但其實(shí)你試試就知道,次數(shù)選擇3的時(shí)候,預(yù)測(cè)的銷(xiāo)量是6213億元,次數(shù)選擇5的時(shí)候,預(yù)測(cè)的銷(xiāo)量是9029億元,對(duì)于銷(xiāo)售量來(lái)說(shuō),這個(gè)范圍已經(jīng)夠大的了。我也就斗膽猜到9029億元,我的膽量也就預(yù)測(cè)到這里了,破萬(wàn)億就太夸張了,歡迎膽子大的同學(xué)留下你們的預(yù)測(cè)結(jié)果,讓我們11月11日,拭目以待吧。
NO.7 總結(jié)最后
希望這篇文章帶著對(duì) Python 的多項(xiàng)式回歸和 Plotly可視化繪圖還不熟悉的同學(xué)一起練習(xí)一下。

技術(shù)交流
歡迎轉(zhuǎn)載、收藏、有所收獲點(diǎn)贊支持一下!

以上就是據(jù)Python爬蟲(chóng)不靠譜預(yù)測(cè)可知今年雙十一銷(xiāo)售額將超過(guò)6000億元的詳細(xì)內(nèi)容,更多關(guān)于Python 爬蟲(chóng)預(yù)測(cè)的資料請(qǐng)關(guān)注本站其它相關(guān)文章!
版權(quán)聲明:本站文章來(lái)源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請(qǐng)保持原文完整并注明來(lái)源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非maisonbaluchon.cn所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來(lái)源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來(lái),僅供學(xué)習(xí)參考,不代表本站立場(chǎng),如有內(nèi)容涉嫌侵權(quán),請(qǐng)聯(lián)系alex-e#qq.com處理。
關(guān)注官方微信