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 package
caret. The German credit scoring data is
provided in that package.
install.packages('caret')
library(caret) #this package contains the german data with its numeric format
## Warning: package 'caret' was built under R version 4.6.2
## Loading required package: ggplot2
## Warning: package 'ggplot2' was built under R version 4.6.1
## 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)
## Warning: package 'rpart.plot' was built under R version 4.6.2
#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.80,
list = FALSE
)
GermanCredit_train <- GermanCredit[train_index, ]
GermanCredit_test <- GermanCredit[-train_index, ]
Class) are
right. (5pts)GermanCredit_tree <- rpart(
Class ~ .,
data = GermanCredit_train,
method = "class"
)
print(GermanCredit_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 tree uses different things to help predict if someone is a good or bad credit risk. Some of the main things it looks at are checking account status, loan duration, loan amount, age, and what the loan is for. Checking account status seems to be the biggest factor since it’s the first thing the tree looks at when making predictions.
rpart.plot(GermanCredit_tree, type = 3, extra = 104, fallen.leaves = TRUE)
GermanCredit_train_pred <- predict(
GermanCredit_tree,
GermanCredit_train,
type = "class"
)
head(GermanCredit_train_pred)
## 1 2 3 4 5 6
## 1 0 1 0 0 1
## Levels: 0 1
train_confusion <- confusionMatrix(
GermanCredit_train_pred,
GermanCredit_train$Class
)
train_confusion
## 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.6167
## Specificity : 0.9071
## Pos Pred Value : 0.7400
## Neg Pred Value : 0.8467
## Prevalence : 0.3000
## Detection Rate : 0.1850
## Detection Prevalence : 0.2500
## Balanced Accuracy : 0.7619
##
## 'Positive' Class : 0
##
train_MR <- 1 - train_confusion$overall["Accuracy"]
train_MR
## Accuracy
## 0.18
Your Answer: Accuracy: 82% Misclassification rate: 0.18, or 18% Correct predictions: 656 Incorrect predictions: 144
GermanCredit_test_pred <- predict(
GermanCredit_tree,
GermanCredit_test,
type = "class"
)
head(GermanCredit_test_pred)
## 17 21 24 28 33 46
## 1 1 1 1 1 1
## Levels: 0 1
test_confusion <- confusionMatrix(
GermanCredit_test_pred,
GermanCredit_test$Class
)
test_confusion
## 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.3667
## Specificity : 0.8500
## Pos Pred Value : 0.5116
## Neg Pred Value : 0.7580
## Prevalence : 0.3000
## Detection Rate : 0.1100
## Detection Prevalence : 0.2150
## Balanced Accuracy : 0.6083
##
## 'Positive' Class : 0
##
test_MR <- 1 - test_confusion$overall["Accuracy"]
test_MR
## Accuracy
## 0.295
Your Answer: Accuracy: 70.5% Misclassification rate: 0.295, or 29.5% Correct predictions: 141 Incorrect predictions: 59 The model did better on the training data (82% accuracy) than the testing data (70.5%). This suggests it doesn’t perform quite as well on data it hasn’t seen before. ### 9. Obtain the ROC and AUC for testing data (not training). (2.5pts)
test_prob <- predict(
GermanCredit_tree,
GermanCredit_test,
type = "prob"
)
library(pROC)
## Warning: package 'pROC' was built under R version 4.6.1
## Type 'citation("pROC")' for a citation.
##
## Attaching package: 'pROC'
## The following objects are masked from 'package:stats':
##
## cov, smooth, var
roc_curve <- roc(
GermanCredit_test$Class,
test_prob[, "0"]
)
## Setting levels: control = 0, case = 1
## Setting direction: controls > cases
plot(roc_curve, main = "ROC Curve for Classification Tree")
auc(roc_curve)
## Area under the curve: 0.6755
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)
index <- sample(1:nrow(mtcars), floor(nrow(mtcars) * 0.80))
mtcars.train <- mtcars[index, ]
mtcars.test <- mtcars[-index, ]
nrow(mtcars.train)
## [1] 25
nrow(mtcars.test)
## [1] 7
library(rpart)
mtcars_tree <- rpart(
mpg ~ .,
data = mtcars.train,
method = "anova"
)
print(mtcars_tree)
## n= 25
##
## node), split, n, deviance, yval
## * denotes terminal node
##
## 1) root 25 829.5200 20.18000
## 2) cyl>=5 17 145.7847 17.08235 *
## 3) cyl< 5 8 173.9787 26.76250 *
library(rpart.plot)
rpart.plot(
mtcars_tree,
type = 3,
extra = 101,
fallen.leaves = TRUE
)
Your Answer: The regression tree uses the number of cylinders to predict
a car’s miles per gallon. Cars with 5 or more cylinders have a predicted
mpg of 17, while cars with fewer than 5 cylinders have a predicted mpg
of 27. This shows that cars with fewer cylinders tend to get better gas
mileage in this model. ### 4. Make predictions and calculate MSE and
R-squared on training set. (5pts)
train_pred <- predict(mtcars_tree, mtcars.train)
train_MSE <- mean((mtcars.train$mpg - train_pred)^2)
train_R2 <- 1 - sum((mtcars.train$mpg - train_pred)^2) /
sum((mtcars.train$mpg - mean(mtcars.train$mpg))^2)
train_MSE
## [1] 12.79054
train_R2
## [1] 0.6145199
Your Answer: The training MSE is 12.79054, and the R-squared is 0.6145. This means the model explains about 61.45% of the variation in mpg for the training data. Overall, the model does a decent job predicting gas mileage, but it doesn’t explain all of the differences between cars. ### 5. Make predictions and calculate MSE and R-squared on testing set. (5pts)
test_pred <- predict(mtcars_tree, mtcars.test)
test_MSE <- mean((mtcars.test$mpg - test_pred)^2)
test_R2 <- 1 - sum((mtcars.test$mpg - test_pred)^2) /
sum((mtcars.test$mpg - mean(mtcars.test$mpg))^2)
test_MSE
## [1] 12.31011
test_R2
## [1] 0.7085027
Your Answer: The testing MSE is 12.31011, and the R-squared is 0.7085. This means the model explains about 70.85% of the variation in mpg for the testing data. The model actually performed a little better on the testing data than the training data, which is a good sign.