Refer to http://archive.ics.uci.edu/ml/datasets/Statlog+(German+Credit+Data)
for variable description. The response variable is Class
and all others are predictors.
Only run the following code once to install the required packages.
install.packages(c('caret', 'rpart', 'rpart.plot', 'pROC'))
library(caret) #this package contains the german data with its numeric format
## Loading required package: ggplot2
## Loading required package: lattice
data(GermanCredit)
# Code the Class variable into 1 and 0: 1 means Good and 0 means Bad.
GermanCredit$Class <- as.numeric(GermanCredit$Class == "Good")
GermanCredit$Class <- as.factor(GermanCredit$Class)
str(GermanCredit)
## 'data.frame': 1000 obs. of 62 variables:
## $ Duration : int 6 48 12 42 24 36 24 36 12 30 ...
## $ Amount : int 1169 5951 2096 7882 4870 9055 2835 6948 3059 5234 ...
## $ InstallmentRatePercentage : int 4 2 2 2 3 2 3 2 2 4 ...
## $ ResidenceDuration : int 4 2 3 4 4 4 4 2 4 2 ...
## $ Age : int 67 22 49 45 53 35 53 35 61 28 ...
## $ NumberExistingCredits : int 2 1 1 1 2 1 1 1 1 2 ...
## $ NumberPeopleMaintenance : int 1 1 2 2 2 2 1 1 1 1 ...
## $ Telephone : num 0 1 1 1 1 0 1 0 1 1 ...
## $ ForeignWorker : num 1 1 1 1 1 1 1 1 1 1 ...
## $ Class : Factor w/ 2 levels "0","1": 2 1 2 2 1 2 2 2 2 1 ...
## $ CheckingAccountStatus.lt.0 : num 1 0 0 1 1 0 0 0 0 0 ...
## $ CheckingAccountStatus.0.to.200 : num 0 1 0 0 0 0 0 1 0 1 ...
## $ CheckingAccountStatus.gt.200 : num 0 0 0 0 0 0 0 0 0 0 ...
## $ CheckingAccountStatus.none : num 0 0 1 0 0 1 1 0 1 0 ...
## $ CreditHistory.NoCredit.AllPaid : num 0 0 0 0 0 0 0 0 0 0 ...
## $ CreditHistory.ThisBank.AllPaid : num 0 0 0 0 0 0 0 0 0 0 ...
## $ CreditHistory.PaidDuly : num 0 1 0 1 0 1 1 1 1 0 ...
## $ CreditHistory.Delay : num 0 0 0 0 1 0 0 0 0 0 ...
## $ CreditHistory.Critical : num 1 0 1 0 0 0 0 0 0 1 ...
## $ Purpose.NewCar : num 0 0 0 0 1 0 0 0 0 1 ...
## $ Purpose.UsedCar : num 0 0 0 0 0 0 0 1 0 0 ...
## $ Purpose.Furniture.Equipment : num 0 0 0 1 0 0 1 0 0 0 ...
## $ Purpose.Radio.Television : num 1 1 0 0 0 0 0 0 1 0 ...
## $ Purpose.DomesticAppliance : num 0 0 0 0 0 0 0 0 0 0 ...
## $ Purpose.Repairs : num 0 0 0 0 0 0 0 0 0 0 ...
## $ Purpose.Education : num 0 0 1 0 0 1 0 0 0 0 ...
## $ Purpose.Vacation : num 0 0 0 0 0 0 0 0 0 0 ...
## $ Purpose.Retraining : num 0 0 0 0 0 0 0 0 0 0 ...
## $ Purpose.Business : num 0 0 0 0 0 0 0 0 0 0 ...
## $ Purpose.Other : num 0 0 0 0 0 0 0 0 0 0 ...
## $ SavingsAccountBonds.lt.100 : num 0 1 1 1 1 0 0 1 0 1 ...
## $ SavingsAccountBonds.100.to.500 : num 0 0 0 0 0 0 0 0 0 0 ...
## $ SavingsAccountBonds.500.to.1000 : num 0 0 0 0 0 0 1 0 0 0 ...
## $ SavingsAccountBonds.gt.1000 : num 0 0 0 0 0 0 0 0 1 0 ...
## $ SavingsAccountBonds.Unknown : num 1 0 0 0 0 1 0 0 0 0 ...
## $ EmploymentDuration.lt.1 : num 0 0 0 0 0 0 0 0 0 0 ...
## $ EmploymentDuration.1.to.4 : num 0 1 0 0 1 1 0 1 0 0 ...
## $ EmploymentDuration.4.to.7 : num 0 0 1 1 0 0 0 0 1 0 ...
## $ EmploymentDuration.gt.7 : num 1 0 0 0 0 0 1 0 0 0 ...
## $ EmploymentDuration.Unemployed : num 0 0 0 0 0 0 0 0 0 1 ...
## $ Personal.Male.Divorced.Seperated : num 0 0 0 0 0 0 0 0 1 0 ...
## $ Personal.Female.NotSingle : num 0 1 0 0 0 0 0 0 0 0 ...
## $ Personal.Male.Single : num 1 0 1 1 1 1 1 1 0 0 ...
## $ Personal.Male.Married.Widowed : num 0 0 0 0 0 0 0 0 0 1 ...
## $ Personal.Female.Single : num 0 0 0 0 0 0 0 0 0 0 ...
## $ OtherDebtorsGuarantors.None : num 1 1 1 0 1 1 1 1 1 1 ...
## $ OtherDebtorsGuarantors.CoApplicant : num 0 0 0 0 0 0 0 0 0 0 ...
## $ OtherDebtorsGuarantors.Guarantor : num 0 0 0 1 0 0 0 0 0 0 ...
## $ Property.RealEstate : num 1 1 1 0 0 0 0 0 1 0 ...
## $ Property.Insurance : num 0 0 0 1 0 0 1 0 0 0 ...
## $ Property.CarOther : num 0 0 0 0 0 0 0 1 0 1 ...
## $ Property.Unknown : num 0 0 0 0 1 1 0 0 0 0 ...
## $ OtherInstallmentPlans.Bank : num 0 0 0 0 0 0 0 0 0 0 ...
## $ OtherInstallmentPlans.Stores : num 0 0 0 0 0 0 0 0 0 0 ...
## $ OtherInstallmentPlans.None : num 1 1 1 1 1 1 1 1 1 1 ...
## $ Housing.Rent : num 0 0 0 0 0 0 0 1 0 0 ...
## $ Housing.Own : num 1 1 1 0 0 0 1 0 1 1 ...
## $ Housing.ForFree : num 0 0 0 1 1 1 0 0 0 0 ...
## $ Job.UnemployedUnskilled : num 0 0 0 0 0 0 0 0 0 0 ...
## $ Job.UnskilledResident : num 0 0 1 0 0 1 0 0 1 0 ...
## $ Job.SkilledEmployee : num 1 1 0 1 1 0 1 0 0 0 ...
## $ Job.Management.SelfEmp.HighlyQualified: num 0 0 0 0 0 0 0 1 0 1 ...
#load tree model packages
library(rpart)
library(rpart.plot)
#This is the code that drop variables that provide no useful information in the data
#Only run this code chunk ONCE.
GermanCredit = GermanCredit[,-c(14,19,27,30,35,40,44,45,48,52,55,58,62)]
2024 for
reproducibility. (2.5pts)set.seed(2024)
train_index <- createDataPartition(GermanCredit$Class, p = 0.8, list = FALSE)
train <- GermanCredit[train_index, ]
test <- GermanCredit[-train_index, ]
Class) are
right. (5pts)class_tree <- rpart(Class ~ ., data = train, method = "class")
class_tree
## n= 800
##
## node), split, n, loss, yval, (yprob)
## * denotes terminal node
##
## 1) root 800 240 1 (0.30000000 0.70000000)
## 2) CheckingAccountStatus.lt.0>=0.5 226 110 0 (0.51327434 0.48672566)
## 4) Duration>=11.5 190 81 0 (0.57368421 0.42631579)
## 8) Duration>=31.5 44 9 0 (0.79545455 0.20454545) *
## 9) Duration< 31.5 146 72 0 (0.50684932 0.49315068)
## 18) Amount< 1381.5 44 14 0 (0.68181818 0.31818182) *
## 19) Amount>=1381.5 102 44 1 (0.43137255 0.56862745)
## 38) Purpose.UsedCar< 0.5 92 43 1 (0.46739130 0.53260870)
## 76) Age>=39.5 18 5 0 (0.72222222 0.27777778) *
## 77) Age< 39.5 74 30 1 (0.40540541 0.59459459)
## 154) Amount< 3571 52 25 1 (0.48076923 0.51923077)
## 308) Amount>=3106 11 1 0 (0.90909091 0.09090909) *
## 309) Amount< 3106 41 15 1 (0.36585366 0.63414634)
## 618) Duration>=16.5 28 14 0 (0.50000000 0.50000000)
## 1236) Amount< 2478 21 8 0 (0.61904762 0.38095238) *
## 1237) Amount>=2478 7 1 1 (0.14285714 0.85714286) *
## 619) Duration< 16.5 13 1 1 (0.07692308 0.92307692) *
## 155) Amount>=3571 22 5 1 (0.22727273 0.77272727) *
## 39) Purpose.UsedCar>=0.5 10 1 1 (0.10000000 0.90000000) *
## 5) Duration< 11.5 36 7 1 (0.19444444 0.80555556) *
## 3) CheckingAccountStatus.lt.0< 0.5 574 124 1 (0.21602787 0.78397213)
## 6) CheckingAccountStatus.0.to.200>=0.5 222 82 1 (0.36936937 0.63063063)
## 12) Amount>=9908.5 15 1 0 (0.93333333 0.06666667) *
## 13) Amount< 9908.5 207 68 1 (0.32850242 0.67149758)
## 26) Purpose.NewCar>=0.5 43 21 0 (0.51162791 0.48837209)
## 52) Amount< 1306.5 16 4 0 (0.75000000 0.25000000) *
## 53) Amount>=1306.5 27 10 1 (0.37037037 0.62962963)
## 106) Age< 29.5 12 4 0 (0.66666667 0.33333333) *
## 107) Age>=29.5 15 2 1 (0.13333333 0.86666667) *
## 27) Purpose.NewCar< 0.5 164 46 1 (0.28048780 0.71951220)
## 54) Duration>=33 33 16 1 (0.48484848 0.51515152)
## 108) SavingsAccountBonds.lt.100>=0.5 19 6 0 (0.68421053 0.31578947) *
## 109) SavingsAccountBonds.lt.100< 0.5 14 3 1 (0.21428571 0.78571429) *
## 55) Duration< 33 131 30 1 (0.22900763 0.77099237) *
## 7) CheckingAccountStatus.0.to.200< 0.5 352 42 1 (0.11931818 0.88068182) *
Your Answer: The classification tree uses all remaining predictors to classify customers as having good (1) or bad (0) credit. Class is a factor because the response is categorical.
rpart.plot(class_tree)
train_pred <- predict(class_tree, newdata = train, type = "class")
head(train_pred)
## 1 2 3 4 5 6
## 1 0 1 0 0 1
## Levels: 0 1
confusionMatrix(train_pred, train$Class, positive = "1")
## Confusion Matrix and Statistics
##
## Reference
## Prediction 0 1
## 0 148 52
## 1 92 508
##
## Accuracy : 0.82
## 95% CI : (0.7916, 0.846)
## No Information Rate : 0.7
## P-Value [Acc > NIR] : 5.501e-15
##
## Kappa : 0.55
##
## Mcnemar's Test P-Value : 0.001154
##
## Sensitivity : 0.9071
## Specificity : 0.6167
## Pos Pred Value : 0.8467
## Neg Pred Value : 0.7400
## Prevalence : 0.7000
## Detection Rate : 0.6350
## Detection Prevalence : 0.7500
## Balanced Accuracy : 0.7619
##
## 'Positive' Class : 1
##
train_mr <- mean(train_pred != train$Class)
train_mr
## [1] 0.18
Your Answer: The training misclassification rate is 18%. This is the percentage of training observations that the model classified incorrectly.
test_pred <- predict(class_tree, newdata = test, type = "class")
head(test_pred)
## 17 21 24 28 33 46
## 1 1 1 1 1 1
## Levels: 0 1
confusionMatrix(test_pred, test$Class, positive = "1")
## Confusion Matrix and Statistics
##
## Reference
## Prediction 0 1
## 0 22 21
## 1 38 119
##
## Accuracy : 0.705
## 95% CI : (0.6366, 0.7672)
## No Information Rate : 0.7
## P-Value [Acc > NIR] : 0.47335
##
## Kappa : 0.2358
##
## Mcnemar's Test P-Value : 0.03725
##
## Sensitivity : 0.8500
## Specificity : 0.3667
## Pos Pred Value : 0.7580
## Neg Pred Value : 0.5116
## Prevalence : 0.7000
## Detection Rate : 0.5950
## Detection Prevalence : 0.7850
## Balanced Accuracy : 0.6083
##
## 'Positive' Class : 1
##
test_mr <- mean(test_pred != test$Class)
test_mr
## [1] 0.295
Your Answer: The testing misclassification rate is 29.5%. This measures how often the model incorrectly classifies new observations.
library(pROC)
## Type 'citation("pROC")' for a citation.
##
## Attaching package: 'pROC'
## The following objects are masked from 'package:stats':
##
## cov, smooth, var
test_prob <- predict(class_tree, newdata = test, type = "prob")[, "1"]
roc_tree <- roc(test$Class, test_prob, levels = c("0", "1"), direction = "<")
plot(roc_tree, main = "Testing ROC Curve")
auc(roc_tree)
## Area under the curve: 0.6755
# Select the complexity parameter using training cross-validation.
best_cp <- class_tree$cptable[which.min(class_tree$cptable[, "xerror"]), "CP"]
pruned_tree <- prune(class_tree, cp = best_cp)
pruned_pred <- predict(pruned_tree, newdata = test, type = "class")
pruned_mr <- mean(pruned_pred != test$Class)
pruned_prob <- predict(pruned_tree, newdata = test, type = "prob")[, "1"]
pruned_auc <- auc(roc(test$Class, pruned_prob, levels = c("0", "1"), direction = "<"))
pruned_mr
## [1] 0.305
pruned_auc
## Area under the curve: 0.6732
The original testing MR was 0.295 and the pruned testing MR was 0.305. The original AUC was 0.675 and the pruned AUC was 0.673. Lower MR and higher AUC indicate better performance.
We will use the built-in mtcars dataset to predict miles per gallon (mpg) using other car characteristics. The dataset includes information about 32 cars from Motor Trend magazine (1973-74).
# Load the mtcars dataset
data(mtcars)
# Display the structure of the dataset
str(mtcars)
## 'data.frame': 32 obs. of 11 variables:
## $ mpg : num 21 21 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 ...
## $ cyl : num 6 6 4 6 8 6 8 4 4 6 ...
## $ disp: num 160 160 108 258 360 ...
## $ hp : num 110 110 93 110 175 105 245 62 95 123 ...
## $ drat: num 3.9 3.9 3.85 3.08 3.15 2.76 3.21 3.69 3.92 3.92 ...
## $ wt : num 2.62 2.88 2.32 3.21 3.44 ...
## $ qsec: num 16.5 17 18.6 19.4 17 ...
## $ vs : num 0 0 1 1 0 1 0 1 1 1 ...
## $ am : num 1 1 1 0 0 0 0 0 0 0 ...
## $ gear: num 4 4 4 3 3 3 3 4 4 4 ...
## $ carb: num 4 4 1 1 2 1 4 2 2 4 ...
set.seed(2020)
car_index <- sample(1:nrow(mtcars), size = round(0.8 * nrow(mtcars)))
car_train <- mtcars[car_index, ]
car_test <- mtcars[-car_index, ]
reg_tree <- rpart(mpg ~ ., data = car_train, method = "anova")
reg_tree
## n= 26
##
## node), split, n, deviance, yval
## * denotes terminal node
##
## 1) root 26 847.9665 20.01154
## 2) cyl>=5 18 147.3378 17.01111 *
## 3) cyl< 5 8 173.9787 26.76250 *
rpart.plot(reg_tree)
Your Answer: The regression tree splits cars into groups based on their characteristics. The first split uses cyl to separate cars into groups with different predicted MPG values. Each terminal node represents the average MPG of the training cars in that group.
car_train_pred <- predict(reg_tree, newdata = car_train)
train_mse <- mean((car_train$mpg - car_train_pred)^2)
train_r2 <- 1 - sum((car_train$mpg - car_train_pred)^2) / sum((car_train$mpg - mean(car_train$mpg))^2)
train_mse
## [1] 12.35833
train_r2
## [1] 0.621074
Your Answer: The training MSE is 12.358 and the training R-squared is 0.621. MSE measures the average squared prediction error, while R-squared measures the proportion of variation explained by the model on the training data.
car_test_pred <- predict(reg_tree, newdata = car_test)
test_mse <- mean((car_test$mpg - car_test_pred)^2)
test_r2 <- 1 - sum((car_test$mpg - car_test_pred)^2) / sum((car_test$mpg - mean(car_test$mpg))^2)
test_mse
## [1] 13.90391
test_r2
## [1] 0.699064
Your Answer: The testing MSE is 13.904 and the testing R-squared is 0.699. These values measure how well the model predicts MPG for cars that were not used to train it. Lower MSE and higher R-squared indicate better predictions. A negative testing R-squared means the predictions are worse than using the testing mean as a baseline.