自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

如何使用XGBoost和InluxDB進(jìn)行時(shí)間序列預(yù)測(cè)

譯文
人工智能 機(jī)器學(xué)習(xí)
XGBoost是一個(gè)流行的開源機(jī)器學(xué)習(xí)庫(kù),可用于解決各種預(yù)測(cè)問(wèn)題。人們需要了解如何使用它與InfluxDB進(jìn)行時(shí)間序列預(yù)測(cè)。

譯者 | 李睿

審校 | 孫淑娟

XGBoost是一個(gè)開源的機(jī)器學(xué)習(xí)庫(kù),它實(shí)現(xiàn)了優(yōu)化的分布式梯度增強(qiáng)算法。XGBoost使用并行處理實(shí)現(xiàn)快速性能,很好地處理缺失值,在小型數(shù)據(jù)集上執(zhí)行良好,并防止過(guò)擬合。所有這些優(yōu)點(diǎn)使XGBoost成為回歸問(wèn)題(例如預(yù)測(cè))的一種流行解決方案。

預(yù)測(cè)是各種業(yè)務(wù)目標(biāo)的關(guān)鍵任務(wù),例如預(yù)測(cè)分析、預(yù)測(cè)維護(hù)、產(chǎn)品規(guī)劃、預(yù)算等。許多預(yù)測(cè)或預(yù)測(cè)問(wèn)題都涉及到時(shí)間序列數(shù)據(jù)。這使得XGBoost成為開源時(shí)間序列數(shù)據(jù)庫(kù)InfluxDB的出色伙伴。

本教程將學(xué)習(xí)如何使用XGBoost的Python包預(yù)測(cè)來(lái)自InfluxDB時(shí)間序列數(shù)據(jù)庫(kù)的數(shù)據(jù)。還將使用InfluxDB Python客戶端庫(kù)從InfluxDB查詢數(shù)據(jù),并將數(shù)據(jù)轉(zhuǎn)換為Pandas DataFrame,以便更容易地使用時(shí)間序列數(shù)據(jù),然后再做預(yù)測(cè)。此外,還將更詳細(xì)地討論XGBoost的優(yōu)點(diǎn)。

一、要求

本教程是在通過(guò)Homebrew安裝Python 3的macOS系統(tǒng)上執(zhí)行的。建議設(shè)置額外的工具,如virtualenv、pyenv或conda-env,以簡(jiǎn)化Python和客戶端安裝。否則,其全部要求如下:

  • influxdb-client=1.30.0
  • pandas = 1.4.3
  • xgboost>=1.7.3
  • influxdb-client>=1.30.0
  • pandas>=1.4.3
  • matplotlib>=3.5.2
  • sklearn>=1.1.1

本教程還假設(shè)有一個(gè)免費(fèi)的層InfluxDB云帳戶,并且已經(jīng)創(chuàng)建了一個(gè)存儲(chǔ)桶和一個(gè)令牌,可以將存儲(chǔ)桶視為數(shù)據(jù)庫(kù)或InfluxDB中數(shù)據(jù)組織的最高層次結(jié)構(gòu)。在本教程中,將創(chuàng)建一個(gè)名為NOAA的存儲(chǔ)桶。

二、決策樹、隨機(jī)森林和梯度增強(qiáng)

為了理解XGBoost是什么,必須理解決策樹、隨機(jī)森林和梯度增強(qiáng)。決策樹是一種有監(jiān)督的學(xué)習(xí)方法,由一系列特征測(cè)試組成。每個(gè)節(jié)點(diǎn)都是一個(gè)測(cè)試,所有節(jié)點(diǎn)都被組織在一個(gè)流程圖結(jié)構(gòu)中。分支表示最終決定將哪個(gè)葉標(biāo)簽或類標(biāo)簽分配給輸入數(shù)據(jù)的條件。

圖片

機(jī)器學(xué)習(xí)中的決策樹用于確定明天是否會(huì)下雨。經(jīng)過(guò)編輯以顯示決策樹的組件:葉、分支和節(jié)點(diǎn)。

