Python中的时间序列库比较与应用

2025年03月06日 由 alex 发表 5005 0

在Python中进行时间序列分析有许多选择,每种选择都有其自身的优势和劣势。这种多样性提供了灵活性,但也可能导致在选择使用哪些工具时感到困惑。最佳选择取决于你项目的需求和限制。本指南通过一个使用能源需求数据的实际示例,展示了如何选择合适的时间序列库。


理解项目需求

选择合适的工具首先要从理解你的分析需求开始。你是在探索模式、预测未来值,还是构建机器学习模型?每个目标都需要不同的方法和工具集。


在本示例中,我们分析能源需求数据,以检测趋势、季节性和异常值。我们还希望构建预测模型并评估其性能。这种端到端的分析涉及数据操作、统计测试、可视化、特征工程和预测。


使用Pandas和NumPy进行基本数据处理

每次时间序列分析都从Pandas和NumPy开始。这些库对于数据操作和数值计算至关重要。在这里,我们模拟了一整年的每小时能源需求数据,以演示不同的时间序列技术。


import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from statsmodels.tsa.seasonal import seasonal_decompose
import seaborn as sns
from sklearn.preprocessing import StandardScaler
# Load the ERCOT dataset and parse dates
df = pd.read_csv("ercot_load_data.csv", parse_dates=['date'])
# Set the date column as the index
df.set_index('date', inplace=True)
# Resample to hourly data by taking the mean
df = df.resample('h').mean().dropna()
# Basic line plot of energy demand over time
plt.figure(figsize=(12, 6))
plt.plot(df.index, df['values'], label='Demand')
plt.title('Energy Demand Over Time (Hourly)')
plt.xlabel('Date')
plt.ylabel('Demand (MW)')
plt.tight_layout()
# Customization: No top and right spines, no grid lines
plt.gca().spines['top'].set_visible(False)
plt.gca().spines['right'].set_visible(False)
plt.grid(False)
plt.savefig('ercot_demand_plot.png')
plt.show()


6


这个数据集捕捉到了每日和每周的周期,以及随机波动,这些都是实际能源需求数据中常见的现象。


使用Statsmodels进行统计分析

Statsmodels是一个用于统计分析和假设检验的常用库。它提供了季节性分解和平稳性测试的工具,这些工具帮助我们理解时间序列数据的结构和特征。


# Seasonal decomposition
decomposition = seasonal_decompose(df['values'], period=24, model='additive')
plt.figure(figsize=(12, 10))
plt.subplot(311)
plt.plot(df.index, decomposition.trend, label='Trend', color='blue')
plt.title('Trend Component')
plt.gca().spines['top'].set_visible(False)
plt.gca().spines['right'].set_visible(False)
plt.subplot(312)
plt.plot(df.index, decomposition.seasonal, label='Seasonality', color='green')
plt.title('Seasonal Component')
plt.gca().spines['top'].set_visible(False)
plt.gca().spines['right'].set_visible(False)
plt.subplot(313)
plt.plot(df.index, decomposition.resid, label='Residual', color='red')
plt.title('Residual Component')
plt.gca().spines['top'].set_visible(False)
plt.gca().spines['right'].set_visible(False)
plt.tight_layout()
plt.savefig('seasonal_decomposition_ercot.png')
plt.show()


7


季节性分解将时间序列分为趋势、季节性和残差成分。迪基-富勒(Dickey-Fuller)检验用于检查平稳性,这对许多统计模型至关重要。


与Scikit-Learn的机器学习集成

Scikit-learn是传统统计模型与现代机器学习之间的桥梁。它提供了特征工程、缩放和模型评估的工具。在这里,我们通过提取一天中的小时和一周中的天数等特征,为机器学习准备数据。


