การพยากรณ์ข้อมูลตามเวลา

Machine Learning สำหรับข้อมูล Time Series ใน Python

Chris Holdgraf

Fellow, Berkeley Institute for Data Science

Classification vs. Regression

Classification
classification_model.predict(X_test)
array([0, 1, 1, 0])
Regression
regression_model.predict(X_test)
array([0.2, 1.4, 3.6, 0.6])
Machine Learning สำหรับข้อมูล Time Series ใน Python

Correlation และ Regression

  • Regression คล้ายกับการคำนวณสหสัมพันธ์ แต่มีความแตกต่างที่สำคัญ
    • Regression: กระบวนการที่ได้ผลลัพธ์เป็นโมเดลอย่างเป็นทางการของข้อมูล
    • Correlation: สถิติที่อธิบายข้อมูล มีข้อมูลน้อยกว่าโมเดล Regression
Machine Learning สำหรับข้อมูล Time Series ใน Python

Correlation ระหว่างตัวแปรมักเปลี่ยนแปลงตามเวลา

  • Timeseries มักมีรูปแบบที่เปลี่ยนแปลงไปตามเวลา
  • Timeseries สองชุดที่ดูเหมือนมีความสัมพันธ์กันในช่วงหนึ่ง อาจไม่คงสภาพนั้นไว้ตลอดเวลา
Machine Learning สำหรับข้อมูล Time Series ใน Python

การแสดงความสัมพันธ์ระหว่าง Timeseries

fig, axs = plt.subplots(1, 2)

# Make a line plot for each timeseries
axs[0].plot(x, c='k', lw=3, alpha=.2)
axs[0].plot(y)
axs[0].set(xlabel='time', title='X values = time')

# Encode time as color in a scatterplot
axs[1].scatter(x_long, y_long, c=np.arange(len(x_long)), cmap='viridis')
axs[1].set(xlabel='x', ylabel='y', title='Color = time')
Machine Learning สำหรับข้อมูล Time Series ใน Python

การแสดง Timeseries สองชุด

Machine Learning สำหรับข้อมูล Time Series ใน Python

โมเดล Regression ด้วย scikit-learn

from sklearn.linear_model import LinearRegression
model = LinearRegression()
model.fit(X, y)
model.predict(X)
Machine Learning สำหรับข้อมูล Time Series ใน Python

แสดงผลการพยากรณ์ด้วย scikit-learn

alphas = [.1, 1e2, 1e3]
ax.plot(y_test, color='k', alpha=.3, lw=3)
for ii, alpha in enumerate(alphas):
    y_predicted = Ridge(alpha=alpha).fit(X_train, y_train).predict(X_test)
    ax.plot(y_predicted, c=cmap(ii / len(alphas)))
ax.legend(['True values', 'Model 1', 'Model 2', 'Model 3'])
ax.set(xlabel="Time")
Machine Learning สำหรับข้อมูล Time Series ใน Python

แสดงผลการพยากรณ์ด้วย scikit-learn

Machine Learning สำหรับข้อมูล Time Series ใน Python

การประเมินโมเดล Regression

  • วิธีที่ใช้บ่อยที่สุด 2 วิธี:
    • Correlation ($r$)
    • Coefficient of Determination ($R^2$)
Machine Learning สำหรับข้อมูล Time Series ใน Python

Coefficient of Determination ($R^2$)

  • ค่า $R^2$ มีขอบเขตสูงสุดที่ 1 และสามารถต่ำได้ไม่จำกัด
  • ค่าที่ใกล้ 1 หมายความว่าโมเดลพยากรณ์ผลลัพธ์ได้ดีกว่า

$$ 1 - \frac{error(model)}{variance(testdata)} $$

Machine Learning สำหรับข้อมูล Time Series ใน Python

$R^2$ ใน scikit-learn

from sklearn.metrics import r2_score
print(r2_score(y_predicted, y_test))
0.08
Machine Learning สำหรับข้อมูล Time Series ใน Python

มาฝึกกันเถอะ!

Machine Learning สำหรับข้อมูล Time Series ใน Python

Preparing Video For Download...