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

Python时间序列分析:使用TSFresh进行自动化特征提取

off999 2025-04-27 15:34 20 浏览 0 评论

TSFresh(基于可扩展假设检验的时间序列特征提取)是一个专门用于时间序列数据特征自动提取的框架。该框架提取的特征可直接应用于分类、回归和异常检测等机器学习任务。TSFresh通过自动化特征工程流程,显著提升了时间序列分析的效率。

自动化特征提取过程涉及处理数百个统计特征,包括均值、方差、偏度和自相关性等,并通过统计检验方法筛选出具有显著性的特征,同时剔除冗余特征。该框架支持单变量和多变量时间序列数据处理。

TSFresh工作流程

TSFresh的基本工作流程包含以下步骤:首先将数据转换为特定格式,然后使用extract_features函数进行特征提取,最后可选择性地使用select_features函数进行特征选择。

TSFresh要求输入数据采用长格式(Long Format),每个时间序列必须包含唯一的id标识列。

构建示例:生成100个特征的100组时间序列观测数据

import pandas as pd
import numpy as np
from tsfresh import extract_features
from tsfresh import select_features
from tsfresh.utilities.dataframe_functions import impute
from tsfresh.feature_extraction import EfficientFCParameters
from tsfresh.feature_extraction.feature_calculators import mean
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score, classification_report, confusion_matrix
import matplotlib.pyplot as plt
import seaborn as sns
# 构建大规模样本数据集
np.random.seed(42)
n_series = 100
n_timepoints = 100
time_series_list = []
for i in range(n_series):
frequency = np.random.uniform(0.5, 2)
phase = np.random.uniform(0, 2*np.pi)
noise_level = np.random.uniform(0.05, 0.2)

values = np.sin(frequency * np.linspace(0, 10, n_timepoints) + phase) + np.random.normal(0, noise_level, n_timepoints)

df = pd.DataFrame({
'id': i,
'time': range(n_timepoints),
'value': values
})
time_series_list.append(df)
time_series = pd.concat(time_series_list, ignore_index=True)
print("Original time series data:")
print(time_series.head())
print(f"Number of time series: {n_series}")
print(f"Number of timepoints per series: {n_timepoints}")

接下来对生成的数据进行可视化分析:

# 选择性可视化时间序列数据
plt.figure(figsize=(12, 6))
for i in range(5): # 绘制前5条时间序列
plt.plot(time_series[time_series['id'] == i]['time'], 
time_series[time_series['id'] == i]['value'], 
label=f'Series {i}')
plt.title('Sample of Time Series')
plt.xlabel('Time')
plt.ylabel('Value')
plt.legend()
plt.savefig("sample_TS.png")
plt.show()

数据展现出预期的随机性特征,这与实际时间序列数据的特性相符。

特征提取过程

数据呈现出典型的时间序列特征,包含噪声和波动。下面使用tsfresh.extract_features函数执行特征提取操作。

# 执行特征提取
features = extract_features(time_series, column_id="id", column_sort="time", n_jobs=0)
print("\nExtracted features:")
print(features.head())
# 对缺失值进行插补处理
features_imputed = impute(features)

输出示例(部分特征):

value__mean value__variance value__autocorrelation_lag_1 
id 
1 0.465421 0.024392 0.856201 
2 0.462104 0.023145 0.845318

特征选择

为提高模型效率,需要对提取的特征进行筛选。使用select_features函数基于统计显著性进行特征选择。

# 构造目标变量(基于频率的二分类)
target = pd.Series(index=range(n_series), dtype=int)
target[features_imputed.index % 2 == 0] = 0 # 偶数索引分类
target[features_imputed.index % 2 == 1] = 1 # 奇数索引分类
# 执行特征选择
selected_features = select_features(features_imputed, target)
# 特征选择结果处理
if selected_features.empty:
print("\nNo features were selected. Using all features.")
selected_features = features_imputed
else:
print("\nSelected features:")
print(selected_features.head())
print(f"\nNumber of features: {selected_features.shape[1]}")
print("\nNames of features (first 10):")
print(selected_features.columns.tolist()[:10])

