Rで何かをしたり、読書をするブログ

政府統計の総合窓口のデータや、OECDやUCIやのデータを使って、Rの練習をしています。ときどき、読書記録も載せています。

IEA Gender and Energy Employment Data Analysis 6 - Linear Regression Models with tidymodels framework

UnsplashPeter Thomasが撮影した写真のPeter Thomasが撮影したイラスト素材

 

www.crosshyou.info

This post is continuation of the above post.
In this post, I will walk through how ot perform linear regression model with tidymodel framework.
First, I make a linear regression model with linear_reg().

engine is "lm".
Next, I mae a recipe, which is for all models.

My recipe contains normalize, dummy and zero-variance.

Then, I combine the model and recipe for a workflow.

Next, I use fit() function to fit the model.

Then, I use predict() function with test_data.

Lastly, I calculate RMSE with rmse() function.

The RMSE is 21.7. In future blog posts, I’ll do my best to use various models to achieve an RMSE lower than 21.7.
That's all.

Next post is

www.crosshyou.info

 


To read from the first post of this series,

www.crosshyou.info

I use below code for this post.
#
# make a linear regression model
lm_mod <- linear_reg() |> 
  set_engine("lm")
#
# make a recipe for all models
all_rec <- recipe(gap ~ ., data = df) |> 
  step_normalize(all_numeric_predictors()) |> 
  step_dummy(all_nominal_predictors()) |> 
  step_zv(all_predictors())
#
# make a workflow for the linear regression model
lm_wf <- workflow() |> 
  add_model(lm_mod) |> 
  add_recipe(all_rec)
#
# fit the linear regression model
lm_fit <- fit(lm_wf, data = train_data)
#
# predict with the linear regression model
lm_pred <- predict(lm_fit, new_data = test_data)
#
# calculate RMSE
lm_results <- bind_cols(
  test_data,
  lm_pred
)
lm_rmse <- rmse(lm_results, truth = gap, estimate = .pred)
lm_rmse
#