将时间序列与机器学习相结合

Python 中的时间序列机器学习

Chris Holdgraf

Fellow, Berkeley Institute for Data Science

了解我们的数据

  • 本课程所用数据集均可在网上免费获取
  • 网络上有很多可下载的数据集,我们将使用来自 Kaggle 的数据
Python 中的时间序列机器学习

心跳声学数据

  • 来自不同患者的多段心音录音
  • 部分为正常心音,部分存在异常
  • 数据由音频文件 + 每个文件的标签组成
  • 我们能找到"异常"心跳吗?
Python 中的时间序列机器学习

加载音频数据

from glob import glob
files = glob('data/heartbeat-sounds/files/*.wav')

print(files)
['data/heartbeat-sounds/proc/files/murmur__201101051104.wav',
 ...
 'data/heartbeat-sounds/proc/files/murmur__201101051114.wav']
Python 中的时间序列机器学习

读取音频数据

import librosa as lr
# `load` 接受音频文件路径
audio, sfreq = lr.load('data/heartbeat-sounds/proc/files/murmur__201101051104.wav')

print(sfreq)
2205

在此示例中,采样频率为 2205,表示每秒 2205 个样本

Python 中的时间序列机器学习

由样本推断时间

  • 若知道时间序列的采样率,就可得到每个数据点相对于首个数据点的时间戳
  • 注意:这假设采样率固定且没有丢失数据点
Python 中的时间序列机器学习

创建时间数组(I)

  • 为每个样本创建索引数组,并除以采样频率

      indices = np.arange(0, len(audio))
      time = indices / sfreq
    
Python 中的时间序列机器学习

创建时间数组(II)

  • 找到第 N-1 个数据点的时间戳。然后用 linspace() 从 0 插值到该时间

      final_time = (len(audio) - 1) / sfreq
      time = np.linspace(0, final_time, sfreq)
    
Python 中的时间序列机器学习

纽约证券交易所数据集

  • 该数据集包含 10 年的公司股价
  • 我们能否从历史记录中发现可用于预测未来股价的模式?
Python 中的时间序列机器学习

查看数据

data = pd.read_csv('path/to/data.csv')

data.columns
Index(['date', 'symbol', 'close', 'volume'], dtype='object')
data.head()
         date symbol       close       volume
0  2010-01-04   AAPL  214.009998  123432400.0
1  2010-01-04    ABT   54.459951   10829000.0
2  2010-01-04    AIG   29.889999    7750900.0
3  2010-01-04   AMAT   14.300000   18615100.0
4  2010-01-04   ARNC   16.650013   11512100.0
Python 中的时间序列机器学习

在 Pandas DataFrame 中处理时间序列

  • 可通过 dtypes 属性查看各列的数据类型
df['date'].dtypes
0    object
1    object
2    object
dtype: object
Python 中的时间序列机器学习

将一列转换为时间序列

  • 要将 DataFrame 中的某列视为时间序列,请使用 to_datetime()
df['date'] = pd.to_datetime(df['date'])

df['date']
0   2017-01-01
1   2017-01-02
2   2017-01-03
Name: date, dtype: datetime64[ns]
Python 中的时间序列机器学习

Passons à la pratique !

Python 中的时间序列机器学习

Preparing Video For Download...