決策樹、隨機(jī)森林和梯度增強(qiáng)背后的指導(dǎo)原則是,多個(gè)“弱學(xué)習(xí)者”或分類器共同做出強(qiáng)大的預(yù)測(cè)。

隨機(jī)森林包含多個(gè)決策樹。決策樹中的每個(gè)節(jié)點(diǎn)都被認(rèn)為是弱學(xué)習(xí)者,隨機(jī)森林中的每個(gè)決策樹被認(rèn)為是隨機(jī)森林模型中許多弱學(xué)習(xí)者中的一個(gè)。通常情況下,所有的數(shù)據(jù)都被隨機(jī)劃分為子集,并通過(guò)不同的決策樹進(jìn)行傳遞。

使用決策樹和隨機(jī)森林的梯度增強(qiáng)是相似的,但它們的結(jié)構(gòu)方式不同。梯度增強(qiáng)樹也包含決策樹森林,但這些決策樹是額外構(gòu)建的,所有數(shù)據(jù)都經(jīng)過(guò)決策樹集合。梯度增強(qiáng)樹可能包含一組分類樹或回歸樹,分類樹用于離散值(例如貓或狗)。回歸樹用于連續(xù)值(例如0到100)。

三、什么是XGBoost?  

梯度增強(qiáng)是一種用于分類和預(yù)測(cè)的機(jī)器學(xué)習(xí)算法。XGBoost只是一個(gè)極端類型的梯度增強(qiáng)。它的極端之處在于,可以通過(guò)并行處理的能力更有效地執(zhí)行梯度增強(qiáng)。XGBoost文檔中的下圖說(shuō)明了如何使用梯度增強(qiáng)來(lái)預(yù)測(cè)某人是否會(huì)喜歡一款電子游戲。

圖片

采用兩棵決策樹被用來(lái)決定某人是否可能喜歡一款電子游戲。將兩棵樹的葉子得分相加,以確定哪一個(gè)人最有可能喜歡這款電子游戲。

XGBoost的一些優(yōu)點(diǎn):

  • 相對(duì)容易理解。
  • 適用于具有很少特征的小型、結(jié)構(gòu)化和規(guī)則數(shù)據(jù)。

XGBoost的一些缺點(diǎn):

  • 易于過(guò)擬合,對(duì)異常值敏感。在XGBoost中使用時(shí)間序列數(shù)據(jù)的物化視圖進(jìn)行預(yù)測(cè)可能是一個(gè)好主意。
  • 在稀疏或無(wú)監(jiān)督數(shù)據(jù)上表現(xiàn)不佳。

四、使用XGBoost進(jìn)行時(shí)間序列預(yù)測(cè)

在這里使用的是空氣傳感器樣本數(shù)據(jù)集,它是由InfluxDB提供的。該數(shù)據(jù)集包含來(lái)自多個(gè)傳感器的溫度數(shù)據(jù)。正在為單個(gè)傳感器創(chuàng)建溫度預(yù)測(cè),其數(shù)據(jù)是這樣的:

圖片

使用以下Flux代碼導(dǎo)入單個(gè)時(shí)間序列的數(shù)據(jù)集和過(guò)濾器。(Flux是InfluxDB的查詢語(yǔ)言)

import "join"

import "influxdata/influxdb/sample"

//dataset is regular time series at 10 second intervals

data = sample.data(set: "airSensor")

|> filter(fn: (r) => r._field == "temperature" and r.sensor_id == "TLM0100")

隨機(jī)森林和梯度增強(qiáng)可以用于時(shí)間序列預(yù)測(cè),但它們需要將數(shù)據(jù)轉(zhuǎn)換為監(jiān)督學(xué)習(xí)。這意味著必須以滑動(dòng)窗口方法或緩慢移動(dòng)方法將數(shù)據(jù)向前移動(dòng),以將時(shí)間序列數(shù)據(jù)轉(zhuǎn)換為監(jiān)督學(xué)習(xí)集,也可以用Flux準(zhǔn)備數(shù)據(jù)。在理想情況下,應(yīng)該首先執(zhí)行一些自相關(guān)分析,以確定要使用的最佳方法。為簡(jiǎn)潔起見,將使用以下Flux代碼按一個(gè)常規(guī)時(shí)間間隔移動(dòng)數(shù)據(jù)。

