-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstep1_explore_and_clean_data.Rmd
More file actions
3295 lines (2334 loc) · 81.9 KB
/
step1_explore_and_clean_data.Rmd
File metadata and controls
3295 lines (2334 loc) · 81.9 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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
---
output:
html_document: default
---
output:
html_document:
fig_width: 6
fig_height: 4
dev.args:
dpi: 72
knitr::opts_chunk$set(
warning = FALSE,
message = FALSE,
error = TRUE,
cache = TRUE
)
```{r setup, include=FALSE}
# Load necessary packages
library(dplyr)
library(lubridate)
#Import new merged dataset
#Load the library
library(readxl)
# Define the file path
file_path <- "~/Downloads/Capstone/merged_final_cleaned.xlsx"
# Read a specific sheet
mfc <- read_excel(file_path, sheet = "Sheet 1")
# Load the required library
library(readxl)
# Define the file path (update the path to your actual Excel file)
file_path <- "/Users/HP/Downloads/Capstone/DePaul_Summer_Quarter_meter.xlsx"
# Read each worksheet into a separate dataframe
asset_details <- read_excel(file_path, sheet = "Asset Detail")
wo_costs <- read_excel(file_path, sheet = "2024 WO Costs")
usage_data <- read_excel(file_path, sheet = "Miles (Driven Last Year)")
# Optional: View structure of the data
str(asset_details)
str(wo_costs)
str(usage_data)
```
```{r}
name(usage_data)
```
Binarize Target Variable
```{r}
mfc <- mfc %>%
mutate(high_cost_flag = ifelse(line_total > quantile(line_total, 0.90, na.rm = TRUE), 1, 0))
```
convert date types
```{r}
# Convert numeric Excel dates to proper Date format
mfc$asset_in_service_date <- as.Date(mfc$asset_in_service_date, origin = "1899-12-30")
mfc$asset_disposal_date <- as.Date(mfc$asset_disposal_date, origin = "1899-12-30")
```
clean categorical variables
```{r}
library(forcats)
mfc$wo_reason_desc <- fct_explicit_na(as.factor(mfc$wo_reason_desc))
```
create time_since_last_wo
```{r}
library(dplyr)
mfc <- mfc %>%
arrange(unit_no, open_date) %>% # Sort by unit and WO date
group_by(unit_no) %>%
mutate(
last_wo_date = lag(open_date), # Previous WO date
time_since_last_wo = as.numeric(difftime(open_date, last_wo_date, units = "days"))
) %>%
ungroup()
```
recent_wo_flag
```{r}
mfc <- mfc %>%
mutate(
recent_wo_flag = ifelse(!is.na(time_since_last_wo) & time_since_last_wo < 90, 1, 0)
)
library(dplyr)
# Add the recent_wo_flag feature
mfc <- mfc %>%
mutate(
recent_wo_flag = ifelse(!is.na(time_since_last_wo) & time_since_last_wo < 90, 1, 0)
)
```
Add vehicle age
```{r}
library(dplyr)
# Step 1: Feature engineering (run this before selecting features)
mfc <- mfc %>%
mutate(
vehicle_age = 2025 - model_year,
recent_wo_flag = ifelse(!is.na(time_since_last_wo) & time_since_last_wo < 90, 1, 0)
)
```
add mileage ratio
```{r}
mfc <- mfc %>%
mutate(
vehicle_age = 2025 - model_year,
recent_wo_flag = ifelse(!is.na(time_since_last_wo) & time_since_last_wo < 90, 1, 0),
mileage_ratio = ifelse(!is.na(miles_driven) & miles_driven != 0,
annualized_mileage / (miles_driven + 1), NA)
)
```
Core Model (All Assets)
Model 1
```{r}
# Load necessary libraries
library(dplyr)
library(forcats)
library(randomForest)
library(caret)
library(pROC)
# STEP 1: Select features with usage included
selected_vars <- c(
"high_cost_flag", "part_amount", "labor_amount", "job_description",
"model", "model_year", "time_since_last_wo", "recent_wo_flag",
"vehicle_age", "mileage_ratio", "annualized_mileage", "miles_driven"
)
# STEP 2: Subset and preprocess
mfc_model1 <- mfc %>%
select(all_of(selected_vars)) %>%
mutate(
job_description = fct_lump(factor(job_description), n = 10),
model = fct_lump(factor(model), n = 10)
) %>%
filter(if_all(everything(), ~ !is.na(.))) # remove NAs
# Check for class balance (optional)
table(mfc_model1$high_cost_flag)
# STEP 3: Train Enhanced Random Forest Model 1
set.seed(123)
rf_model1 <- randomForest(
as.factor(high_cost_flag) ~ .,
data = mfc_model1,
ntree = 200,
importance = TRUE
)
# STEP 4: Make Predictions
mfc_model1$high_cost_predicted <- predict(rf_model1, mfc_model1)
mfc_model1$prediction_probability <- predict(rf_model1, mfc_model1, type = "prob")[, 2]
# STEP 5: Evaluate - Confusion Matrix
confusionMatrix(
as.factor(mfc_model1$high_cost_predicted),
as.factor(mfc_model1$high_cost_flag),
positive = "1"
)
# STEP 6: Evaluate - ROC and AUC
roc_model1 <- roc(mfc_model1$high_cost_flag, mfc_model1$prediction_probability)
plot(roc_model1, main = "ROC Curve - Model 1 (With Imputed Usage)")
auc(roc_model1)
# STEP 7: Feature Importance Plot
varImpPlot(rf_model1, main = "Feature Importance - Model 1")
```
Model 2: Only Assets with Verified Usage Data
Filter by Usage Dataset
```{r}
mfc$unit_no <- as.character(mfc$unit_no)
usage_data$unit_no <- as.character(usage_data$Unit_No)
# Assuming usage_data is already loaded with unit_no
mfc_model2 <- mfc %>%
filter(unit_no %in% usage_data$unit_no) %>%
select(all_of(selected_vars)) %>%
mutate(
job_description = fct_lump(factor(job_description), n = 10),
model = fct_lump(factor(model), n = 10)
) %>%
filter(if_all(everything(), ~ !is.na(.)))
```
Train Model 2 (Usage-Confirmed Assets)
```{r}
set.seed(123)
rf_model2 <- randomForest(
as.factor(high_cost_flag) ~ .,
data = mfc_model2,
ntree = 200,
importance = TRUE
)
```
```{r}
mfc_model2$high_cost_predicted <- predict(rf_model2, mfc_model2, type = "response")
mfc_model2$prediction_probability <- predict(rf_model2, mfc_model2, type = "prob")[,2]
```
Confusion Matrix
```{r}
confusionMatrix(
as.factor(mfc_model2$high_cost_predicted),
as.factor(mfc_model2$high_cost_flag),
positive = "1"
)
```
AUC
```{r}
roc_model2 <- roc(mfc_model2$high_cost_flag, mfc_model2$prediction_probability)
plot(roc_model2, main = "ROC Curve - Model 2 (Usage-Confirmed Assets)")
auc(roc_model2)
```
Feature Importance Plot
```{r}
varImpPlot(rf_model2, main = "Feature Importance - Model 2 (Usage-Confirmed Assets)")
```
Calibration Plot (Probability Accuracy)
```{r}
library(ggplot2)
calibration_plot <- function(data, prob_col, label_col, title_text) {
data %>%
mutate(bin = cut(!!sym(prob_col), breaks = seq(0, 1, 0.1))) %>%
group_by(bin) %>%
summarise(
mean_prob = mean(!!sym(prob_col)),
actual_rate = mean(!!sym(label_col) == 1)
) %>%
ggplot(aes(x = mean_prob, y = actual_rate)) +
geom_line(color = "blue") +
geom_abline(linetype = "dashed") +
labs(title = title_text, x = "Predicted Probability", y = "Observed Rate") +
theme_minimal()
}
calibration_plot(mfc_model1, "prediction_probability", "high_cost_flag", "Model 1 Calibration")
calibration_plot(mfc_model2, "prediction_probability", "high_cost_flag", "Model 2 Calibration")
```
Lift & Gain Chart Code for Binary Classification
Define Lift/Gain Chart Function
```{r}
library(dplyr)
library(ggplot2)
get_lift_gain_data <- function(data, prob_col, target_col, model_name) {
data %>%
arrange(desc(!!sym(prob_col))) %>%
mutate(rank = row_number()) %>%
mutate(bin = ntile(!!sym(prob_col), 10)) %>%
group_by(bin) %>%
summarise(
total = n(),
positives = sum(!!sym(target_col) == 1),
cumulative_positives = cumsum(positives),
.groups = "drop"
) %>%
mutate(
cumulative_gain = cumsum(positives) / sum(positives),
lift = cumulative_gain / (bin / 10),
model = model_name,
decile = bin * 10
)
}
```
Create Datasets for Each Model
```{r}
# For Model 1 (All Assets)
lift_gain_model1 <- get_lift_gain_data(mfc_model1, "prediction_probability", "high_cost_flag", "Model 1")
# For Model 2 (Usage Assets)
lift_gain_model2 <- get_lift_gain_data(mfc_model2, "prediction_probability", "high_cost_flag", "Model 2")
# Combine
lift_gain_data <- bind_rows(lift_gain_model1, lift_gain_model2)
```
Plot Gain Chart
```{r}
ggplot(lift_gain_data, aes(x = decile, y = cumulative_gain * 100, color = model)) +
geom_line(size = 1.2) +
geom_abline(slope = 1, intercept = 0, linetype = "dashed", color = "gray") +
labs(title = "Cumulative Gain Chart",
x = "Percent of Assets Scored",
y = "Cumulative % of High-Cost WOs Captured") +
theme_minimal()
```
Plot Lift Chart
```{r}
ggplot(lift_gain_data, aes(x = decile, y = lift, color = model)) +
geom_line(size = 1.2) +
geom_hline(yintercept = 1, linetype = "dashed", color = "gray") +
labs(title = "Lift Chart",
x = "Percent of Assets Scored",
y = "Lift (Model vs Random)") +
theme_minimal()
```
Probability Distribution by Model
```{r}
library(ggplot2)
# Combine into one dataframe
mfc_model1$model <- "Model 1"
mfc_model2$model <- "Model 2"
combined_preds <- bind_rows(
mfc_model1 %>% select(prediction_probability, high_cost_flag, model),
mfc_model2 %>% select(prediction_probability, high_cost_flag, model)
)
ggplot(combined_preds, aes(x = prediction_probability, fill = as.factor(high_cost_flag))) +
geom_histogram(position = "identity", bins = 40, alpha = 0.6) +
facet_wrap(~model) +
scale_fill_manual(values = c("0" = "steelblue", "1" = "tomato"), name = "Actual Flag") +
labs(
title = "Predicted Probability Distributions by Model",
x = "Prediction Probability",
y = "Count"
) +
theme_minimal()
```
Interpretation: Model 2 has tighter, more polarized probability bands — indicating stronger class separation and less ambiguity.
Boxplot of Probabilities by Actual Class
```{r}
ggplot(combined_preds, aes(x = as.factor(high_cost_flag), y = prediction_probability, fill = model)) +
geom_boxplot(alpha = 0.7, outlier.shape = NA) +
facet_wrap(~model) +
labs(
title = "Predicted Probability vs Actual Outcome",
x = "Actual High Cost Flag",
y = "Prediction Probability"
) +
theme_minimal()
```
Interpretation:
Model 2’s box is very tight near 1.0 → very confident
Model 1 has a broader spread, though still high.
Again, Model 2 demonstrates better probability calibration and less variance in predictions for true positives.
Predicted Risk Bands (Stacked Bar Chart)
```{r}
combined_preds <- combined_preds %>%
mutate(
risk_band = case_when(
prediction_probability >= 0.8 ~ "High",
prediction_probability >= 0.6 ~ "Medium",
TRUE ~ "Low"
)
)
ggplot(combined_preds, aes(x = risk_band, fill = model)) +
geom_bar(position = "dodge") +
labs(title = "Prediction Band Distribution", x = "Risk Band", y = "Asset Count") +
theme_minimal()
```
Bands defined as:
High: ≥ 0.80
Medium: 0.60–0.79
Low: < 0.60
What it shows:
Both models classify most assets as Low Risk
Model 2 identifies more true High Risk assets confidently
Model 1 has more variability and some spread across bands
Model 2 gives a tighter segmentation of assets with fewer in ambiguous medium-risk categories.
Interpretation:
Asset Level agrreation:
```{r}
# Re-attach unit_no to prediction output
mfc_model1$unit_no <- mfc$unit_no[as.numeric(rownames(mfc_model1))]
mfc_model2$unit_no <- mfc$unit_no[as.numeric(rownames(mfc_model2))]
```
```{r}
# Function to summarize predictions to asset level
summarize_asset_predictions <- function(data, model_name) {
data %>%
group_by(unit_no) %>%
summarise(
total_wos = n(),
high_cost_predicted = sum(high_cost_predicted == 1, na.rm = TRUE),
avg_prediction_probability = mean(prediction_probability, na.rm = TRUE),
risk_rate = high_cost_predicted / total_wos,
model_used = model_name
) %>%
mutate(
risk_level = case_when(
risk_rate >= 0.75 ~ "High",
risk_rate >= 0.25 ~ "Medium",
TRUE ~ "Low"
)
)
}
# Apply to both models
asset_level_model1 <- summarize_asset_predictions(mfc_model1, "Model 1")
asset_level_model2 <- summarize_asset_predictions(mfc_model2, "Model 2")
```
check for effectiveness of asset level aggregation
```{r}
library(ggplot2)
# Histogram of total WOs per asset
ggplot(asset_level_model1, aes(x = total_wos)) +
geom_histogram(bins = 30, fill = "skyblue", color = "black") +
labs(title = "Distribution of WO Count per Asset", x = "Work Orders", y = "Asset Count")
# Risk rate distribution
ggplot(asset_level_model1, aes(x = risk_rate)) +
geom_histogram(bins = 30, fill = "tomato", color = "black") +
labs(title = "Distribution of Risk Rate per Asset", x = "Predicted High-Cost WO Rate", y = "Asset Count")
```
Most assets have fewer than 20 WOs, with a long tail up to 600+
This is a realistic skew for a fleet: some assets are very lightly used; others are heavily maintained
Conclusion: Distribution is healthy; aggregation makes sense.
Majority of assets have risk rates near 0, meaning few or no predicted high-cost WOs
There’s a meaningful tail toward higher risk rates
Conclusion: The model is not biased to assign high risk to everyone. It’s distinguishing well across the fleet.
Check Correlation Between WO-Level Confidence and Asset-Level Risk
```{r}
cor(asset_level_model1$risk_rate, asset_level_model1$avg_prediction_probability, use = "complete.obs")
```
This is near-perfect correlation — your aggregation is working extremely well.
High WO-level probabilities are translating to appropriate asset-level risk rates.
Compare Asset Risk Levels with Known Outcomes (if available)
```{r}
ggplot(asset_level_model1, aes(x = risk_level, y = avg_prediction_probability)) +
geom_boxplot() +
labs(title = "Confidence by Asset Risk Level", y = "Avg Prediction Probability", x = "Risk Level")
```
Majority of assets fall into Low Risk
A smaller but meaningful number fall into Medium and High Risk
onclusion: Risk segmentation is not uniform — model isn’t overgeneralizing.
Cross-Check with WO-Level Results
```{r}
top_assets <- asset_level_model1 %>% arrange(desc(risk_rate)) %>% slice_head(n = 100)
summary(top_assets$risk_rate)
```
Conclusion: Distribution is healthy; aggregation makes sense
Visual Asset Scoring Bands (Optional)
```{r}
ggplot(asset_level_model1, aes(x = risk_level)) +
geom_bar(fill = "steelblue") +
labs(title = "Asset Risk Level Classification", x = "Risk Level", y = "Asset Count")
```
Conclusion: Risk segmentation is not uniform — model isn’t overgeneralizing.
```{r}
names(mfc_model1)
names(mfc_model2)
```
```{r}
company_map <- mfc %>%
mutate(
unit_no = toupper(trimws(as.character(unit_no))),
company = trimws(as.character(company))
) %>%
select(unit_no, company) %>%
distinct()
# Create a reference with row index and unit_no
unit_no_ref <- mfc %>%
mutate(unit_no = toupper(trimws(as.character(unit_no)))) %>%
select(unit_no) %>%
mutate(row_id = row_number())
# Add row index to mfc_model1
mfc_model1 <- mfc_model1 %>%
mutate(row_id = row_number())
# Join back unit_no
mfc_model1 <- mfc_model1 %>%
left_join(unit_no_ref, by = "row_id") %>%
select(-row_id)
sum(is.na(mfc_model1$unit_no)) # Should be 0
sum(is.na(mfc_model1$company)) # Should be 0 (if mapping is clean)
```
```{r}
# Load libraries
library(dplyr)
library(randomForest)
library(pROC)
library(caret)
library(forcats)
# Step 1: Combine WO-level Model 1 and Model 2 predictions
combined_wo_data <- bind_rows(mfc_model2, mfc_model1) %>%
distinct(unit_no, .keep_all = TRUE)
# Step 2: Aggregate to asset-level
third_model_data <- combined_wo_data %>%
group_by(unit_no) %>%
summarise(
part_amount = mean(part_amount, na.rm = TRUE),
labor_amount = mean(labor_amount, na.rm = TRUE),
job_description = fct_lump(factor(first(job_description)), n = 10),
model = fct_lump(factor(first(model)), n = 10),
mileage_ratio = mean(mileage_ratio, na.rm = TRUE),
annualized_mileage = mean(annualized_mileage, na.rm = TRUE),
miles_driven = mean(miles_driven, na.rm = TRUE),
model_year = first(model_year),
vehicle_age = first(vehicle_age),
time_since_last_wo = mean(time_since_last_wo, na.rm = TRUE),
recent_wo_flag = max(recent_wo_flag, na.rm = TRUE),
actual_high_cost = ifelse(sum(high_cost_flag, na.rm = TRUE) > 0, 1, 0)
) %>%
filter(if_all(everything(), ~ !is.na(.)))
# Step 3: Train RF model
set.seed(123)
rf_third <- randomForest(
as.factor(actual_high_cost) ~ .,
data = third_model_data,
ntree = 200,
importance = TRUE
)
# Step 4: Predict and Evaluate
third_model_data$predicted <- predict(rf_third, third_model_data)
third_model_data$probability <- predict(rf_third, third_model_data, type = "prob")[,2]
# Confusion Matrix
confusionMatrix(as.factor(third_model_data$predicted), as.factor(third_model_data$actual_high_cost), positive = "1")
# ROC
roc_obj <- roc(third_model_data$actual_high_cost, third_model_data$probability)
plot(roc_obj, main = "ROC Curve - Final Model")
auc(roc_obj)
# Feature Importance
varImpPlot(rf_third, main = "Feature Importance - Third RF Model")
```
asset-level clustering using K-means and UMAP for model 1
add utilization_score to asset_level_model1
```{r}
#Compute WO count and mileage from raw mfc
wo_usage_summary <- mfc %>%
group_by(unit_no) %>%
summarise(
total_wos = n(),
avg_mileage = mean(annualized_mileage, na.rm = TRUE)
) %>%
mutate(
z_mileage = scale(avg_mileage),
z_wos = scale(total_wos),
utilization_score = z_mileage + z_wos
)
#Merge into asset_level_model1
asset_level_model1 <- asset_level_model1 %>%
left_join(wo_usage_summary %>% select(unit_no, utilization_score), by = "unit_no")
summary(asset_level_model1$utilization_score)
```
Choose Features for Clustering
```{r}
# Features that define asset behavior
clustering_vars <- c(
"risk_rate",
"avg_prediction_probability",
"total_wos", "utilization_score"
)
```
Prepare Data for Clustering
```{r}
library(dplyr)
library(tidyr)
# Subset and scale
clustering_data <- asset_level_model1 %>%
select(unit_no, all_of(clustering_vars)) %>%
drop_na() %>%
mutate(across(all_of(clustering_vars), scale))
# Keep original IDs for later merge
row_ids <- clustering_data$unit_no
clustering_matrix <- clustering_data %>% select(-unit_no)
```
Run K-Means Clustering
```{r}
set.seed(123)
# You can test different values of k (e.g., 3 to 6)
kmeans_model <- kmeans(clustering_matrix, centers = 4, nstart = 25)
# Add cluster labels back to original data
clustered_assets <- asset_level_model1 %>%
filter(unit_no %in% row_ids) %>%
mutate(cluster = as.factor(kmeans_model$cluster))
```
Visualize Clusters with PCA
```{r}
library(ggplot2)
pca <- prcomp(clustering_matrix, scale. = TRUE)
pca_df <- as.data.frame(pca$x[, 1:2])
pca_df$cluster <- clustered_assets$cluster
ggplot(pca_df, aes(x = PC1, y = PC2, color = cluster)) +
geom_point(alpha = 0.6) +
labs(title = "PCA: Asset Clusters") +
theme_minimal()
```
Clear separation between clusters, especially Cluster 1 and Cluster 4
Confirms that asset behavior is differentiable based on risk + utilization or UMAP
```{r}
library(umap)
# Re-scale everything (UMAP is sensitive!)
scaled_data <- clustering_matrix %>%
mutate(across(everything(), scale))
umap_result <- umap(scaled_data)
#install.packages("umap")
library(umap)
umap_result <- umap(clustering_matrix)
umap_df <- as.data.frame(umap_result$layout)
umap_df$cluster <- clustered_assets$cluster
ggplot(umap_df, aes(x = V1, y = V2, color = cluster)) +
geom_point(alpha = 0.6) +
labs(title = "UMAP: Asset Clusters") +
theme_minimal()
```
Explore Cluster Insights
```{r}
clustered_assets %>%
group_by(cluster) %>%
summarise(
avg_risk = mean(risk_rate),
avg_confidence = mean(avg_prediction_probability),
avg_wos = mean(total_wos),
count = n()
)
```
asset-level clustering using K-means and UMAP for model 2
Add utilization_score to asset_level_model2
```{r}
wo_usage_summary2 <- mfc %>%
filter(unit_no %in% asset_level_model2$unit_no) %>% # restrict to Model 2 units
group_by(unit_no) %>%
summarise(
total_wos = n(),
avg_mileage = mean(annualized_mileage, na.rm = TRUE)
) %>%
mutate(
z_mileage = scale(avg_mileage),
z_wos = scale(total_wos),
utilization_score = z_mileage + z_wos
)
asset_level_model2 <- asset_level_model2 %>%
left_join(wo_usage_summary2 %>% select(unit_no, utilization_score), by = "unit_no")
summary(asset_level_model2$utilization_score)
```
```{r}
clustering_vars <- c(
"risk_rate",
"avg_prediction_probability",
"total_wos",
"utilization_score"
)
#Prepare Data
library(dplyr)
clustering_data2 <- asset_level_model2 %>%
select(unit_no, all_of(clustering_vars)) %>%
drop_na() %>%
mutate(across(all_of(clustering_vars), scale))
row_ids2 <- clustering_data2$unit_no
clustering_matrix2 <- clustering_data2 %>% select(-unit_no)
# Run K-Means Clustering
set.seed(123)
kmeans_model2 <- kmeans(clustering_matrix2, centers = 4, nstart = 25)
# Add cluster label to asset dataset
clustered_assets2 <- asset_level_model2 %>%
filter(unit_no %in% row_ids2) %>%
mutate(cluster = as.factor(kmeans_model2$cluster))
#Visualize Clusters with PCA
pca2 <- prcomp(clustering_matrix2, scale. = TRUE)
pca_df2 <- as.data.frame(pca2$x[, 1:2])
pca_df2$cluster <- clustered_assets2$cluster
library(ggplot2)
ggplot(pca_df2, aes(x = PC1, y = PC2, color = cluster)) +
geom_point(alpha = 0.6) +
labs(title = "PCA: Model 2 Asset Clusters") +
theme_minimal()
#Fix UMAP if desired
library(umap)
umap_result2 <- umap(clustering_matrix2)
umap_df2 <- as.data.frame(umap_result2$layout)
umap_df2$cluster <- clustered_assets2$cluster
ggplot(umap_df2, aes(x = V1, y = V2, color = cluster)) +
geom_point(alpha = 0.6) +
labs(title = "UMAP: Model 2 Asset Clusters") +
theme_minimal()
#Review Cluster Statistics
clustered_assets2 %>%
group_by(cluster) %>%
summarise(
avg_risk = mean(risk_rate),
avg_confidence = mean(avg_prediction_probability),
avg_wos = mean(total_wos),
avg_utilization = mean(utilization_score),
count = n()
)
```
clustering for both model 1 and 2 together
```{r}
library(dplyr)
library(fastDummies)
library(ggplot2)
# STEP 1: Create utilization_category from mfc
utilization_benchmark <- mfc %>%
group_by(unit_no) %>%
summarise(avg_utilized_days = mean(utilized_days_per_month, na.rm = TRUE)) %>%
mutate(utilization_category = case_when(
avg_utilized_days < 10 ~ "Low",
avg_utilized_days < 20 ~ "Medium",
avg_utilized_days >= 20 ~ "High",
TRUE ~ NA_character_
))
# STEP 2: Combine asset_level_model1 and model2, prioritize Model 2
asset_level_model1 <- asset_level_model1 %>% mutate(source_model = "Model 1")
asset_level_model2 <- asset_level_model2 %>% mutate(source_model = "Model 2")
combined_assets <- bind_rows(asset_level_model2, asset_level_model1) %>%
group_by(unit_no) %>%
arrange(desc(source_model)) %>%
slice(1) %>%
ungroup()
# STEP 3: Merge utilization_category
combined_assets <- combined_assets %>%
left_join(utilization_benchmark %>% select(unit_no, utilization_category), by = "unit_no")
# STEP 4: One-hot encode utilization_category
combined_assets_encoded <- combined_assets %>%
filter(!is.na(utilization_category)) %>%
fastDummies::dummy_cols(select_columns = "utilization_category", remove_selected_columns = TRUE)
# STEP 5: Define clustering variables
clustering_vars <- c(
"risk_rate", "avg_prediction_probability", "total_wos", "utilization_score",
"utilization_category_Low", "utilization_category_Medium", "utilization_category_High"
)
# STEP 6: Prepare data for clustering
clustering_data <- combined_assets_encoded %>%
select(unit_no, all_of(clustering_vars)) %>%
drop_na() %>%
mutate(across(-unit_no, scale)) # standardize all but ID
row_ids <- clustering_data$unit_no
clustering_matrix <- clustering_data %>% select(-unit_no)
# STEP 7: Run K-means clustering
set.seed(123)
kmeans_combined <- kmeans(clustering_matrix, centers = 4, nstart = 25)
# STEP 8: Attach clusters back to dataset
clustered_combined_assets <- combined_assets_encoded %>%
filter(unit_no %in% row_ids) %>%
mutate(cluster = as.factor(kmeans_combined$cluster))
# STEP 9: Visualize with PCA
pca <- prcomp(clustering_matrix, scale. = TRUE)
pca_df <- as.data.frame(pca$x[, 1:2])
pca_df$cluster <- clustered_combined_assets$cluster
ggplot(pca_df, aes(x = PC1, y = PC2, color = cluster)) +
geom_point(alpha = 0.6) +
labs(title = "PCA: Combined Asset Clusters (with Utilization Category)") +
theme_minimal()
```