Facebook開源一站式服務(wù)python時(shí)序利器Kats詳解
轉(zhuǎn)自微信公眾號:機(jī)器學(xué)習(xí)社區(qū),經(jīng)作者授權(quán)轉(zhuǎn)載
時(shí)間序列分析是數(shù)據(jù)科學(xué)中一個(gè)非常重要的領(lǐng)域,它主要包含統(tǒng)計(jì)分析、檢測變化點(diǎn)、異常檢測和預(yù)測未來趨勢。然而,這些時(shí)間序列技術(shù)通常由不同的庫實(shí)現(xiàn)。有沒有一種方法可以讓你在一個(gè)庫中獲得所有這些技術(shù)?
答案是肯定的,本文中我將分享一個(gè)非常棒的工具包 Kats,它可以完美解決上述問題。
什么是 Kats?
目前時(shí)間序列分析以及建模的技術(shù)非常多,但相對散亂,本次 FaceBook 開源了 Kats,它是一款輕量級的、易于使用的、通用的時(shí)間序列分析框架,包括:預(yù)測、異常檢測、多元分析和特征提取嵌入。你可以將 Kats 視為 Python 中時(shí)間序列分析的一站式工具包。
安裝 Kats
pip install --upgrade pip pip install kats
為了了解 Kats 的功能,我們將使用這個(gè)框架來分析 Kaggle 上的 StackOverflow問題計(jì)數(shù)問題。數(shù)據(jù)鏈接為:https://www.kaggle.com/aishu200023/stackindex
首先我們從讀取數(shù)據(jù)開始。
import pandas as pd df = pd.read_csv("MLTollsStackOverflow.csv") # Turn the month column into datetime df["month"] = pd.to_datetime(df["month"], format="%y-%b") df = df.set_index("month")
現(xiàn)在讓我們分析一下與 Python 相關(guān)的 StackOverflow 問題計(jì)數(shù)。數(shù)據(jù)被分成一列和一個(gè)測試集來評估預(yù)測。
python = df["python"].to_frame() # Split data into train and test set train_len = 102 train = python.iloc[:train_len] test = python.iloc[train_len:]
將數(shù)據(jù)轉(zhuǎn)換為時(shí)間序列
首先構(gòu)造一個(gè)時(shí)間序列對象。我們使用time_col_name='month'
指定時(shí)間列。
from kats.consts import TimeSeriesData # Construct TimeSeriesData object ts = TimeSeriesData(train.reset_index(), time_col_name="month")
要繪制數(shù)據(jù),調(diào)用plot方法:
ts.plot(cols=["python"])
酷!看起來關(guān)于 Python 的問題的數(shù)量隨著時(shí)間的推移而增加。我們能預(yù)測未來30天的趨勢嗎?是的,我們可以和 Kats 一起做。
預(yù)測
Kats目前支持以下10種預(yù)測模型:
Linear
Quadratic
ARIMA
SARIMA
Holt-Winters
Prophet
AR-Net
LSTM
Theta
VAR
上述模型較多,讓我們試一下其中兩種類型吧!
從使用 Prophet 進(jìn)行預(yù)測開始:
from kats.models.prophet import ProphetModel, ProphetParams # Specify parameters params = ProphetParams(seasonality_mode="multiplicative") # Create a model instance m = ProphetModel(ts, params) # Fit mode m.fit() # Forecast fcst = m.predict(steps=30, freq="MS") fcst
可視化
m.plot()
酷!讓我們通過與測試數(shù)據(jù)的比較來評估預(yù)測。
import matplotlib.pyplot as plt fig, ax = plt.subplots(figsize=(12, 7)) train.plot(ax=ax, label="train", color="black") test.plot(ax=ax, color="black") fcst.plot(x="time", y="fcst", ax=ax, color="blue") ax.fill_between(test.index, fcst["fcst_lower"], fcst["fcst_upper"], alpha=0.5) ax.get_legend().remove()
預(yù)報(bào)似乎很好地符合觀察結(jié)果!
Holt-Winters
我們將嘗試的下一個(gè)模式是Holt-Winters。它是一種捕捉季節(jié)性的方法。下面是如何在 Kats 中使用 Holt-Winters 方法。
from kats.models.holtwinters import HoltWintersParams, HoltWintersModel import warnings warnings.simplefilter(action='ignore') params = HoltWintersParams( trend="add", seasonal="mul", seasonal_periods=12, ) m = HoltWintersModel( data=ts, params=params) m.fit() fcst = m.predict(steps=30, alpha = 0.1) m.plot()
檢測變化點(diǎn)
你有沒有想過在你的時(shí)間序列中發(fā)生統(tǒng)計(jì)上顯著的均值變化的時(shí)間?
Kats 允許使用 CUSUM 算法檢測變化點(diǎn)。Cusum 是一種檢測時(shí)間序列中均值上下移動(dòng)的方法。
讓我們看看如何檢測 Kats 中的變化點(diǎn)。
from kats.consts import TimeSeriesData, TimeSeriesIterator from kats.detectors.cusum_detection import CUSUMDetector import matplotlib.pyplot as plt detector = CUSUMDetector(ts) change_points = detector.detector(change_directions=["increase", "decrease"]) print("The change point is on", change_points[0][0].start_time) # plot the results plt.xticks(rotation=45) detector.plot(change_points) plt.show()
酷!讓我們嘗試檢測 StackOverflow 問題計(jì)數(shù)的其他類別的變化點(diǎn)。
首先創(chuàng)建一個(gè)函數(shù)來檢測主題提供的更改點(diǎn)。
def get_ts(topic: str): return TimeSeriesData(df[topic].to_frame().reset_index(), time_col_name="month") def detect_change_point(topic: str): ts = get_ts(topic) detector = CUSUMDetector(ts) change_points = detector.detector() for change_point in change_points: print("The change point is on", change_point[0].start_time) # plot the results plt.xticks(rotation=45) detector.plot(change_points) plt.show()
機(jī)器學(xué)習(xí)
detect_change_point("machine-learning")
深度學(xué)習(xí)
detect_change_point("deep-learning")
孤立點(diǎn)檢測
你在看NLP的時(shí)間序列時(shí)看到了什么?
df["nlp"].plot()
從2018年到2019年,NLP的問題數(shù)量有所下降。
問題數(shù)量的下降是一個(gè)異常值。檢測異常值很重要,因?yàn)樗鼈兛赡軙?huì)在下游處理中造成問題。
然而,通過查看數(shù)據(jù)來發(fā)現(xiàn)異常值并不總是高效和容易的。幸運(yùn)的是,Kats還允許您檢測時(shí)間序列中的異常值!
用kat檢測異常值只需要幾行行代碼。
from kats.detectors.outlier import OutlierDetector # Get time series object ts = get_ts("nlp") # Detect outliers ts_outlierDetection = OutlierDetector(ts, "additive") ts_outlierDetection.detector() # Print outliers outlier_range1 = ts_outlierDetection.outliers[0] print(f"The outliers range from {outlier_range1[0]} to {outlier_range1[1]}")
The outliers range from 2018-01-01 00:00:00 to 2019-03-01 00:00:00
酷!結(jié)果證實(shí)了我們從上圖中看到的情況。
時(shí)間序列特征
除了統(tǒng)計(jì)數(shù)據(jù)外,時(shí)間序列中還有其他一些特性,如線性、趨勢強(qiáng)度、季節(jié)性強(qiáng)度、季節(jié)性參數(shù)等,您可能會(huì)感興趣。
Kats 允許通過 TsFeatures 查找有關(guān)時(shí)間序列特征的重要信息:
from kats.tsfeatures.tsfeatures import TsFeatures model = TsFeatures() output_features = model.transform(ts) output_features
小結(jié)
我們剛剛學(xué)習(xí)了如何使用 Kats 來預(yù)測、檢測變化點(diǎn)、檢測異常值和提取時(shí)間序列特征。我希望這篇文章能幫助到大家解決工作中的時(shí)間序列問題,并從數(shù)據(jù)中提取有價(jià)值的信息。
以上就是Facebook開源一站式服務(wù)python時(shí)序利器Kats詳解的詳細(xì)內(nèi)容,更多關(guān)于Facebook開源時(shí)序利器Kats的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Pytest初學(xué)者快速上手高效Python測試指南
這篇文章主要為大家介紹了Pytest初學(xué)者快速上手的高效Python測試指南,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2024-01-01Empty test suite.(PyCharm程序運(yùn)行錯(cuò)誤的解決方法)
今天小編就為大家分享一篇Empty test suite.(PyCharm程序運(yùn)行錯(cuò)誤的解決方法),具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-11-11Python使用psutil庫對系統(tǒng)數(shù)據(jù)進(jìn)行采集監(jiān)控的方法
利用psutil庫可以獲取系統(tǒng)的一些信息,如cpu,內(nèi)存等使用率,從而可以查看當(dāng)前系統(tǒng)的使用情況,實(shí)時(shí)采集這些信息可以達(dá)到實(shí)時(shí)監(jiān)控系統(tǒng)的目的。本文給大家介紹Python psutil系統(tǒng)監(jiān)控的相關(guān)知識,感興趣的朋友一起看看吧2021-08-08python利用paramiko連接遠(yuǎn)程服務(wù)器執(zhí)行命令的方法
下面小編就為大家?guī)硪黄猵ython利用paramiko連接遠(yuǎn)程服務(wù)器執(zhí)行命令的方法。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-10-10python的launcher用法知識點(diǎn)總結(jié)
在本篇文章里小編給大家整理的是一篇關(guān)于python的launcher用法知識點(diǎn)總結(jié)內(nèi)容,有興趣的朋友們可以學(xué)習(xí)下。2020-08-08