import "join"

import "influxdata/influxdb/sample"

data = sample.data(set: "airSensor")

|> filter(fn: (r) => r._field == "temperature" and r.sensor_id == "TLM0100")

shiftedData = data

|> timeShift(duration: 10s , columns: ["_time"] )

join.time(left: data, right: shiftedData, as: (l, r) => ({l with data: l._value, shiftedData: r._value}))

|> drop(columns: ["_measurement", "_time", "_value", "sensor_id", "_field"])

左右滑動(dòng)查看完整代碼

圖片

如果想向模型輸入中添加額外的滯后數(shù)據(jù),可以改為遵循以下Flux邏輯。

import "experimental"

import "influxdata/influxdb/sample"

data = sample.data(set: "airSensor")

|> filter(fn: (r) => r._field == "temperature" and r.sensor_id == "TLM0100")



shiftedData1 = data

|> timeShift(duration: 10s , columns: ["_time"] )

|> set(key: "shift" , value: "1" )



shiftedData2 = data

|> timeShift(duration: 20s , columns: ["_time"] )

|> set(key: "shift" , value: "2" )



shiftedData3 = data

|> timeShift(duration: 30s , columns: ["_time"] )

|> set(key: "shift" , value: "3")



shiftedData4 = data

|> timeShift(duration: 40s , columns: ["_time"] )

|> set(key: "shift" , value: "4")



union(tables: [shiftedData1, shiftedData2, shiftedData3, shiftedData4])

|> pivot(rowKey:["_time"], columnKey: ["shift"], valueColumn: "_value")

|> drop(columns: ["_measurement", "_time", "_value", "sensor_id", "_field"])

// remove the NaN values

|> limit(n:360)

|> tail(n: 356)

此外,我們必須使用向前驗(yàn)證來(lái)訓(xùn)練算法。這涉及到將數(shù)據(jù)集分為測(cè)試集和訓(xùn)練集。然后利用XGB Regressor對(duì)XGBoost模型進(jìn)行訓(xùn)練,并用擬合方法進(jìn)行預(yù)測(cè)。最后,我們使用平均絕對(duì)誤差 (MAE)來(lái)確定預(yù)測(cè)的準(zhǔn)確性。對(duì)于10秒的延遲,計(jì)算出的平均絕對(duì)誤差 (MAE)為0.035。我們可以把這理解為96.5%的預(yù)測(cè)是非常正確的。下圖展示了我們從XGBoost得到的預(yù)測(cè)結(jié)果與從訓(xùn)練/測(cè)試分割得到的期望值之間的對(duì)比。

圖片

以下是完整的腳本。這段代碼主要是從這里的教程中引入的。

import pandas as pd

from numpy import asarray

from sklearn.metrics import mean_absolute_error

from xgboost import XGBRegressor

from matplotlib import pyplot

from influxdb_client import InfluxDBClient

from influxdb_client.client.write_api import SYNCHRONOUS



# query data with the Python InfluxDB Client Library and transform data into a supervised learning problem with Flux

client = InfluxDBClient(url="https://us-west-2-1.aws.cloud2.influxdata.com", token="NyP-HzFGkObUBI4Wwg6Rbd-_SdrTMtZzbFK921VkMQWp3bv_e9BhpBi6fCBr_0-6i0ev32_XWZcmkDPsearTWA==", org="0437f6d51b579000")



# write_api = client.write_api(write_optinotallow=SYNCHRONOUS)

query_api = client.query_api()

