-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFinal Project_R code.Rmd
More file actions
193 lines (139 loc) · 6 KB
/
Final Project_R code.Rmd
File metadata and controls
193 lines (139 loc) · 6 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
---
---
```{r message=FALSE, warning=FALSE}
#library
library(readxl)
library(readr)
library(ggplot2)
library(dplyr)
library(pROC)
library(caret)
library(nnet)
library(glmnet)
library(knitr)
library(rpart)
library(kableExtra)
data <- read_csv("~/NEU Grad docs/ALY6015/Capstone Project/Violence_Reduction_-_Shotspotter_Alerts.csv")
```
```{r}
# Removing rows with missing values
cleaned_data <- na.omit(data)
```
```{r}
# Transform INCIDENT_TYPE_DESCRIPTION to a numerical column, Incident_Type_Code
cleaned_data <- cleaned_data %>%
mutate(Incident_Type_Code = case_when(
INCIDENT_TYPE_DESCRIPTION == "SINGLE GUNSHOT" ~ 0,
INCIDENT_TYPE_DESCRIPTION == "MULTIPLE GUNSHOTS" ~ 1,
INCIDENT_TYPE_DESCRIPTION %in% c("GUNSHOT OR FIRECRACKER") ~ 1,
))
# Assuming the DATE column is in a character format
cleaned_data$DATE <- as.Date(cleaned_data$DATE, format = "%Y-%m-%d")
cleaned_data$ZIP_CODE <- as.numeric(cleaned_data$ZIP_CODE)
head(cleaned_data)
```
<B>
<FONT SIZE = 2, color = "black">
DATA PARTITION
</B><BR>
```{r warning=FALSE}
set.seed(20353)
#partitioning dataset into train and test
# Create separate partitions for columns with different data types
train_indices <- createDataPartition(cleaned_data$Incident_Type_Code, p = 0.70, list = FALSE, times = 1)
train_viol_split <- cleaned_data[train_indices, ]
test_viol_split = cleaned_data[-train_indices,]
```
<B>
<FONT SIZE = 2, color = "black">
GLM - LOGISTIC REGRESSION
</B><BR>
```{r warning=FALSE}
# Fit the GLM model
glm_model <- glm(Incident_Type_Code ~ ZIP_CODE + MONTH + DAY_OF_WEEK + ROUNDS + LATITUDE + LONGITUDE, data = train_viol_split, family = binomial)
# Summary of the model
summary(glm_model)
# Obtain predictions on the test set
predicted_probabilities_test <- predict(glm_model, newdata = test_viol_split, type = "response")
# Convert predicted probabilities to predicted classes (0 or 1)
predicted_classes_test <- ifelse(predicted_probabilities_test > 0.5, 1, 0)
# Create the confusion matrix for test set
conf_matrix_test <- table(Actual = test_viol_split$Incident_Type_Code, Predicted = predicted_classes_test)
conf_matrix_test
# Calculate ROC curve and AUC for test set
roc_curve_test <- roc(test_viol_split$Incident_Type_Code, predicted_probabilities_test)
auc_test <- auc(roc_curve_test)
# Plot ROC curve for training set
plot(roc_curve_test, main = "ROC Curve - Test Set", col = "blue")
legend("bottomright", legend = paste("AUC =", round(auc_test, 3)), col = "blue", lty = 1, cex = 0.8)
```
<B>
<BR>
<FONT SIZE = 2, color = "black">
LINEAR REGRESSION
</B><BR>
```{r}
# Fit the linear regression model
linear_model <- lm(ROUNDS ~ ZIP_CODE + MONTH + DAY_OF_WEEK + ROUNDS + LATITUDE + LONGITUDE, data = train_viol_split)
# Summary of the model
summary(linear_model)
# Make predictions on the test set
linear_predictions <- predict(linear_model, newdata = test_viol_split, type = "response")
# Convert predicted probabilities to binary predictions based on a threshold (e.g., 0.5)
lm_predictions <- ifelse(linear_predictions >= 0.5, 1, 0)
# Compute Mean Squared Error (MSE)
mse <- mean((linear_predictions - test_viol_split$Incident_Type_Code)^2)
# Compute Root Mean Squared Error (RMSE)
rmse <- sqrt(mse)
# Compute Mean Absolute Error (MAE)
mae <- mean(abs(linear_predictions - test_viol_split$Incident_Type_Code))
# Compute R-squared (Coefficient of Determination)
rss <- sum((linear_predictions - mean(test_viol_split$Incident_Type_Code))^2)
tss <- sum((test_viol_split$Incident_Type_Code - mean(test_viol_split$Incident_Type_Code))^2)
rsquared <- 1 - (rss / tss)
# Print evaluation metrics
cat("Mean Squared Error (MSE):", mse, "\n")
cat("Root Mean Squared Error (RMSE):", rmse, "\n")
cat("Mean Absolute Error (MAE):", mae, "\n")
cat("R-squared:", rsquared, "\n")
# Create a table to compare model results
comparison_table <- data.frame(
Metric = c("Residual Standard Error (RSE)", "Mean Squared Error (MSE)", "Root Mean Squared Error (RMSE)",
"Mean Absolute Error (MAE)", "Multiple R-squared", "Adjusted R-squared"),
Trained_Data = c(0.4117, NA, NA, NA, 0.2291, 0.2291),
Test_Data = c(NA, 0.1695297, 0.4117399, 0.3795446, NA, NA)
)
# Print the comparison table with formatting
kable(comparison_table, align = c("c", "c", "c"), caption = "Comparison of Model Results between Trained Data and Test Data") %>%
kable_styling(bootstrap_options = "basic")
# Extract predictor variables from both trained and test datasets
predictor_trained <- train_viol_split[, c("ZIP_CODE", "MONTH", "DAY_OF_WEEK", "ROUNDS", "LATITUDE", "LONGITUDE")]
predictor_test <- test_viol_split[, c("ZIP_CODE", "MONTH", "DAY_OF_WEEK", "ROUNDS", "LATITUDE", "LONGITUDE")]
```
<B>
<FONT SIZE = 2, color = "black">
DECISION TREE - MODEL
</B><BR>
```{r message=FALSE,warning=FALSE}
# Fitting a Decision Tree model
decision_tree_model <- rpart(Incident_Type_Code ~ ZIP_CODE + MONTH + DAY_OF_WEEK + ROUNDS + LATITUDE + LONGITUDE, data = train_viol_split, method="class")
# Viewing the decision tree
print(decision_tree_model)
# Make predictions on the test set
predictions <- predict(decision_tree_model, newdata = test_viol_split, type = "prob")
# Extract probabilities for the positive class
predicted_probabilities <- predictions[, "1"]
# Calculate ROC curve
roc_curve1 <- roc(ifelse(test_viol_split$Incident_Type_Code == "1", 1, 0), predicted_probabilities)
# Calculate AUC
auc_value1 <- auc(roc_curve1)
# Plot ROC curve for training set
plot(roc_curve1, main = "ROC Curve - Test Set", col = "blue")
legend("bottomright", legend = paste("AUC =", round(auc_value1, 3)), col = "blue", lty = 1, cex = 0.8)
# Convert predicted probabilities to binary predictions based on a threshold (e.g., 0.5)
DT_predictions <- ifelse(predicted_probabilities >= 0.5, 1, 0)
# Create the confusion matrix
confusion_matrix <- table(DT_predictions, test_viol_split$Incident_Type_Code)
# Print the confusion matrix
print(confusion_matrix)
```