-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathModel Code
More file actions
269 lines (225 loc) · 8.17 KB
/
Model Code
File metadata and controls
269 lines (225 loc) · 8.17 KB
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
library(caret)
library(randomForest)
library(tidyverse)
library(Boruta)
library(gt)
# Load and preprocess data
load_and_preprocess_data <- function(file_path) {
data <- read_csv(file_path)
# Replace spaces in column names with underscores
names(data) <- gsub(" ", "_", names(data))
data <- data %>%
na.omit() %>%
mutate(Pitcher_throws = factor(Pitcher_throws, levels = c("RHP", "LHP"))) %>%
group_by(Name, Pitcher_throws) %>%
summarize(across(active_spin:Vz0, median), .groups = "drop")
data$Release_Pos_Z = data$`Release_Pos_Z_(fixed)`
data$Release_Pos_X = data$`Release_Pos_X_(fixed)`
data <- data %>%
select(-`VAA_AA,_pitch_type`, -`Release_Pos_Z_(fixed)`, -`Release_Pos_X_(fixed)`)
return(data)
}
# Feature selection with Boruta
feature_selection <- function(data, formula) {
boruta_fs <- Boruta(formula, data = data)
print(boruta_fs)
plot(boruta_fs, xlab = "", ylab = "")
# Add variable names to the plot
all_names <- colnames(data[, -1])
text(x = 1:length(all_names), y = -0.5, labels = all_names, xpd = NA, srt = 90, adj = 1, cex = 0.8)
return(boruta_fs)
}
# Train models with k-fold cross-validation
train_models_with_cv <- function(data, formula_v, formula_h, k = 10) {
# Set up cross-validation
control <- trainControl(method = "cv", number = k)
# Set up parameter grid with mtry=9
tune_grid <- expand.grid(.mtry = 9)
# Train models with mtry=9
ivb_model <- train(formula_v, data = data, trControl = control, tuneGrid = tune_grid)
ihb_model <- train(formula_h, data = data, trControl = control, tuneGrid = tune_grid)
return(list(ivb_model, ihb_model))
}
print_boruta_importance <- function(data, boruta_output) {
selected_attributes <- getSelectedAttributes(boruta_output)
importance_values <- boruta_output$ImpHistory[which(boruta_output$finalDecision == "Confirmed"), ]
if (length(selected_attributes) != ncol(importance_values)) {
importance_values <- importance_values[, selected_attributes]
}
importance_df <- data.frame(attribute = selected_attributes, importance = colMeans(importance_values))
importance_df <- importance_df[order(importance_df$importance, decreasing = TRUE), ]
return(importance_df)
}
# Main code
dash_2021 <- load_and_preprocess_data("~/Downloads/2021_pitch_characteristics.csv")
dash_2022 <- load_and_preprocess_data("~/Downloads/2022_pitch_characteristics.csv")
# Assuming dash_2021 is a data frame containing your variables
response_variables <- c("V_Mov", "H_Mov")
independent_variables <- setdiff(names(dash_2021), c("Name", response_variables))
# Collapse the independent variables into a single string with the '+' symbol
independent_variables_string <- paste(sapply(independent_variables, function(x) {
if (grepl("[^[:alnum:]_]", x)) {
paste0("`", x, "`")
} else {
x
}
}), collapse = " + ")
# Create the formula for both H_Mov and V_Mov
#boruta_formula <- as.formula(paste0(paste(response_variables, collapse = " + "), " ~ ", independent_variables_string))
#Just Vertical or horizontal
boruta_formula <- as.formula(paste0("H_Mov", " ~ ", independent_variables_string))
#Just Horizontal
#boruta_formula <- as.formula(paste0(paste(response_variables, collapse = " + "), " ~ ", independent_variables_string))
boruta_fs_2021 <- feature_selection(dash_2021, boruta_formula)
print_boruta_importance(dash_2021, boruta_fs_2021)
# Extract the important variables from the Boruta output
important_vars <- getSelectedAttributes(boruta_fs_2021)
# Create a new string with important independent variables
important_variables_string <- paste(important_vars, collapse = " + ")
# Update your formulae to include only the important variables
train_formula_v <- as.formula(paste("V_Mov", " ~ ", important_variables_string))
#this is the horizontal movement formula. Commented out because doing only vertical
boruta_fs_2021 <- feature_selection(dash_2021, train_formula_v)
train_formula_h <- update(train_formula_v, H_Mov ~ .)
# Train models using 10-fold cross-validation
#formula for all aspects
models_with_cv <- train_models_with_cv(dash_2021, train_formula_v, train_formula_h )
ivb_model_with_cv <- models_with_cv[[1]]
ihb_model_with_cv <- models_with_cv[[2]]
# Access cross-validation results for IVB model
ivb_cv_results <- ivb_model_with_cv$results
print(ivb_cv_results)
# Access cross-validation results for IHB model
ihb_cv_results <- ihb_model_with_cv$results
print(ihb_cv_results)
# Make predictions
predictions_ivb <- predict(ivb_model_with_cv, dash_2022)
predictions_ihb <- predict(ihb_model_with_cv, dash_2022)
dash_2022 <- dash_2022 %>%
mutate(xIVB = predictions_ivb,
xHB = predictions_ihb,
diffVB = V_Mov - xIVB,
diffHB = H_Mov - xHB)
# Print dash_2022 with predictions and differences
print(dash_2022)
# Sort the data by the diffVB column in descending order
sorted_dash_2022 <- dash_2022 %>%
arrange(desc(diffVB))
# Get the top 10 best performers
top_10_best <- sorted_dash_2022[1:10, ]
# Get the top 10 worst performers
top_10_worst <- sorted_dash_2022[(nrow(sorted_dash_2022) - 9):nrow(sorted_dash_2022), ]
# Combine the top 10 best and worst performers into one table
top_10_best_worst <- rbind(top_10_best, top_10_worst)
# Round the diffVB and xIVB columns to 2 decimal places
top_10_best <- top_10_best %>%
mutate(
xIVB = round(xIVB, 2),
diffVB = round(diffVB, 2),
active_spin = paste0(round(as.numeric(active_spin) * 100, 2), "%"),
Name = gsub(",", "", Name) %>%
str_split(" ", 2) %>%
lapply(rev) %>%
lapply(paste, collapse = " ") %>%
unlist()
)
top_10_worst <- top_10_worst %>%
mutate(
xIVB = round(xIVB, 2),
diffVB = round(diffVB, 2),
active_spin = paste0(round(as.numeric(active_spin) * 100, 2), "%"),
Name = gsub(",", "", Name) %>%
str_split(" ", 2) %>%
lapply(rev) %>%
lapply(paste, collapse = " ") %>%
unlist()
) %>%
arrange(diffVB)
best_table <- top_10_best %>%
select(Name, V_Mov, xIVB, diffVB, active_spin) %>%
gt() %>%
tab_header(title = "Overachievers") %>%
cols_label(
Name = "Name",
V_Mov = "IVB",
xIVB = "xIVB",
diffVB = "Difference",
active_spin = "Spin Efficiency"
) %>%
tab_style(
style = cell_text(weight = "bold", size = "large", color = "white"),
locations = cells_title()
) %>%
tab_style(
style = cell_text(weight = "bold", color = "white"),
locations = cells_column_labels()
) %>%
tab_style(
style = cell_fill(color = "black"),
locations = cells_title()
) %>%
tab_style(
style = cell_fill(color = "black"),
locations = cells_column_labels()
) %>%
tab_style(
style = cell_text(color = "white"),
locations = cells_body()
) %>%
tab_style(
style = cell_fill(color = "black"),
locations = cells_body()
) %>%
tab_options(
table.font.names = "Times New Roman", # Replace "Arial" with your preferred font
table.border.top.width = px(0),
table.border.bottom.width = px(0),
table.border.left.width = px(0),
table.border.right.width = px(0)
)
# Display the table in the console
print(best_table)
worst_table <- top_10_worst %>%
select(Name, V_Mov, xIVB, diffVB, active_spin) %>%
gt() %>%
tab_header(title = "Underachievers") %>%
cols_label(
Name = "Name",
V_Mov = "IVB",
xIVB = "xIVB",
diffVB = "Difference",
active_spin = "Spin Efficiency"
) %>%
tab_style(
style = cell_text(weight = "bold", size = "large", color = "white"),
locations = cells_title()
) %>%
tab_style(
style = cell_text(weight = "bold", color = "white"),
locations = cells_column_labels()
) %>%
tab_style(
style = cell_fill(color = "black"),
locations = cells_title()
) %>%
tab_style(
style = cell_fill(color = "black"),
locations = cells_column_labels()
) %>%
tab_style(
style = cell_text(color = "white"),
locations = cells_body()
) %>%
tab_style(
style = cell_fill(color = "black"),
locations = cells_body()
) %>%
tab_options(
table.font.names = "Times New Roman", # Replace "Arial" with your preferred font
table.border.top.width = px(0),
table.border.bottom.width = px(0),
table.border.left.width = px(0),
table.border.right.width = px(0)
)
# Display the table in the console
print(worst_table)