R 的特徵工程
Jorge Zazueta
Research Professor and Head of the Modeling Group at the School of Economics, UASLP
特徵工程是一門結合 {{1}} 的方法:
變數,以提升模型效能與可解釋性。
物體高度隨時間的函式
# A tibble: 100 × 2
time height
<dbl> <dbl>
1 0 0
2 0.101 3.85
3 0.202 17.7
4 0.303 15.1
5 0.404 20.0
6 0.505 32.6
7 0.606 30.8
8 0.707 26.6
9 0.808 33.8
10 0.909 39.2
# ... with 90 more rows
# ℹ Use `print(n = ...)` to see more rows
我們為高度建立一個簡單的迴歸模型
lr_height <- lm(height ~ time,
data = height)
並繪圖用肉眼評估準確度。
df <- height %>%
bind_cols(lr_pred = predict(lr_height))
df %>%
ggplot(aes(x = time, y = height)) +
geom_point() +
geom_line(aes(y = lr_pred),
color = "blue", lwd = .75)+
theme_classic()
我們的模型完全無法代表資料!
高度對時間的線性迴歸。

物體的高度遵循拋物線軌跡,可用下式表示:
$y(t) = y_0 + v_0t - \frac{g}{2}t^2$.
其中 $y$ 表示時間 $t$ 的高度,$y_0$、$v_0$、$g$ 分別為初始高度、初速與重力加速度。
我們可擬合模型,納入高度對時間與時間平方的依賴。
mutate() 的第一個參數是資料框,後續提供要加入的新變數定義。
df_2 <- df %>% mutate(time_2 = time^2)
# A tibble: 100 × 4
time height lr_pred time_2
<dbl> <dbl> <dbl> <dbl>
1 0 0 80.8 0
2 0.101 3.85 80.9 0.0102
3 0.202 17.7 81.0 0.0408
4 0.303 15.1 81.1 0.0918
我們再建立一個迴歸模型,同時使用新特徵與原始特徵。
lr_height_2 <-
lm(height ~ time + time_2, data = df_2)
並將新預測畫成圖。
df_2 <- df_2 %>%
bind_cols(lr2_pred = predict(lr_height_2))
df_2 %>%
ggplot(aes(x = time, y = height)) +
geom_point() +
geom_line(aes(y = lr2_pred),
col = "blue", lwd = .75) +
theme_classic()
不更換模型就有明顯改進。
Height 對 time 與 time_2

R 的特徵工程