工夫序列剖析包含查看随着时间推移收集的数据点,目标是确定能够为将来预测提供信息的模式和趋势。咱们曾经介绍过很多个工夫序列剖析库了,然而随着时间推移,新的库和更新也在一直的呈现,所以本文将分享 8 个目前比拟罕用的,用于解决工夫序列问题的 Python 库。他们是 tsfresh, autots, darts, atspy, kats, sktime, greykite。
1、Tsfresh
Tsfresh 在工夫序列特征提取和抉择方面功能强大。它旨在主动从工夫序列数据中提取大量特色,并辨认出最相干的特色。Tsfresh 反对多种工夫序列格局,可用于分类、聚类和回归等各种应用程序。
importpandasaspd
fromtsfreshimportextract_features
fromtsfresh.utilities.dataframe_functionsimportmake_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 是另一个用于工夫序列预测的 Python 库:
- 提供了单变量和多变量工夫序列预测的各种算法,包含 ARIMA, ETS, Prophet 和 DeepAR。
- 为最佳模型执行主动模型集成。
- 提供了上界和下界的置信区间预测。
- 通过学习最优 NaN imputation 和异样值去除来解决数据。
fromautots.datasetsimportload_monthly
df_long=load_monthly(long=True)
fromautotsimportAutoTS
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)有多种工夫序列预测模型,包含 ARIMA、Prophet、指数平滑的各种变体,以及各种深度学习模型,如 LSTMs、gru 和 tcn。Darts 还具备用于穿插验证、超参数调优和特色工程的内置办法。
darts 的一个要害特色是可能进行概率预测。这意味着,不仅能够为每个工夫步骤生成单点预测,还能够生成可能后果的散布,从而更全面地了解预测中的不确定性。
importpandasaspd
importmatplotlib.pyplotasplt
fromdartsimportTimeSeries
fromdarts.modelsimportExponentialSmoothing
# 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,能够简略地加载数据并指定要测试的模型,如上面的代码所示。
# Importing packages
importpandasaspd
fromatspyimportAutomatedModel
# 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(当初的 Meta)开发的 Python 库。这个库的三个外围个性是:
模型预测: 提供了一套残缺的预测工具,包含 10+ 个独自的预测模型、集成、元学习模型、回溯测试、超参数调优和教训预测区间。
检测:Kats 反对检测时间序列数据中的各种模式的函数,包含季节性、异样、变动点和迟缓的趋势变动。
特征提取和嵌入:Kats 中的工夫序列特色 (TSFeature) 提取模块能够生成 65 个具备明确统计定义的特色,可利用于大多数机器学习 (ML) 模型,如分类和回归。
# pip install kats
importpandasaspd
fromkats.constsimportTimeSeriesData
fromkats.models.prophetimportProphetModel, 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 是一个用于工夫序列剖析的库,它构建在 scikit-learn 之上,并遵循相似的 API,能够轻松地在两个库之间切换。上面是如何应用 Sktime 进行工夫序列分类的示例:
fromsktime.datasetsimportload_arrow_head
fromsktime.classification.composeimportTimeSeriesForestClassifier
fromsktime.utils.samplingimporttrain_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
fromsklearn.metricsimportclassification_report
print(classification_report(y_test, y_pred))
7、GreyKite
greykite 是 LinkedIn 公布的一个工夫序列预测库。该库能够解决简单的工夫序列数据,并提供一系列性能,包含自动化特色工程、探索性数据分析、预测管道和模型调优。
fromgreykite.common.data_loaderimportDataLoader
fromgreykite.framework.templates.autogen.forecast_configimportForecastConfig
fromgreykite.framework.templates.autogen.forecast_configimportMetadataParam
fromgreykite.framework.templates.forecasterimportForecaster
fromgreykite.framework.templates.model_templatesimportModelTemplateEnum
# 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 个方向,一个是特色的生成,另外一个就是多种工夫序列预测模型的集成,所以无论是解决单变量还是多变量数据,它们都能够满足咱们的需要,然而具体用那个还要看具体的需要和应用的习惯。
https://avoid.overfit.cn/post/45451d119a154aeba72bf8dd3eaa9496
作者:Joanna