# Feature engineering for ML
df['hour'] = df.index.hour
df['day_of_week'] = df.index.dayofweek
scaler = StandardScaler()
scaled_features = scaler.fit_transform(df[['values', 'hour', 'day_of_week']])
scaled_df = pd.DataFrame(scaled_features, columns=['values', 'hour', 'day_of_week'])
plt.figure(figsize=(15, 10))
plt.subplot(221)
sns.boxplot(x=df['hour'], y=df['values'])
plt.title('Demand by Hour')
plt.xlabel('Hour of Day')
plt.ylabel('Demand (MW)')
plt.gca().spines['top'].set_visible(False)
plt.gca().spines['right'].set_visible(False)
plt.subplot(222)
sns.boxplot(x=df['day_of_week'], y=df['values'])
plt.title('Demand by Day of Week')
plt.xlabel('Day of Week (0=Monday)')
plt.ylabel('Demand (MW)')
plt.gca().spines['top'].set_visible(False)
plt.gca().spines['right'].set_visible(False)
plt.subplot(223)
correlation_matrix = scaled_df.corr()
sns.heatmap(correlation_matrix, annot=True, cmap='coolwarm', center=0)
plt.title('Correlation Matrix')
plt.gca().spines['top'].set_visible(False)
plt.gca().spines['right'].set_visible(False)
plt.subplot(224)
sns.histplot(scaled_df['values'], kde=True)
plt.title('Distribution of Scaled Demand')
plt.xlabel('Standardized Demand')
plt.ylabel('Count')
plt.gca().spines['top'].set_visible(False)
plt.gca().spines['right'].set_visible(False)
plt.tight_layout()
plt.savefig('feature_analysis_ercot.png')
plt.show()


8


这些可视化揭示了需求、一天中的时间和一周中的天数之间的关系,这些信息对于构建预测模型非常有用。


使用Prophet进行自动化预测

Prophet旨在以最少的配置快速、自动地进行预测。它能够高效地处理缺失数据、异常值和季节性模式。


from prophet import Prophet
def prophet_forecast(df, periods=24):
    df=df.reset_index()
    prophet_df = df[["date","values"]]
    prophet_df.rename(columns={'date': 'ds', 'values': 'y'}, inplace=True)
    model = Prophet(daily_seasonality=True, weekly_seasonality=True)
    model.fit(prophet_df)
    future = model.make_future_dataframe(periods=periods, freq='h')
    forecast = model.predict(future)
    return forecast, model
prophet_results, m = prophet_forecast(df)
fig = m.plot_components(prophet_results)
fig.set_size_inches(15, 10)
plt.tight_layout()
plt.savefig('prophet_components.png')
plt.show()


9


Prophet能够自动检测每日和每周的季节性,使其适用于季节性因素至关重要的商业应用。


使用Darts进行高级时间序列分析

Darts为复杂的时间序列任务提供了统一的接口,包括预测、特征提取和异常检测。它支持从统计模型到深度学习模型的一系列模型。


from darts import TimeSeries
from darts.models import ExponentialSmoothing
# Set date as index and resample to hourly mean
df.set_index('date', inplace=True)   
df = df.resample('h').mean().dropna() 
df.reset_index(inplace=True)  
# Convert to Darts TimeSeries
series = TimeSeries.from_dataframe(df, time_col='date', value_cols='values')
# Create and train model
model = ExponentialSmoothing()
model.fit(series)
# Generate forecast for the next 24 hours
forecast = model.predict(24)
# Plotting
plt.figure(figsize=(15, 8))
series.plot(label='Actual')
forecast.plot(label='Forecast')
plt.title('Energy Demand Forecast (Exponential Smoothing)')
plt.xlabel('Time')
plt.ylabel('Demand')
plt.legend()
plt.grid(False)
plt.tight_layout()
plt.savefig('forecast_comparison.png')
plt.show()


10


Darts通过在一个框架中集成数据处理、建模和评估,简化了复杂的工作流程。


做出正确选择

选择合适的时间序列库取决于你的目标:

  • 使用Pandas和NumPy进行数据操作和基本分析。
  • 使用Statsmodels进行统计分析和传统建模。
  • 使用Scikit-learn进行机器学习和特征工程。
  • 使用Prophet进行自动化的快速启动预测。
  • 使用Darts进行高级建模和深度学习集成。


最佳方法通常涉及同时使用多个库。例如,你可以使用Pandas进行数据操作,使用Statsmodels进行探索性分析,使用Darts进行高级预测。了解每个库的优势和局限性,使你能够构建灵活且稳健的时间序列解决方案。

文章来源:https://medium.com/@kylejones_47003/using-different-time-series-libraryies-in-python-220d6944c45d
欢迎关注ATYUN官方公众号
商务合作及内容投稿请联系邮箱:bd@atyun.com
评论 登录
热门职位
Maluuba
20000~40000/月
Cisco
25000~30000/月 深圳市
PilotAILabs
30000~60000/年 深圳市
写评论取消
回复取消