R語言機(jī)器學(xué)習(xí)一攬子解決方案-tidymodels(Build a model)

本文為筆者從官網(wǎng)學(xué)習(xí)的代碼實錄,不對的地方請多指教!
官網(wǎng)地址:https://www.tidymodels.org/
官網(wǎng)介紹:The tidymodels framework is a collection of packages for modeling and machine learning using tidyverse principles.
本次內(nèi)容為get started部分的pipeline

內(nèi)容目錄如下圖

內(nèi)容目錄
載入需要的包
library(tidymodels)  # for the parsnip package, along with the rest of tidymodels
# Helper packages
library(readr)       # for importing data
library(broom.mixed) # for converting bayesian models to tidy tibbles
library(dotwhisker)  # for visualizing regression results
#讀入測試數(shù)據(jù)
urchins <-read_csv("https://tidymodels.org/start/models/urchins.csv") %>% #讀入數(shù)據(jù)
  setNames(c("food_regime", "initial_volume", "width")) %>% #定義列名稱
  mutate(food_regime = factor(food_regime, levels = c("Initial", "Low", "High")))#設(shè)定因子變量
glimpse(urchins)
測試數(shù)據(jù)變量情況

food_regime列為三種不同的喂養(yǎng)策略,initial_volume為金槍魚初始的體積,width為金槍魚最終喂養(yǎng)后的寬度數(shù)據(jù)。研究的主要目的是看看不同的喂養(yǎng)策略對于金槍魚最終寬度的影響。從嘗試可以知道,金槍魚的初始體積initial_volume也會影響最終width的結(jié)果。

#對數(shù)據(jù)進(jìn)行可視化
ggplot(data = urchins,#數(shù)據(jù)集
       aes(x = initial_volume, #全局映射
           y = width, 
           group = food_regime, 
           color = food_regime)) + 
  geom_point() + #繪制點圖
  geom_smooth(method = lm, se = FALSE) +#繪制平滑曲線
  scale_color_viridis_d(option = "plasma", end = .7) #色盲友好顏色

數(shù)據(jù)可視化情況,不同分組對于最終連續(xù)變量的影響

從圖中可以看出,三組共同的趨勢為:金槍魚的初始體積越大,最終喂養(yǎng)后的寬度越大。不同的喂養(yǎng)策略產(chǎn)生的直線的斜率有點不同

可以看到,因為本研究的結(jié)局變量為數(shù)值型變量,所以應(yīng)該用線性回歸模型進(jìn)行擬合分析

選定模型后,我們還需要對模型內(nèi)部的engine進(jìn)行選擇,其定義如下:The engine value is often a mash-up of the software that can be used to fit or train the model as well as the estimation method. 個人認(rèn)為engine的作用主要是確定損失函數(shù)。

linear_reg()#查看線性回歸默認(rèn)的engine
線性回歸默認(rèn)的engine

linear_reg()的engine可選項目
lm_mod <- linear_reg()#定義需要的模型,默認(rèn)參數(shù)
lm_fit <- lm_mod %>% #對模型進(jìn)行擬合
  fit(width ~ initial_volume * food_regime, data = urchins)
tidy(lm_fit)#查看模型
模型擬合結(jié)果
#以下對于估計值及標(biāo)準(zhǔn)誤進(jìn)行可視化
tidy(lm_fit) %>% 
  dwplot(dot_args = list(size = 2, color = "black"),
         whisker_args = list(color = "black"),
         vline = geom_vline(xintercept = 0, colour = "grey50", linetype = 2))+
可視化結(jié)果
#構(gòu)建測試數(shù)據(jù)
new_points <- expand.grid(initial_volume = 20, 
                          food_regime = c("Initial", "Low", "High"))
new_points
測試數(shù)據(jù)
#進(jìn)行點數(shù)據(jù)預(yù)測
m%ean_pred <- predict(lm_fit, new_data = new_points)
mean_pred
均值估計結(jié)果
#95%CI估計
conf_int_pred <- predict(lm_fit, 
                         new_data = new_points, 
                         type = "conf_int")
conf_int_pred 
95%CI估計
#構(gòu)建可視化需要的數(shù)據(jù)集
plot_data <- 
  new_points %>% 
  bind_cols(mean_pred) %>% 
  bind_cols(conf_int_pred)
plot_data 
可視化需要的數(shù)據(jù)集
#畫圖
ggplot(plot_data, aes(x = food_regime)) + 
  geom_point(aes(y = .pred)) + 
  geom_errorbar(aes(ymin = .pred_lower, 
                    ymax = .pred_upper),
                width = .2) + 
  labs(y = "urchin size")
可視化預(yù)測結(jié)果

利用其他engine進(jìn)行數(shù)據(jù)擬合及分析

#以下利用貝葉斯模型進(jìn)行數(shù)據(jù)分析擬合
# 設(shè)定數(shù)據(jù)的先驗分布,這是后面貝葉斯engine的參數(shù)
prior_dist <- rstanarm::student_t(df = 1)
#設(shè)定種子數(shù)
set.seed(123)

# 定義模型
bayes_mod <-   
  linear_reg() %>% 
  set_engine("stan", 
             prior_intercept = prior_dist, 
             prior = prior_dist) 

# 訓(xùn)練模型
bayes_fit <- 
  bayes_mod %>% 
  fit(width ~ initial_volume * food_regime, data = urchins)

print(bayes_fit, digits = 5)#展示模型
貝葉斯模型擬合結(jié)果
tidy(bayes_fit, conf.int = TRUE)
整潔展示
#貝葉斯模型進(jìn)行可視化
bayes_plot_data <- 
  new_points %>% 
  bind_cols(predict(bayes_fit, new_data = new_points)) %>% 
  bind_cols(predict(bayes_fit, new_data = new_points, type = "conf_int"))

ggplot(bayes_plot_data, aes(x = food_regime)) + 
  geom_point(aes(y = .pred)) + 
  geom_errorbar(aes(ymin = .pred_lower, ymax = .pred_upper), width = .2) + 
  labs(y = "urchin size") + 
  ggtitle("Bayesian model with t(1) prior distribution")
貝葉斯模型結(jié)果

以下網(wǎng)址為tidymodels包提供的可以擬合的模型和engine

https://www.tidymodels.org/find/parsnip/


?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容