时间序列分析包括检查随着时间推移收集的数据点,目的是确定可以为未来预测提供信息的模式和趋势。我们已经介绍过很多个时间序列分析库了,但是随着时间推移,新的库和更新也在不断的出现,所以本文将分享8个目前比较常用的,用于处理时间序列问题的Python/ target=_blank class=infotextkey>Python库。他们是tsfresh, autots, darts, atspy, kats, sktime, greykite。
Tsfresh在时间序列特征提取和选择方面功能强大。它旨在自动从时间序列数据中提取大量特征,并识别出最相关的特征。Tsfresh支持多种时间序列格式,可用于分类、聚类和回归等各种应用程序。
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)
autots是另一个用于时间序列预测的Python库:
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)
darts(Data Analytics and Real-Time Systems)有多种时间序列预测模型,包括ARIMA、Prophet、指数平滑的各种变体,以及各种深度学习模型,如LSTMs、gru和tcn。Darts还具有用于交叉验证、超参数调优和特征工程的内置方法。
darts的一个关键特征是能够进行概率预测。这意味着,不仅可以为每个时间步骤生成单点预测,还可以生成可能结果的分布,从而更全面地理解预测中的不确定性。
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()
atspy,可以简单地加载数据并指定要测试的模型,如下面的代码所示。
# 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)
该包提供了一组完全自动化的模型。包括:
kats (kit to Analyze Time Series)是一个由Facebook(现在的Meta)开发的Python库。这个库的三个核心特性是:
模型预测:提供了一套完整的预测工具,包括10+个单独的预测模型、集成、元学习模型、回溯测试、超参数调优和经验预测区间。
检测:Kats支持检测时间序列数据中的各种模式的函数,包括季节性、异常、变化点和缓慢的趋势变化。
特征提取和嵌入:Kats中的时间序列特征(TSFeature)提取模块可以生成65个具有明确统计定义的特征,可应用于大多数机器学习(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()
sktime是一个用于时间序列分析的库,它构建在scikit-learn之上,并遵循类似的API,可以轻松地在两个库之间切换。下面是如何使用Sktime进行时间序列分类的示例:
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))
greykite是LinkedIn发布的一个时间序列预测库。该库可以处理复杂的时间序列数据,并提供一系列功能,包括自动化特征工程、探索性数据分析、预测管道和模型调优。
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
我们可以看到,这些时间序列的库主要功能有2个方向,一个是特征的生成,另外一个就是多种时间序列预测模型的集成,所以无论是处理单变量还是多变量数据,它们都可以满足我们的需求,但是具体用那个还要看具体的需求和使用的习惯。