快速开始
安装 tsfresh
由于编译后的 tsfresh 包托管在 Python Package Index (PyPI) 上,您可以使用 pip 轻松安装它
pip install tsfresh
如果您需要处理可能不适合内存的大型时间序列数据,请使用 Dask 安装 tsfresh
pip install tsfresh[dask]
另请参阅 大型输入数据。
深入了解
在详细阅读文档之前,您可以直接通过以下示例深入了解 tsfresh
我们得到一个包含机器人故障的数据集,如 [1] 中所述。每个机器人记录来自六个不同传感器的时间序列。对于由不同 id 表示的每个样本,我们将分类机器人是否报告故障。从机器学习的角度来看,我们的目标是分类每组时间序列。
首先,我们将数据加载到 python 中
from tsfresh.examples.robot_execution_failures import download_robot_execution_failures, \
    load_robot_execution_failures
download_robot_execution_failures()
timeseries, y = load_robot_execution_failures()
并得到一个形状如下的 pandas.DataFrame timeseries
print(timeseries.head())
| id | time | F_x | F_y | F_z | T_x | T_y | T_z | |
|---|---|---|---|---|---|---|---|---|
| 0 | 1 | 0 | -1 | -1 | 63 | -3 | -1 | 0 | 
| 1 | 1 | 1 | 0 | 0 | 62 | -3 | -1 | 0 | 
| 2 | 1 | 2 | -1 | -1 | 61 | -3 | 0 | 0 | 
| 3 | 1 | 3 | -1 | -1 | 63 | -2 | -1 | 0 | 
| 4 | 1 | 4 | -1 | -1 | 63 | -3 | -1 | 0 | 
| … | … | … | … | … | … | … | … | … | 
第一列是 DataFrame 索引,在此没有意义。不同传感器有六个不同的时间序列(F_x, F_y, F_z, T_x, T_y, T_z)。不同的机器人由 ids 列表示。
另一方面,y 包含哪个机器人 id 报告了故障而哪个没有的信息
| 1 | 0 | 
| 2 | 0 | 
| 3 | 0 | 
| 4 | 0 | 
| 5 | 0 | 
| … | … | 
这里,ids 为 1 到 5 的样本没有报告故障。
下面我们展示 id 为 3 的样本报告无故障的时间序列
import matplotlib.pyplot as plt
timeseries[timeseries['id'] == 3].plot(subplots=True, sharex=True, figsize=(10,10))
plt.show()
 
以及 id 为 20 的样本报告故障的时间序列
timeseries[timeseries['id'] == 20].plot(subplots=True, sharex=True, figsize=(10,10))
plt.show()
 
您已经可以通过肉眼看到一些差异 - 但为了成功的机器学习,我们需要将这些差异转化为数字。
为此,tsfresh 应运而生。它允许我们自动为每个机器人从这六个不同的时间序列中提取超过 1200 个特征。
要提取所有特征,我们执行以下操作
from tsfresh import extract_features
extracted_features = extract_features(timeseries, column_id="id", column_sort="time")
您将得到一个包含 1200 多个不同提取特征的 DataFrame extracted_features。现在我们将首先移除所有 NaN 值(这些值是由无法用于给定数据的特征计算器生成的,例如,因为统计量过低),然后只选择相关的特征
from tsfresh import select_features
from tsfresh.utilities.dataframe_functions import impute
impute(extracted_features)
features_filtered = select_features(extracted_features, y)
只有大约 300 个特征被认为足够相关。
此外,您甚至可以使用 tsfresh.extract_relevant_features() 函数同时执行特征提取、填充和过滤
from tsfresh import extract_relevant_features
features_filtered_direct = extract_relevant_features(timeseries, y,
                                                     column_id='id', column_sort='time')
您现在可以使用 DataFrame features_filtered (与 features_filtered_direct 相同) 中的特征结合 y 来训练您的分类模型。您可以在 Jupyter notebook 01 Feature Extraction and Selection.ipynb 中找到一个示例,我们在其中使用提取的特征训练了一个 RandomForestClassifier。
参考资料