分類與特徵工程

Python 的時間序列資料機器學習

Chris Holdgraf

Fellow, Berkeley Institute for Data Science

在建模前先視覺化原始資料

Python 的時間序列資料機器學習

先把時間序列畫出來!

ixs = np.arange(audio.shape[-1])
time = ixs / sfreq
fig, ax = plt.subplots()
ax.plot(time, audio)

Python 的時間序列資料機器學習

該用哪些特徵?

  • 直接用原始時間序列做分類會太雜訊
  • 需要先計算特徵!
  • 簡單起手式:先摘要你的音訊資料
Python 的時間序列資料機器學習

Python 的時間序列資料機器學習

一次計算多個特徵

print(audio.shape)
# (n_files, time)
(20, 7000) 
means = np.mean(audio, axis=-1)
maxs = np.max(audio, axis=-1)
stds = np.std(audio, axis=-1)

print(means.shape)
# (n_files,)
(20,) 
Python 的時間序列資料機器學習

用 scikit-learn 訓練分類器

  • 我們把 2 維資料集(樣本 × 時間)壓縮成 1 維資料集(樣本)的多個特徵
  • 可將各特徵組合,作為模型輸入
  • 若每個樣本都有標籤,就能用 scikit-learn 建立並訓練分類器
Python 的時間序列資料機器學習

為 scikit-learn 準備特徵

# Import a linear classifier
from sklearn.svm import LinearSVC

# Note that means are reshaped to work with scikit-learn
X = np.column_stack([means, maxs, stds])
y = labels.reshape(-1, 1)
model = LinearSVC()
model.fit(X, y)
Python 的時間序列資料機器學習

評分你的 scikit-learn 模型

from sklearn.metrics import accuracy_score

# Different input data
predictions = model.predict(X_test)  

# Score our model with % correct
# Manually
percent_score = sum(predictions == labels_test) / len(labels_test)  
# Using a sklearn scorer
percent_score = accuracy_score(labels_test, predictions)  
Python 的時間序列資料機器學習

一起來練習吧!

Python 的時間序列資料機器學習

Preparing Video For Download...