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

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

off999 2025-04-27 15:34 67 浏览 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

相关推荐

阿里云国际站ECS:阿里云ECS如何提高网站的访问速度?

TG:@yunlaoda360引言:速度即体验,速度即业务在当今数字化的世界中,网站的访问速度已成为决定用户体验、用户留存乃至业务转化率的关键因素。页面加载每延迟一秒,都可能导致用户流失和收入损失。对...

高流量大并发Linux TCP性能调优_linux 高并发网络编程

其实主要是手里面的跑openvpn服务器。因为并没有明文禁p2p(哎……想想那么多流量好像不跑点p2p也跑不完),所以造成有的时候如果有比较多人跑BT的话,会造成VPN速度急剧下降。本文所面对的情况为...

性能测试100集(12)性能指标资源使用率

在性能测试中,资源使用率是评估系统硬件效率的关键指标,主要包括以下四类:#性能测试##性能压测策略##软件测试#1.CPU使用率定义:CPU处理任务的时间占比,计算公式为1-空闲时间/总...

Linux 服务器常见的性能调优_linux高性能服务端编程

一、Linux服务器性能调优第一步——先搞懂“看什么”很多人刚接触Linux性能调优时,总想着直接改配置,其实第一步该是“看清楚问题”。就像医生看病要先听诊,调优前得先知道服务器“哪里...

Nginx性能优化实战:手把手教你提升10倍性能!

关注△mikechen△,十余年BAT架构经验倾囊相授!Nginx是大型架构而核心,下面我重点详解Nginx性能@mikechen文章来源:mikechen.cc1.worker_processe...

高并发场景下,Spring Cloud Gateway如何抗住百万QPS?

关注△mikechen△,十余年BAT架构经验倾囊相授!大家好,我是mikechen。高并发场景下网关作为流量的入口非常重要,下面我重点详解SpringCloudGateway如何抗住百万性能@m...

Kubernetes 高并发处理实战(可落地案例 + 源码)

目标场景:对外提供HTTPAPI的微服务在短时间内收到大量请求(例如每秒数千至数万RPS),要求系统可弹性扩容、限流降级、缓存减压、稳定运行并能自动恢复。总体思路(多层防护):边缘层:云LB...

高并发场景下,Nginx如何扛住千万级请求?

Nginx是大型架构的必备中间件,下面我重点详解Nginx如何实现高并发@mikechen文章来源:mikechen.cc事件驱动模型Nginx采用事件驱动模型,这是Nginx高并发性能的基石。传统...

Spring Boot+Vue全栈开发实战,中文版高清PDF资源

SpringBoot+Vue全栈开发实战,中文高清PDF资源,需要的可以私我:)SpringBoot致力于简化开发配置并为企业级开发提供一系列非业务性功能,而Vue则采用数据驱动视图的方式将程序...

Docker-基础操作_docker基础实战教程二

一、镜像1、从仓库获取镜像搜索镜像:dockersearchimage_name搜索结果过滤:是否官方:dockersearch--filter="is-offical=true...

你有空吗?跟我一起搭个服务器好不好?

来人人都是产品经理【起点学院】,BAT实战派产品总监手把手系统带你学产品、学运营。昨天闲的没事的时候,随手翻了翻写过的文章,发现一个很严重的问题。就是大多数时间我都在滔滔不绝的讲理论,却很少有涉及动手...

部署你自己的 SaaS_saas如何部署

部署你自己的VPNOpenVPN——功能齐全的开源VPN解决方案。(DigitalOcean教程)dockovpn.io—无状态OpenVPNdockerized服务器,不需要持久存储。...

Docker Compose_dockercompose安装

DockerCompose概述DockerCompose是一个用来定义和管理多容器应用的工具,通过一个docker-compose.yml文件,用YAML格式描述服务、网络、卷等内容,...

京东T7架构师推出的电子版SpringBoot,从构建小系统到架构大系统

前言:Java的各种开发框架发展了很多年,影响了一代又一代的程序员,现在无论是程序员,还是架构师,使用这些开发框架都面临着两方面的挑战。一方面是要快速开发出系统,这就要求使用的开发框架尽量简单,无论...

Kubernetes (k8s) 入门学习指南_k8s kubeproxy

Kubernetes(k8s)入门学习指南一、什么是Kubernetes?为什么需要它?Kubernetes(k8s)是一个开源的容器编排系统,用于自动化部署、扩展和管理容器化应用程序。它...

取消回复欢迎 发表评论: