机器学习基础

Python 中的时间序列机器学习

Chris Holdgraf

Fellow, Berkeley Institute for Data Science

始终先查看数据

array.shape
(10, 5)
array[:3]
array([[ 0.735528  ,  1.00122818, -0.28315978],
       [-0.94478393,  0.18658748, -0.00241224],
       [-0.74822942, -1.46636618,  0.69835096]]) 
Python 中的时间序列机器学习

始终先查看数据

df.head()
       col1      col2      col3
0  0.735528  1.001228 -0.283160
1 -0.944784  0.186587 -0.002412
2 -0.748229 -1.466366  0.698351
3  1.038589 -0.171248  0.831457
4 -0.161904  0.003972 -0.321933
Python 中的时间序列机器学习

始终可视化数据

确保它符合预期。

# 使用 matplotlib
fig, ax = plt.subplots()
ax.plot(...)

# 使用 pandas
fig, ax = plt.subplots()
df.plot(..., ax=ax)
Python 中的时间序列机器学习

Scikit-learn

Scikit-learn 是 Python 中最流行的机器学习库

from sklearn.svm import LinearSVC
Python 中的时间序列机器学习

为 scikit-learn 准备数据

  • scikit-learn 期望特定的数据结构:

    (samples, features)

  • 确保数据至少是二维的

  • 确保第一维是样本数

Python 中的时间序列机器学习

当数据形状不正确时

  • 如果轴被交换:
array.T.shape
(10, 3)
Python 中的时间序列机器学习

当数据形状不正确时

  • 如果缺少一个轴,用 .reshape():
array.shape
(10,)
array.reshape(-1, 1).shape
(10, 1)
  • -1 会自动用剩余元素填充该轴
Python 中的时间序列机器学习

使用 scikit-learn 拟合模型

# 导入支持向量分类器
from sklearn.svm import LinearSVC

# 实例化模型
model = LinearSVC()

# 在数据上拟合模型
model.fit(X, y)

y 常见形状为 (samples, 1)

Python 中的时间序列机器学习

检查模型

# 每个输入特征对应一个系数
model.coef_
array([[ 0.69417875, -0.5289162 ]])
Python 中的时间序列机器学习

用已拟合模型进行预测

# 生成预测
predictions = model.predict(X_test)
Python 中的时间序列机器学习

开始练习吧

Python 中的时间序列机器学习

Preparing Video For Download...