按时间创建特征

Python 中的时间序列机器学习

Chris Holdgraf

Fellow, Berkeley Institute for Data Science

用滑动窗口提取特征

Python 中的时间序列机器学习

使用 .aggregate 进行特征提取

# Visualize the raw data
print(prices.head(3))
symbol            AIG        ABT
date                            
2010-01-04  29.889999  54.459951
2010-01-05  29.330000  54.019953
2010-01-06  29.139999  54.319953
# Calculate a rolling window, then extract two features
feats = prices.rolling(20).aggregate([np.std, np.max]).dropna()
print(feats.head(3))
                 AIG                  ABT           
                 std       amax       std       amax
date                                                
2010-02-01  2.051966  29.889999  0.868830  56.239949
2010-02-02  2.101032  29.629999  0.869197  56.239949
2010-02-03  2.157249  29.629999  0.852509  56.239949
Python 中的时间序列机器学习

检查特征的性质!

Python 中的时间序列机器学习

在 Python 中使用 partial()

# If we just take the mean, it returns a single value
a = np.array([[0, 1, 2], [0, 1, 2], [0, 1, 2]])
print(np.mean(a))
1.0
# We can use the partial function to initialize np.mean 
# with an axis parameter
from functools import partial
mean_over_first_axis = partial(np.mean, axis=0)

print(mean_over_first_axis(a))
[0. 1. 2.]
Python 中的时间序列机器学习

用分位数概括数据

  • 分位数可比 np.mean 提供更细的汇总。
  • 对于数据集,第 N 个分位数是:有 N% 的数据不大于该值,100−N% 不小于该值。
print(np.percentile(np.linspace(0, 200), q=20))
40.0
Python 中的时间序列机器学习

将 np.percentile() 与偏函数结合以计算一组分位数

data = np.linspace(0, 100)

# Create a list of functions using a list comprehension
percentile_funcs = [partial(np.percentile, q=ii) for ii in [20, 40, 60]]

# Calculate the output of each function in the same way
percentiles = [i_func(data) for i_func in percentile_funcs]
print(percentiles)
[20.0, 40.00000000000001, 60.0]
# Calculate multiple percentiles of a rolling window
data.rolling(20).aggregate(percentiles)
Python 中的时间序列机器学习

计算"基于日期"的特征

  • 到目前为止,我们关注"统计型"特征——即均值、标准差等反映数据统计性质的特征。
  • 但别忘了,时间序列常有更"人类化"的特征,如星期、节假日等。
  • 这些特征在跨年时间序列(如股价)中常很有用。
Python 中的时间序列机器学习

用 Pandas 提取 datetime 特征

# Ensure our index is datetime
prices.index = pd.to_datetime(prices.index)

# Extract datetime features
day_of_week_num = prices.index.weekday
print(day_of_week_num[:10])
Index([0 1 2 3 4 0 1 2 3 4], dtype='object')
day_of_week = prices.index.day_name()
print(day_of_week[:10])
Index(['Monday' 'Tuesday' 'Wednesday' 'Thursday' 'Friday' 'Monday' 'Tuesday'
 'Wednesday' 'Thursday' 'Friday'], dtype='object')
Python 中的时间序列机器学习

Passons à la pratique !

Python 中的时间序列机器学习

Preparing Video For Download...