Facebook開(kāi)源一站式服務(wù)python時(shí)序利器Kats詳解
轉(zhuǎn)自微信公眾號(hào):機(jī)器學(xué)習(xí)社區(qū),經(jīng)作者授權(quán)轉(zhuǎn)載
時(shí)間序列分析是數(shù)據(jù)科學(xué)中一個(gè)非常重要的領(lǐng)域,它主要包含統(tǒng)計(jì)分析、檢測(cè)變化點(diǎn)、異常檢測(cè)和預(yù)測(cè)未來(lái)趨勢(shì)。然而,這些時(shí)間序列技術(shù)通常由不同的庫(kù)實(shí)現(xiàn)。有沒(méi)有一種方法可以讓你在一個(gè)庫(kù)中獲得所有這些技術(shù)?
答案是肯定的,本文中我將分享一個(gè)非常棒的工具包 Kats,它可以完美解決上述問(wèn)題。
什么是 Kats?
目前時(shí)間序列分析以及建模的技術(shù)非常多,但相對(duì)散亂,本次 FaceBook 開(kāi)源了 Kats,它是一款輕量級(jí)的、易于使用的、通用的時(shí)間序列分析框架,包括:預(yù)測(cè)、異常檢測(cè)、多元分析和特征提取嵌入。你可以將 Kats 視為 Python 中時(shí)間序列分析的一站式工具包。
安裝 Kats
pip install --upgrade pip pip install kats
為了了解 Kats 的功能,我們將使用這個(gè)框架來(lái)分析 Kaggle 上的 StackOverflow問(wèn)題計(jì)數(shù)問(wèn)題。數(shù)據(jù)鏈接為:https://www.kaggle.com/aishu200023/stackindex
首先我們從讀取數(shù)據(jù)開(kāi)始。
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 問(wèn)題計(jì)數(shù)。數(shù)據(jù)被分成一列和一個(gè)測(cè)試集來(lái)評(píng)估預(yù)測(cè)。
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í)間序列對(duì)象。我們使用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"])
酷!看起來(lái)關(guān)于 Python 的問(wèn)題的數(shù)量隨著時(shí)間的推移而增加。我們能預(yù)測(cè)未來(lái)30天的趨勢(shì)嗎?是的,我們可以和 Kats 一起做。
預(yù)測(cè)
Kats目前支持以下10種預(yù)測(cè)模型:
Linear
Quadratic
ARIMA
SARIMA
Holt-Winters
Prophet
AR-Net
LSTM
Theta
VAR
上述模型較多,讓我們?cè)囈幌缕渲袃煞N類(lèi)型吧!
從使用 Prophet 進(jìn)行預(yù)測(cè)開(kāi)始:
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()
酷!讓我們通過(guò)與測(cè)試數(shù)據(jù)的比較來(lái)評(píng)估預(yù)測(cè)。
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)似乎很好地符合觀(guān)察結(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()
檢測(cè)變化點(diǎn)
你有沒(méi)有想過(guò)在你的時(shí)間序列中發(fā)生統(tǒng)計(jì)上顯著的均值變化的時(shí)間?
Kats 允許使用 CUSUM 算法檢測(cè)變化點(diǎn)。Cusum 是一種檢測(cè)時(shí)間序列中均值上下移動(dòng)的方法。
讓我們看看如何檢測(cè) 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()
酷!讓我們嘗試檢測(cè) StackOverflow 問(wèn)題計(jì)數(shù)的其他類(lèi)別的變化點(diǎn)。
首先創(chuàng)建一個(gè)函數(shù)來(lái)檢測(cè)主題提供的更改點(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)檢測(cè)
你在看NLP的時(shí)間序列時(shí)看到了什么?
df["nlp"].plot()
從2018年到2019年,NLP的問(wèn)題數(shù)量有所下降。
問(wèn)題數(shù)量的下降是一個(gè)異常值。檢測(cè)異常值很重要,因?yàn)樗鼈兛赡軙?huì)在下游處理中造成問(wèn)題。
然而,通過(guò)查看數(shù)據(jù)來(lái)發(fā)現(xiàn)異常值并不總是高效和容易的。幸運(yùn)的是,Kats還允許您檢測(cè)時(shí)間序列中的異常值!
用kat檢測(cè)異常值只需要幾行行代碼。
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í)間序列中還有其他一些特性,如線(xiàn)性、趨勢(shì)強(qiáng)度、季節(jié)性強(qiáng)度、季節(jié)性參數(shù)等,您可能會(huì)感興趣。
Kats 允許通過(guò) TsFeatures 查找有關(guān)時(shí)間序列特征的重要信息:
from kats.tsfeatures.tsfeatures import TsFeatures model = TsFeatures() output_features = model.transform(ts) output_features
小結(jié)
我們剛剛學(xué)習(xí)了如何使用 Kats 來(lái)預(yù)測(cè)、檢測(cè)變化點(diǎn)、檢測(cè)異常值和提取時(shí)間序列特征。我希望這篇文章能幫助到大家解決工作中的時(shí)間序列問(wèn)題,并從數(shù)據(jù)中提取有價(jià)值的信息。
以上就是Facebook開(kāi)源一站式服務(wù)python時(shí)序利器Kats詳解的詳細(xì)內(nèi)容,更多關(guān)于Facebook開(kāi)源時(shí)序利器Kats的資料請(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)站,禁止在非www.sddonglingsh.com所屬的服務(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處理。