Python时间序列分析:使用TSFresh进行自动化特征提取
off999 2025-04-27 15:34 42 浏览 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-fire 快速构建 CLI_如何搭建python项目架构
-
命令行应用程序是开发人员最好的朋友。想快速完成某事?只需敲击几下键盘,您就已经拥有了想要的东西。Python是许多开发人员在需要快速组合某些东西时选择的第一语言。但是我们拼凑起来的东西在大多数时候并...
- Python 闭包:从底层逻辑到实战避坑,附安全防护指南
-
一、闭包到底是什么?你可以把闭包理解成一个"带记忆的函数"。它诞生时会悄悄记下自己周围的变量,哪怕跑到别的地方执行,这些"记忆"也不会丢失。就像有人出门时总会带上...
- 使用Python实现九九乘法表的打印_用python打印一个九九乘法表
-
任务要求九九乘法表的结构如下:1×1=11×2=22×2=41×3=32×3=63×3=9...1×9=92×9=18...9×9=81使用Python编写程序,按照上述格式打印出完整的九...
- 吊打面试官(四)--Java语法基础运算符一文全掌握
-
简介本文介绍了Java运算符相关知识,包含运算规则,运算符使用经验,特殊运算符注意事项等,全文5400字。熟悉了这些内容,在运算符这块就可以吊打面试官了。Java运算符的规则与特性1.贪心规则(Ma...
- Python三目运算基础与进阶_python三目运算符判断三个变量
-
#头条创作挑战赛#Python中你学会了三步运算,你将会省去很多无用的代码,我接下来由基础到进阶的方式讲解Python三目运算基础在Python中,三目运算符也称为条件表达式。它可以通过一行代码实现条...
- Python 中 必须掌握的 20 个核心函数——set()详解
-
set()是Python中用于创建集合的核心函数,集合是一种无序、不重复元素的容器,非常适合用于成员检测、去重和数学集合运算。一、set()的基本用法1.1创建空集合#创建空集合empty_se...
- 15个让Python编码效率翻倍的实用技巧
-
在软件开发领域,代码质量往往比代码数量更重要。本文整理的15个Python编码技巧,源自开发者在真实项目中验证过的工作方法,能够帮助您用更简洁的代码实现更清晰的逻辑。这些技巧覆盖基础语法优化到高级特性...
- 《Python从小白到入门》自学课程目录汇总(和猫妹学Python)
-
小朋友们好,大朋友们好!不知不觉,这套猫妹自学Python基础课程已经结束了,猫妹体会到了水滴石穿的力量。水一直向下滴,时间长了能把石头滴穿。只要坚持不懈,细微之力也能做出很难办的事。就比如咱们的学习...
- 8÷2(2+2) 等于1还是16?国外网友为这道小学数学题吵疯了……
-
近日,国外网友因为一道小学数学题在推特上争得热火朝天。事情的起因是一个推特网友@pjmdoll发布了一条推文,让他的关注者解答一道数学题:Viralmathequationshavebeen...
- Python学不会来打我(21)python表达式知识点汇总
-
在Python中,表达式是由变量、运算符、函数调用等组合而成的语句,用于产生值或执行特定操作。以下是对Python中常见表达式的详细讲解:1.1算术表达式涉及数学运算的表达式。例如:a=5b...
- Python运算符:数学助手,轻松拿咧
-
Python中的运算符就像是生活中的数学助手,帮助我们快速准确地完成这些计算。比如购物时计算总价、做家务时分配任务等。这篇文章就来详细聊聊Python中的各种运算符,并通过实际代码示例帮助你更好地理解...
- Python学不会来打我(17)逻辑运算符的使用方法与使用场景
-
在Python编程中,逻辑运算符(LogicalOperators)是用于组合多个条件表达式的关键工具。它们可以将多个布尔表达式连接起来,形成更复杂的判断逻辑,并返回一个布尔值(True或Fa...
- Python编程基础:运算符的优先级_python中的运算符优先级问题
-
多个运算符同时出现在一个表达式中时,先执行哪个,后执行哪个,这就涉及运算符的优先级。如数学表达式,有+、-、×、÷、()等,优先级顺序是()、×、÷、+、-,如5+(5-3)×4÷2,先计算(5-3)...
- Python运算符与表达式_python中运算符&的功能
-
一、运算符分类总览1.Python运算符全景图2.运算符优先级表表1.3.1Python运算符优先级(从高到低)优先级运算符描述结合性1**指数右→左2~+-位非/一元加减右→左3*//...
- Python操作Excel:从基础到高级的深度实践
-
Python凭借其丰富的库生态系统,已成为自动化处理Excel数据的强大工具。本文将深入探讨五个关键领域,通过实际代码示例展示如何利用Python进行高效的Excel操作,涵盖数据处理、格式控制、可视...
你 发表评论:
欢迎- 一周热门
- 最近发表
-
- 使用 python-fire 快速构建 CLI_如何搭建python项目架构
- Python 闭包:从底层逻辑到实战避坑,附安全防护指南
- 使用Python实现九九乘法表的打印_用python打印一个九九乘法表
- 吊打面试官(四)--Java语法基础运算符一文全掌握
- Python三目运算基础与进阶_python三目运算符判断三个变量
- Python 中 必须掌握的 20 个核心函数——set()详解
- 15个让Python编码效率翻倍的实用技巧
- 《Python从小白到入门》自学课程目录汇总(和猫妹学Python)
- 8÷2(2+2) 等于1还是16?国外网友为这道小学数学题吵疯了……
- Python学不会来打我(21)python表达式知识点汇总
- 标签列表
-
- python计时 (73)
- python安装路径 (56)
- python类型转换 (93)
- python进度条 (67)
- python吧 (67)
- python的for循环 (65)
- python格式化字符串 (61)
- python静态方法 (57)
- python列表切片 (59)
- python面向对象编程 (60)
- python 代码加密 (65)
- python串口编程 (77)
- python封装 (57)
- python写入txt (66)
- python读取文件夹下所有文件 (59)
- python操作mysql数据库 (66)
- python获取列表的长度 (64)
- python接口 (63)
- python调用函数 (57)
- python多态 (60)
- python匿名函数 (59)
- python打印九九乘法表 (65)
- python赋值 (62)
- python异常 (69)
- python元祖 (57)