此过程可有效筛选出与目标变量具有显著相关性的特征。

特征应用于监督学习

特征工程的主要目的是为机器学习模型提供有效的输入变量。TSFresh可与scikit-learn等主流机器学习库无缝集成。

以下展示了特征在分类任务中的应用实例:

# 分类模型构建
# 数据集划分
X_train_clf, X_test_clf, y_train_clf, y_test_clf = train_test_split(
selected_features, target, test_size=0.2, random_state=42
)
# 随机森林分类器训练
clf = RandomForestClassifier(random_state=42)
clf.fit(X_train_clf, y_train_clf)
# 模型评估
y_pred_clf = clf.predict(X_test_clf)
print("\nClassification Model Performance:")
print(f"Accuracy: {accuracy_score(y_test_clf, y_pred_clf):.2f}")
print("\nClassification Report:")
print(classification_report(y_test_clf, y_pred_clf))
# 混淆矩阵可视化
cm = confusion_matrix(y_test_clf, y_pred_clf)
plt.figure(figsize=(8, 6))
sns.heatmap(cm, annot=True, fmt='d', cmap='Blues')
plt.title('Confusion Matrix')
plt.xlabel('Predicted')
plt.ylabel('Actual')
plt.savefig("confusion_matrix.png")
plt.show()
# 特征重要性分析
feature_importance = pd.DataFrame({
'feature': X_train_clf.columns,
'importance': clf.feature_importances_
}).sort_values('importance', ascending=False)
print("\nTop 10 Most Important Features:")
print(feature_importance.head(10))
# 特征重要性可视化
plt.figure(figsize=(12, 6))
sns.barplot(x='importance', y='feature', data=feature_importance.head(20))
plt.title('Top 20 Most Important Features')
plt.xlabel('Importance')
plt.ylabel('Feature')
plt.savefig("feature_importance.png")
plt.show()

多变量时间序列处理

TSFresh支持对数据集中的多个变量同时进行特征提取。

# 多变量特征提取示例
# 添加新的时间序列变量
time_series["value2"] = time_series["value"] * 0.5 + np.random.normal(0, 0.05, len(time_series))
# 对多个变量进行特征提取
features_multivariate = extract_features(
time_series, 
column_id="id", 
column_sort="time", 
default_fc_parameters=EfficientFCParameters(),
n_jobs=0
)
print("\nMultivariate features:")
print(features_multivariate.head())

自定义特征提取方法

TSFresh框架允许通过
tsfresh.feature_extraction.feature_calculators模块定制特征提取函数。

# 多变量特征提取实现
# 构造附加时间序列变量
time_series["value2"] = time_series["value"] * 0.5 + np.random.normal(0, 0.05, len(time_series))
# 执行多变量特征提取
features_multivariate = extract_features(
time_series, 
column_id="id", 
column_sort="time", 
default_fc_parameters=EfficientFCParameters(),
n_jobs=0
)
print("\nMultivariate features:")
print(features_multivariate.head())

以下展示了使用matplotlib进行数据分布可视化:

# 计算时间序列均值特征
custom_features = time_series.groupby("id")["value"].apply(mean)
print("\nCustom features (mean of each time series, first 5):")
print(custom_features.head())
# 特征分布可视化
plt.figure(figsize=(10, 6))
sns.histplot(custom_features, kde=True)
plt.title('Distribution of Mean Values for Each Time Series')
plt.xlabel('Mean Value')
plt.ylabel('Count')
plt.savefig("dist_of_means_TS.png")
plt.show()
# 特征与目标变量关系可视化
plt.figure(figsize=(10, 6))
sns.scatterplot(x=custom_features, y=target)
plt.title('Relationship between Mean Values and Target')
plt.xlabel('Mean Value')
plt.ylabel('Target')
plt.savefig("means_v_target_TS.png")
plt.show()

总结

TSFresh在时间序列特征工程领域展现出显著优势。通过自动化特征生成机制,它为下游机器学习任务提供了丰富的特征输入。但是需要注意的是,大量自动生成的特征可能导致过拟合问题,这一方面仍需进一步的实证研究验证。

