在本文中,我們將嘗試實(shí)現(xiàn)一個(gè)機(jī)器學(xué)習(xí)模型,該模型可以預(yù)測(cè)在不同商店銷售的不同產(chǎn)品的庫(kù)存量。
導(dǎo)入庫(kù)和數(shù)據(jù)集
Python庫(kù)使我們可以輕松地處理數(shù)據(jù),并通過一行代碼執(zhí)行典型和復(fù)雜的任務(wù)。
- Pandas -此庫(kù)有助于以2D陣列格式加載數(shù)據(jù)幀,并具有多種功能,可一次性執(zhí)行分析任務(wù)。
- Numpy - Numpy數(shù)組非??欤梢栽诤芏痰臅r(shí)間內(nèi)執(zhí)行大型計(jì)算。
- Matplotlib/Seaborn -這個(gè)庫(kù)用于繪制可視化。
- Sklearn -此模塊包含多個(gè)庫(kù),這些庫(kù)具有預(yù)實(shí)現(xiàn)的功能,以執(zhí)行從數(shù)據(jù)預(yù)處理到模型開發(fā)和評(píng)估的任務(wù)。
- XGBoost -這包含eXtreme Gradient Boosting機(jī)器學(xué)習(xí)算法,這是幫助我們實(shí)現(xiàn)高精度預(yù)測(cè)的算法之一。
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sb
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder, StandardScaler
from sklearn import metrics
from sklearn.svm import SVC
from xgboost import XGBRegressor
from sklearn.linear_model import LinearRegression, Lasso, Ridge
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import mean_absolute_error as mae
import warnings
warnings.filterwarnings('ignore')
現(xiàn)在,讓我們將數(shù)據(jù)集加載到panda的數(shù)據(jù)框中,并打印它的前五行。
df = pd.read_csv('StoreDemand.csv')
display(df.head())
display(df.tail())
如我們所見,我們有10家商店和50種產(chǎn)品的5年數(shù)據(jù),可以計(jì)算得,
(365 * 4 + 366) * 10 * 50 = 913000
現(xiàn)在讓我們檢查一下我們計(jì)算的數(shù)據(jù)大小是否正確。
df.shape
輸出:
(913000, 4)
讓我們檢查數(shù)據(jù)集的每列包含哪種類型的數(shù)據(jù)。
df.info()
根據(jù)上面關(guān)于每列數(shù)據(jù)的信息,我們可以觀察到?jīng)]有空值。
df.describe()
特征工程
有時(shí)候,同一個(gè)特征中提供了多個(gè)特征,或者我們必須從現(xiàn)有的特征中派生一些特征。我們還將嘗試在數(shù)據(jù)集中包含一些額外的功能,以便我們可以從我們擁有的數(shù)據(jù)中獲得一些有趣的見解。此外,如果導(dǎo)出的特征是有意義的,那么它們將成為顯著提高模型準(zhǔn)確性的決定性因素。
parts = df["date"].str.split("-", n = 3, expand = True)
df["year"]= parts[0].astype('int')
df["month"]= parts[1].astype('int')
df["day"]= parts[2].astype('int')
df.head()
無論是周末還是工作日,都必須對(duì)滿足需求的要求產(chǎn)生一定的影響。
from datetime import datetime
import calendar
def weekend_or_weekday(year,month,day):
d = datetime(year,month,day)
if d.weekday()>4:
return 1
else:
return 0
df['weekend'] = df.apply(lambda x:weekend_or_weekday(x['year'], x['month'], x['day']), axis=1)
df.head()
如果有一個(gè)列可以表明某一天是否有任何假期,那就太好了。
from datetime import date
import holidays
def is_holiday(x):
india_holidays = holidays.country_holidays('IN')
if india_holidays.get(x):
return 1
else:
return 0
df['holidays'] = df['date'].apply(is_holiday)
df.head()
現(xiàn)在,讓我們添加一些周期特性。
df['m1'] = np.sin(df['month'] * (2 * np.pi / 12))
df['m2'] = np.cos(df['month'] * (2 * np.pi / 12))
df.head()
讓我們有一個(gè)列,其值指示它是一周中的哪一天。
def which_day(year, month, day):
d = datetime(year,month,day)
return d.weekday()
df['weekday'] = df.apply(lambda x: which_day(x['year'],
x['month'],
x['day']),
axis=1)
df.head()
現(xiàn)在讓我們刪除對(duì)我們無用的列。
df.drop('date', axis=1, inplace=True)
可能還有一些其他相關(guān)的特征可以添加到這個(gè)數(shù)據(jù)集中,但是讓我們嘗試使用這些特征構(gòu)建一個(gè)構(gòu)建,并嘗試提取一些見解。
探索性數(shù)據(jù)分析
EDA是一種使用可視化技術(shù)分析數(shù)據(jù)的方法。它用于發(fā)現(xiàn)趨勢(shì)和模式,或在統(tǒng)計(jì)摘要和圖形表示的幫助下檢查假設(shè)。
我們使用一些假設(shè)向數(shù)據(jù)集添加了一些功能。現(xiàn)在讓我們檢查不同特征與目標(biāo)特征之間的關(guān)系。
df['store'].nunique(), df['item'].nunique()
輸出:
(10, 50)
從這里我們可以得出結(jié)論,有10個(gè)不同的商店,他們出售50種不同的產(chǎn)品。
features = ['store', 'year', 'month',\
'weekday', 'weekend', 'holidays']
plt.subplots(figsize=(20, 10))
for i, col in enumerate(features):
plt.subplot(2, 3, i + 1)
df.groupby(col).mean()['sales'].plot.bar()
plt.show()
現(xiàn)在讓我們來看看隨著月末的臨近,庫(kù)存的變化情況.
plt.figure(figsize=(10,5))
df.groupby('day').mean()['sales'].plot()
plt.show()
讓我們畫出30天的表現(xiàn)。
plt.figure(figsize=(15, 10))
# Calculating Simple Moving Average
# for a window period of 30 days
window_size = 30
data = df[df['year']==2013]
windows = data['sales'].rolling(window_size)
sma = windows.mean()
sma = sma[window_size - 1:]
data['sales'].plot()
sma.plot()
plt.legend()
plt.show()
由于sales列中的數(shù)據(jù)是連續(xù)的,讓我們檢查它的分布,并檢查該列中是否有一些離群值。
plt.subplots(figsize=(12, 5))
plt.subplot(1, 2, 1)
sb.distplot(df['sales'])
plt.subplot(1, 2, 2)
sb.boxplot(df['sales'])
plt.show()
高度相關(guān)的特征
plt.figure(figsize=(10, 10))
sb.heatmap(df.corr() > 0.8,
annot=True,
cbar=False)
plt.show()
正如我們之前所觀察到的,讓我們刪除數(shù)據(jù)中存在的離群值。
df = df[df['sales']<140]
模型訓(xùn)練
現(xiàn)在,我們將分離特征和目標(biāo)變量,并將它們分為訓(xùn)練數(shù)據(jù)和測(cè)試數(shù)據(jù),我們將使用這些數(shù)據(jù)來選擇在驗(yàn)證數(shù)據(jù)上表現(xiàn)最好的模型。
features = df.drop(['sales', 'year'], axis=1)
target = df['sales'].values
X_train, X_val, Y_train, Y_val = train_test_split(features, target,
test_size = 0.05,
random_state=22)
X_train.shape, X_val.shape
輸出:
((861170, 9), (45325, 9))
在將數(shù)據(jù)輸入機(jī)器學(xué)習(xí)模型之前對(duì)其進(jìn)行標(biāo)準(zhǔn)化,有助于我們實(shí)現(xiàn)穩(wěn)定和快速的訓(xùn)練。
# Normalizing the features for stable and fast training.
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_val = scaler.transform(X_val)
我們將數(shù)據(jù)分為訓(xùn)練數(shù)據(jù)和驗(yàn)證數(shù)據(jù),并對(duì)數(shù)據(jù)進(jìn)行了歸一化。現(xiàn)在,讓我們訓(xùn)練一些最先進(jìn)的機(jī)器學(xué)習(xí)模型,并使用驗(yàn)證數(shù)據(jù)集從中選擇最佳模型。文章來源:http://www.zghlxwxcb.cn/news/detail-639530.html
models = [LinearRegression(), XGBRegressor(), Lasso(), Ridge()]
for i in range(4):
models[i].fit(X_train, Y_train)
print(f'{models[i]} : ')
train_preds = models[i].predict(X_train)
print('Training Error : ', mae(Y_train, train_preds))
val_preds = models[i].predict(X_val)
print('Validation Error : ', mae(Y_val, val_preds))
輸出:文章來源地址http://www.zghlxwxcb.cn/news/detail-639530.html
LinearRegression() :
Training Error : 20.902897365994484
Validation Error : 20.97143554027027
[08:31:23] WARNING: /workspace/src/objective/regression_obj.cu:152:
reg:linear is now deprecated in favor of reg:squarederror.
XGBRegressor() :
Training Error : 11.751541013057603
Validation Error : 11.790298395298885
Lasso() :
Training Error : 21.015028699769758
Validation Error : 21.071517213774968
Ridge() :
Training Error : 20.90289749951532
Validation Error : 20.971435731904066
到了這里,關(guān)于基于機(jī)器學(xué)習(xí)的庫(kù)存需求預(yù)測(cè) -- 機(jī)器學(xué)習(xí)項(xiàng)目基礎(chǔ)篇(12)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!