百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术文章 > 正文

7个最新的时间序列分析库介绍和代码示例

itomcoil 2024-12-18 14:55 59 浏览

时间序列分析包括检查随着时间推移收集的数据点,目的是确定可以为未来预测提供信息的模式和趋势。我们已经介绍过很多个时间序列分析库了,但是随着时间推移,新的库和更新也在不断的出现,所以本文将分享8个目前比较常用的,用于处理时间序列问题的Python库。他们是tsfresh, autots, darts, atspy, kats, sktime, greykite。

1、Tsfresh

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)

2、AutoTS

autots是另一个用于时间序列预测的Python库:

  • 提供了单变量和多变量时间序列预测的各种算法,包括ARIMA, ETS, Prophet和DeepAR。
  • 为最佳模型执行自动模型集成。
  • 提供了上界和下界的置信区间预测。
  • 通过学习最优NaN imputation和异常值去除来处理数据。
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)有多种时间序列预测模型,包括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()

4、AtsPy

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)

该包提供了一组完全自动化的模型。包括:

5、kats

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()

6、Sktime

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))

7、GreyKite

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个方向,一个是特征的生成,另外一个就是多种时间序列预测模型的集成,所以无论是处理单变量还是多变量数据,它们都可以满足我们的需求,但是具体用那个还要看具体的需求和使用的习惯。

作者:Joanna

相关推荐

selenium(WEB自动化工具)

定义解释Selenium是一个用于Web应用程序测试的工具。Selenium测试直接运行在浏览器中,就像真正的用户在操作一样。支持的浏览器包括IE(7,8,9,10,11),MozillaF...

开发利器丨如何使用ELK设计微服务中的日志收集方案?

【摘要】微服务各个组件的相关实践会涉及到工具,本文将会介绍微服务日常开发的一些利器,这些工具帮助我们构建更加健壮的微服务系统,并帮助排查解决微服务系统中的问题与性能瓶颈等。我们将重点介绍微服务架构中...

高并发系统设计:应对每秒数万QPS的架构策略

当面试官问及"如何应对每秒几万QPS(QueriesPerSecond)"时,大概率是想知道你对高并发系统设计的理解有多少。本文将深入探讨从基础设施到应用层面的解决方案。01、理解...

2025 年每个 JavaScript 开发者都应该了解的功能

大家好,很高兴又见面了,我是"高级前端进阶",由我带着大家一起关注前端前沿、深入前端底层技术,大家一起进步,也欢迎大家关注、点赞、收藏、转发。1.Iteratorhelpers开发者...

JavaScript Array 对象

Array对象Array对象用于在变量中存储多个值:varcars=["Saab","Volvo","BMW"];第一个数组元素的索引值为0,第二个索引值为1,以此类推。更多有...

Gemini 2.5编程全球霸榜,谷歌重回AI王座,神秘模型曝光,奥特曼迎战

刚刚,Gemini2.5Pro编程登顶,6美元性价比碾压Claude3.7Sonnet。不仅如此,谷歌还暗藏着更强的编程模型Dragontail,这次是要彻底翻盘了。谷歌,彻底打了一场漂亮的翻...

动力节点最新JavaScript教程(高级篇),深入学习JavaScript

JavaScript是一种运行在浏览器中的解释型编程语言,它的解释器被称为JavaScript引擎,是浏览器的一部分,JavaScript广泛用于浏览器客户端编程,通常JavaScript脚本是通过嵌...

一文看懂Kiro,其 Spec工作流秒杀Cursor,可移植至Claude Code

当Cursor的“即兴编程”开始拖累项目质量,AWS新晋IDEKiro以Spec工作流打出“先规范后编码”的系统工程思维:需求-设计-任务三件套一次生成,文档与代码同步落地,复杂项目不...

「晚安·好梦」努力只能及格,拼命才能优秀

欢迎光临,浏览之前点击上面的音乐放松一下心情吧!喜欢的话给小编一个关注呀!Effortscanonlypass,anddesperatelycanbeexcellent.努力只能及格...

JavaScript 中 some 与 every 方法的区别是什么?

大家好,很高兴又见面了,我是姜茶的编程笔记,我们一起学习前端相关领域技术,共同进步,也欢迎大家关注、点赞、收藏、转发,您的支持是我不断创作的动力在JavaScript中,Array.protot...

10个高效的Python爬虫框架,你用过几个?

小型爬虫需求,requests库+bs4库就能解决;大型爬虫数据,尤其涉及异步抓取、内容管理及后续扩展等功能时,就需要用到爬虫框架了。下面介绍了10个爬虫框架,大家可以学习使用!1.Scrapysc...

12个高效的Python爬虫框架,你用过几个?

实现爬虫技术的编程环境有很多种,Java、Python、C++等都可以用来爬虫。但很多人选择Python来写爬虫,为什么呢?因为Python确实很适合做爬虫,丰富的第三方库十分强大,简单几行代码便可实...

pip3 install pyspider报错问题解决

运行如下命令报错:>>>pip3installpyspider观察上面的报错问题,需要安装pycurl。是到这个网址:http://www.lfd.uci.edu/~gohlke...

PySpider框架的使用

PysiderPysider是一个国人用Python编写的、带有强大的WebUI的网络爬虫系统,它支持多种数据库、任务监控、项目管理、结果查看、URL去重等强大的功能。安装pip3inst...

「机器学习」神经网络的激活函数、并通过python实现激活函数

神经网络的激活函数、并通过python实现whatis激活函数感知机的网络结构如下:左图中,偏置b没有被画出来,如果要表示出b,可以像右图那样做。用数学式来表示感知机:上面这个数学式子可以被改写:...