作者:Kyle Jones

相关推荐

python入门到脱坑经典案例—清空列表

在Python中,清空列表是一个基础但重要的操作。clear()方法是最直接的方式,但还有其他方法也可以实现相同效果。以下是详细说明:1.使用clear()方法(Python3.3+推荐)...

python中元组,列表,字典,集合删除项目方式的归纳

九三,君子终日乾乾,夕惕若,厉无咎。在使用python过程中会经常遇到这四种集合数据类型,今天就对这四种集合数据类型中删除项目的操作做个总结性的归纳。列表(List)是一种有序和可更改的集合。允许重复...

Linux 下海量文件删除方法效率对比,最慢的竟然是 rm

Linux下海量文件删除方法效率对比,本次参赛选手一共6位,分别是:rm、find、findwithdelete、rsync、Python、Perl.首先建立50万个文件$testfor...

数据结构与算法——链式存储(链表)的插入及删除,

持续分享嵌入式技术,操作系统,算法,c语言/python等,欢迎小友关注支持上篇文章我们讲述了链表的基本概念及一些查找遍历的方法,本篇我们主要将一下链表的插入删除操作,以及采用堆栈方式如何创建链表。链...

Python自动化:openpyxl写入数据,插入删除行列等基础操作

importopenpyxlwb=openpyxl.load_workbook("example1.xlsx")sh=wb['Sheet1']写入数据#...

在Linux下软件的安装与卸载(linux里的程序的安装与卸载命令)

通过apt安装/协助软件apt是AdvancedPackagingTool,是Linux下的一款安装包管理工具可以在终端中方便的安装/卸载/更新软件包命令使用格式:安装软件:sudoapt...

Python 批量卸载关联包 pip-autoremove

pip工具在安装扩展包的时候会自动安装依赖的关联包,但是卸载时只删除单个包,无法卸载关联的包。pip-autoremove就是为了解决卸载关联包的问题。安装方法通过下面的命令安装:pipinsta...

用Python在Word文档中插入和删除文本框

在当今自动化办公需求日益增长的背景下,通过编程手段动态管理Word文档中的文本框元素已成为提升工作效率的关键技术路径。文本框作为文档排版中灵活的内容容器,既能承载多模态信息(如文字、图像),又可实现独...

Python 从列表中删除值的多种实用方法详解

#Python从列表中删除值的多种实用方法详解在Python编程中,列表(List)是一种常用的数据结构,具有动态可变的特性。当我们需要从列表中删除元素时,根据不同的场景(如按值删除、按索引删除、...

Python 中的前缀删除操作全指南(python删除前导0)

1.字符串前缀删除1.1使用内置方法Python提供了几种内置方法来处理字符串前缀的删除:#1.使用removeprefix()方法(Python3.9+)text="...

每天学点Python知识:如何删除空白

在Python中,删除空白可以分为几种不同的情况,常见的是针对字符串或列表中空白字符的处理。一、删除字符串中的空白1.删除字符串两端的空白(空格、\t、\n等)使用.strip()方法:s...

Linux系统自带Python2&yum的卸载及重装

写在前面事情的起因是我昨天在测试Linux安装Python3的shell脚本时,需要卸载Python3重新安装一遍。但是通过如下命令卸载python3时,少写了个3,不小心将系统自带的python2也...

如何使用Python将多个excel文件数据快速汇总?

在数据分析和处理的过程中,Excel文件是我们经常会遇到的数据格式之一。本文将通过一个具体的示例,展示如何使用Python和Pandas库来读取、合并和处理多个Excel文件的数据,并最终生成一个包含...

【第三弹】用Python实现Excel的vlookup功能

今天继续用pandas实现Excel的vlookup功能,假设我们的2个表长成这样:我们希望把Sheet2的部门匹在Sheet1的最后一列。话不多说,先上代码:importpandasaspd...

python中pandas读取excel单列及连续多列数据

案例:想获取test.xls中C列、H列以后(当H列后列数未知时)的所有数据。importpandasaspdfile_name=r'D:\test.xls'#表格绝对...

取消回复欢迎 发表评论: