-
Notifications
You must be signed in to change notification settings - Fork 1
/
Traditional Regression_EXT.Rmd
74 lines (57 loc) · 1.48 KB
/
Traditional Regression_EXT.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
---
title: ""
date: "`r Sys.Date()`"
output:
rmdformats::readthedown:
highlight: kate
---
```{r setup, include=FALSE}
## Global options
knitr::opts_chunk$set(cache = TRUE)
```
```{r lib}
library(ISLR)
library(tidyverse)
library(tidymodels)
library(modelr)
library(purrr)
library(rsample)
library(tidyr)
library(here)
```
```{r}
options(scipen = 999)
```
```{r}
insurance <- read.csv(here("Data", "Insurance_Costs_1.csv"))
insurance_new <- read_csv("https://www.dropbox.com/s/sky86agc4s8c6qe/insurance_costs_2.csv?dl=1")
```
##Part 4 - Q1: Model 2
```{r}
lin_reg <- linear_reg() %>%
set_mode("regression") %>%
set_engine("lm")
modelB <- lin_reg %>%
fit(charges ~ age + bmi, data = insurance)
insurance_new <- insurance_new %>%
mutate(predB = predict(modelB, insurance_new)$.pred)
# MSE for modelB
mean((insurance_new$charges - insurance_new$predB)^2)
```
##Create cross validation function that takes in the model parameters, the dataset and the number of folds for cross validation and returns the MSE.
```{r}
crossV <- function(data, k){
cv <- crossv_kfold(data, k)
prediction <- function(model, test_data){
data <- as.data.frame(test_data)
pred <- add_predictions(data, model)
return(pred)
}
model = map(cv$train, ~lm(charges ~ age + bmi, data = .))
pred1 <- map2_df(model, cv$test, prediction, .id = "C")
MSE1 <- pred1 %>% group_by(C) %>%
summarise(MSE = mean( (charges - pred)^2))
return (mean(MSE1$MSE))
}
crossV(insurance_new, 5)
```