時間序列分析包括檢查隨著時間推移收集的數(shù)據(jù)點(diǎn),目的是確定可以為未來預(yù)測提供信息的模式和趨勢。我們已經(jīng)介紹過很多個時間序列分析庫了,但是隨著時間推移,新的庫和更新也在不斷的出現(xiàn),所以本文將分享8個目前比較常用的,用于處理時間序列問題的Python/ target=_blank class=infotextkey>Python庫。他們是tsfresh, autots, darts, atspy, kats, sktime, greykite。
1、Tsfresh
Tsfresh在時間序列特征提取和選擇方面功能強(qiáng)大。它旨在自動從時間序列數(shù)據(jù)中提取大量特征,并識別出最相關(guān)的特征。Tsfresh支持多種時間序列格式,可用于分類、聚類和回歸等各種應(yīng)用程序。
import pandas as pd
from tsfresh import extract_features
from tsfresh.utilities.dataframe_functions import make_forecasting_frame
# Assume we have a time series dataset `data` with columns "time" and "value"
data = pd.read_csv('data.csv')
# We will use the last 10 points to predict the next point
df_shift, y = make_forecasting_frame(data["value"], kind="value", max_timeshift=10, rolling_direction=1)
# Extract relevant features using tsfresh
X = extract_features(df_shift, column_id="id", column_sort="time", column_value="value", impute_function=impute)
2、AutoTS
autots是另一個用于時間序列預(yù)測的Python庫:
- 提供了單變量和多變量時間序列預(yù)測的各種算法,包括ARIMA, ETS, Prophet和DeepAR。
- 為最佳模型執(zhí)行自動模型集成。
- 提供了上界和下界的置信區(qū)間預(yù)測。
- 通過學(xué)習(xí)最優(yōu)NaN imputation和異常值去除來處理數(shù)據(jù)。
from autots.datasets import load_monthly
df_long = load_monthly(long=True)
from autots import AutoTS
model = AutoTS(
forecast_length=3,
frequency='infer',
ensemble='simple',
max_generations=5,
num_validations=2,
)
model = model.fit(df_long, date_col='datetime', value_col='value', id_col='series_id')
# Print the description of the best model
print(model)
3、darts
darts(Data Analytics and Real-Time Systems)有多種時間序列預(yù)測模型,包括ARIMA、Prophet、指數(shù)平滑的各種變體,以及各種深度學(xué)習(xí)模型,如LSTMs、gru和tcn。Darts還具有用于交叉驗(yàn)證、超參數(shù)調(diào)優(yōu)和特征工程的內(nèi)置方法。
darts的一個關(guān)鍵特征是能夠進(jìn)行概率預(yù)測。這意味著,不僅可以為每個時間步驟生成單點(diǎn)預(yù)測,還可以生成可能結(jié)果的分布,從而更全面地理解預(yù)測中的不確定性。
import pandas as pd
import matplotlib.pyplot as plt
from darts import TimeSeries
from darts.models import ExponentialSmoothing
# Read data
df = pd.read_csv("AirPassengers.csv", delimiter=",")
# Create a TimeSeries, specifying the time and value columns
series = TimeSeries.from_dataframe(df, "Month", "#Passengers")
# Set aside the last 36 months as a validation series
train, val = series[:-36], series[-36:]
# Fit an exponential smoothing model, and make a (probabilistic)
# prediction over the validation series’ duration
model = ExponentialSmoothing()
model.fit(train)
prediction = model.predict(len(val), num_samples=1000)
# Plot the median, 5th and 95th percentiles
series.plot()
prediction.plot(label="forecast", low_quantile=0.05, high_quantile=0.95)
plt.legend()
4、AtsPy
atspy,可以簡單地加載數(shù)據(jù)并指定要測試的模型,如下面的代碼所示。
# Importing packages
import pandas as pd
from atspy import AutomatedModel
# Reading data
df = pd.read_csv("AirPassengers.csv", delimiter=",")
# Preprocessing data
data.columns = ['month','Passengers']
data['month'] = pd.to_datetime(data['month'],infer_datetime_format=True,format='%y%m')
data.index = data.month
df_air = data.drop(['month'], axis = 1)
# Select the models you want to run:
models = ['ARIMA','Prophet']
run_models = AutomatedModel(df = df_air, model_list=models, forecast_len=10)
該包提供了一組完全自動化的模型。包括:
5、kats
kats (kit to Analyze Time Series)是一個由Facebook(現(xiàn)在的Meta)開發(fā)的Python庫。這個庫的三個核心特性是:
模型預(yù)測:提供了一套完整的預(yù)測工具,包括10+個單獨(dú)的預(yù)測模型、集成、元學(xué)習(xí)模型、回溯測試、超參數(shù)調(diào)優(yōu)和經(jīng)驗(yàn)預(yù)測區(qū)間。
檢測:Kats支持檢測時間序列數(shù)據(jù)中的各種模式的函數(shù),包括季節(jié)性、異常、變化點(diǎn)和緩慢的趨勢變化。
特征提取和嵌入:Kats中的時間序列特征(TSFeature)提取模塊可以生成65個具有明確統(tǒng)計(jì)定義的特征,可應(yīng)用于大多數(shù)機(jī)器學(xué)習(xí)(ML)模型,如分類和回歸。
# pip install kats
import pandas as pd
from kats.consts import TimeSeriesData
from kats.models.prophet import ProphetModel, ProphetParams
# Read data
df = pd.read_csv("AirPassengers.csv", names=["time", "passengers"])
# Convert to TimeSeriesData object
air_passengers_ts = TimeSeriesData(air_passengers_df)
# Create a model param instance
params = ProphetParams(seasonality_mode='multiplicative')
# Create a prophet model instance
m = ProphetModel(air_passengers_ts, params)
# Fit model simply by calling m.fit()
m.fit()
# Make prediction for next 30 month
forecast = m.predict(steps=30, freq="MS")
forecast.head()
6、Sktime
sktime是一個用于時間序列分析的庫,它構(gòu)建在scikit-learn之上,并遵循類似的API,可以輕松地在兩個庫之間切換。下面是如何使用Sktime進(jìn)行時間序列分類的示例:
from sktime.datasets import load_arrow_head
from sktime.classification.compose import TimeSeriesForestClassifier
from sktime.utils.sampling import train_test_split
# Load ArrowHead dataset
X, y = load_arrow_head(return_X_y=True)
# Split data into train and test sets
X_train, X_test, y_train, y_test = train_test_split(X, y)
# Create and fit a time series forest classifier
classifier = TimeSeriesForestClassifier(n_estimators=100)
classifier.fit(X_train, y_train)
# Predict labels for the test set
y_pred = classifier.predict(X_test)
# Print classification report
from sklearn.metrics import classification_report
print(classification_report(y_test, y_pred))
7、GreyKite
greykite是LinkedIn發(fā)布的一個時間序列預(yù)測庫。該庫可以處理復(fù)雜的時間序列數(shù)據(jù),并提供一系列功能,包括自動化特征工程、探索性數(shù)據(jù)分析、預(yù)測管道和模型調(diào)優(yōu)。
from greykite.common.data_loader import DataLoader
from greykite.framework.templates.autogen.forecast_config import ForecastConfig
from greykite.framework.templates.autogen.forecast_config import MetadataParam
from greykite.framework.templates.forecaster import Forecaster
from greykite.framework.templates.model_templates import ModelTemplateEnum
# Defines inputs
df = DataLoader().load_bikesharing().tail(24*90) # Input time series (pandas.DataFrame)
config = ForecastConfig(
metadata_param=MetadataParam(time_col="ts", value_col="count"), # Column names in `df`
model_template=ModelTemplateEnum.AUTO.name, # AUTO model configuration
forecast_horizon=24, # Forecasts 24 steps ahead
coverage=0.95, # 95% prediction intervals
)
# Creates forecasts
forecaster = Forecaster()
result = forecaster.run_forecast_config(df=df, config=config)
# Accesses results
result.forecast # Forecast with metrics, diagnostics
result.backtest # Backtest with metrics, diagnostics
result.grid_search # Time series CV result
result.model # Trained model
result.timeseries # Processed time series with plotting functions
總結(jié)
我們可以看到,這些時間序列的庫主要功能有2個方向,一個是特征的生成,另外一個就是多種時間序列預(yù)測模型的集成,所以無論是處理單變量還是多變量數(shù)據(jù),它們都可以滿足我們的需求,但是具體用那個還要看具體的需求和使用的習(xí)慣。