df = query_api.query_data_frame('import "join"'

'import "influxdata/influxdb/sample"'

'data = sample.data(set: "airSensor")'

'|> filter(fn: (r) => r._field == "temperature" and r.sensor_id == "TLM0100")'

'shiftedData = data'

'|> timeShift(duration: 10s , columns: ["_time"] )'

'join.time(left: data, right: shiftedData, as: (l, r) => ({l with data: l._value, shiftedData: r._value}))'

'|> drop(columns: ["_measurement", "_time", "_value", "sensor_id", "_field"])'

'|> yield(name: "converted to supervised learning dataset")'

)

df = df.drop(columns=['table', 'result'])

data = df.to_numpy()



# split a univariate dataset into train/test sets

def train_test_split(data, n_test):

return data[:-n_test:], data[-n_test:]



# fit an xgboost model and make a one step prediction

def xgboost_forecast(train, testX):

# transform list into array

train = asarray(train)

# split into input and output columns

trainX, trainy = train[:, :-1], train[:, -1]

# fit model

model = XGBRegressor(objective='reg:squarederror', n_estimators=1000)

model.fit(trainX, trainy)

# make a one-step prediction

yhat = model.predict(asarray([testX]))

return yhat[0]



# walk-forward validation for univariate data

def walk_forward_validation(data, n_test):

predictions = list()

# split dataset

train, test = train_test_split(data, n_test)

history = [x for x in train]

# step over each time-step in the test set

for i in range(len(test)):

# split test row into input and output columns

testX, testy = test[i, :-1], test[i, -1]

# fit model on history and make a prediction

yhat = xgboost_forecast(history, testX)

# store forecast in list of predictions

predictions.append(yhat)

# add actual observation to history for the next loop

history.append(test[i])

# summarize progress

print('>expected=%.1f, predicted=%.1f' % (testy, yhat))

# estimate prediction error

error = mean_absolute_error(test[:, -1], predictions)

return error, test[:, -1], predictions



# evaluate

mae, y, yhat = walk_forward_validation(data, 100)

print('MAE: %.3f' % mae)



# plot expected vs predicted

pyplot.plot(y, label='Expected')

pyplot.plot(yhat, label='Predicted')

pyplot.legend()

pyplot.show()

五、結(jié)論

希望這篇博文能夠激勵(lì)人們利用XGBoost和InfluxDB進(jìn)行預(yù)測(cè)。為此建議查看相關(guān)的報(bào)告,其中包括如何使用本文描述的許多算法和InfluxDB來(lái)進(jìn)行預(yù)測(cè)和執(zhí)行異常檢測(cè)的示例。

原文鏈接:https://www.infoworld.com/article/3682070/time-series-forecasting-with-xgboost-and-influxdb.html

責(zé)任編輯:武曉燕 來(lái)源: 51CTO技術(shù)棧
相關(guān)推薦

2021-04-07 10:02:00

XGBoostPython代碼

2024-07-18 13:13:58

2025-01-14 13:32:47

2023-03-16 07:27:30

CnosDB數(shù)據(jù)庫(kù)

2024-01-30 01:12:37

自然語(yǔ)言時(shí)間序列預(yù)測(cè)Pytorch

2022-12-09 14:50:51

機(jī)器學(xué)習(xí)時(shí)間序列預(yù)測(cè)

2024-10-23 17:10:49

2024-11-04 15:34:01

2017-01-09 09:20:07

Ubuntu NTP同步

2022-11-24 17:00:01

模型ARDL開發(fā)

2022-08-16 09:00:00

機(jī)器學(xué)習(xí)人工智能數(shù)據(jù)庫(kù)

2024-05-09 16:23:14

2024-06-27 16:38:57

2024-12-16 13:15:15

機(jī)器學(xué)習(xí)時(shí)間序列分析數(shù)據(jù)缺失

2021-07-01 21:46:30

PythonHot-Winters數(shù)據(jù)

2023-10-13 15:34:55

時(shí)間序列TimesNet

2024-06-17 16:02:58

2024-11-15 15:20:00

模型數(shù)據(jù)

2023-10-16 18:02:29

2021-07-02 10:05:45

PythonHot-winters指數(shù)平滑
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)