Starter code for German credit scoring

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 in provided in that package.

install.packages('caret')

Task1: Data Preparation

1. Load the caret package and the GermanCredit dataset. (5pts)

library(caret) #this package contains the german data with its numeric format
## Loading required package: ggplot2
## Loading required package: lattice
data(GermanCredit)
GermanCredit$Class <-  as.numeric(GermanCredit$Class == "Good") # use this code to convert `Class` into True or False (equivalent to 1 or 0)
GermanCredit$Class <- as.factor(GermanCredit$Class) #make sure `Class` is a factor as SVM require a factor response,now 1 is good and 0 is bad.
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 ...
# This is the code that drop variables that provide no information in the data
# Just run it
GermanCredit = GermanCredit[,-c(14,19,27,30,35,40,44,45,48,52,55,58,62)]

2. Explore the dataset to understand its structure. It’s okay to use same code from last homework. (2.5pts)

head(GermanCredit)
##   Duration Amount InstallmentRatePercentage ResidenceDuration Age
## 1        6   1169                         4                 4  67
## 2       48   5951                         2                 2  22
## 3       12   2096                         2                 3  49
## 4       42   7882                         2                 4  45
## 5       24   4870                         3                 4  53
## 6       36   9055                         2                 4  35
##   NumberExistingCredits NumberPeopleMaintenance Telephone ForeignWorker Class
## 1                     2                       1         0             1     1
## 2                     1                       1         1             1     0
## 3                     1                       2         1             1     1
## 4                     1                       2         1             1     1
## 5                     2                       2         1             1     0
## 6                     1                       2         0             1     1
##   CheckingAccountStatus.lt.0 CheckingAccountStatus.0.to.200
## 1                          1                              0
## 2                          0                              1
## 3                          0                              0
## 4                          1                              0
## 5                          1                              0
## 6                          0                              0
##   CheckingAccountStatus.gt.200 CreditHistory.NoCredit.AllPaid
## 1                            0                              0
## 2                            0                              0
## 3                            0                              0
## 4                            0                              0
## 5                            0                              0
## 6                            0                              0
##   CreditHistory.ThisBank.AllPaid CreditHistory.PaidDuly CreditHistory.Delay
## 1                              0                      0                   0
## 2                              0                      1                   0
## 3                              0                      0                   0
## 4                              0                      1                   0
## 5                              0                      0                   1
## 6                              0                      1                   0
##   Purpose.NewCar Purpose.UsedCar Purpose.Furniture.Equipment
## 1              0               0                           0
## 2              0               0                           0
## 3              0               0                           0
## 4              0               0                           1
## 5              1               0                           0
## 6              0               0                           0
##   Purpose.Radio.Television Purpose.DomesticAppliance Purpose.Repairs
## 1                        1                         0               0
## 2                        1                         0               0
## 3                        0                         0               0
## 4                        0                         0               0
## 5                        0                         0               0
## 6                        0                         0               0
##   Purpose.Education Purpose.Retraining Purpose.Business
## 1                 0                  0                0
## 2                 0                  0                0
## 3                 1                  0                0
## 4                 0                  0                0
## 5                 0                  0                0
## 6                 1                  0                0
##   SavingsAccountBonds.lt.100 SavingsAccountBonds.100.to.500
## 1                          0                              0
## 2                          1                              0
## 3                          1                              0
## 4                          1                              0
## 5                          1                              0
## 6                          0                              0
##   SavingsAccountBonds.500.to.1000 SavingsAccountBonds.gt.1000
## 1                               0                           0
## 2                               0                           0
## 3                               0                           0
## 4                               0                           0
## 5                               0                           0
## 6                               0                           0
##   EmploymentDuration.lt.1 EmploymentDuration.1.to.4 EmploymentDuration.4.to.7
## 1                       0                         0                         0
## 2                       0                         1                         0
## 3                       0                         0                         1
## 4                       0                         0                         1
## 5                       0                         1                         0
## 6                       0                         1                         0
##   EmploymentDuration.gt.7 Personal.Male.Divorced.Seperated
## 1                       1                                0
## 2                       0                                0
## 3                       0                                0
## 4                       0                                0
## 5                       0                                0
## 6                       0                                0
##   Personal.Female.NotSingle Personal.Male.Single OtherDebtorsGuarantors.None
## 1                         0                    1                           1
## 2                         1                    0                           1
## 3                         0                    1                           1
## 4                         0                    1                           0
## 5                         0                    1                           1
## 6                         0                    1                           1
##   OtherDebtorsGuarantors.CoApplicant Property.RealEstate Property.Insurance
## 1                                  0                   1                  0
## 2                                  0                   1                  0
## 3                                  0                   1                  0
## 4                                  0                   0                  1
## 5                                  0                   0                  0
## 6                                  0                   0                  0
##   Property.CarOther OtherInstallmentPlans.Bank OtherInstallmentPlans.Stores
## 1                 0                          0                            0
## 2                 0                          0                            0
## 3                 0                          0                            0
## 4                 0                          0                            0
## 5                 0                          0                            0
## 6                 0                          0                            0
##   Housing.Rent Housing.Own Job.UnemployedUnskilled Job.UnskilledResident
## 1            0           1                       0                     0
## 2            0           1                       0                     0
## 3            0           1                       0                     1
## 4            0           0                       0                     0
## 5            0           0                       0                     0
## 6            0           0                       0                     1
##   Job.SkilledEmployee
## 1                   1
## 2                   1
## 3                   0
## 4                   1
## 5                   1
## 6                   0
dim(GermanCredit)
## [1] 1000   49
str(GermanCredit)
## 'data.frame':    1000 obs. of  49 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 ...
##  $ 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 ...
##  $ 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.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 ...
##  $ 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 ...
##  $ 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 ...
##  $ 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 ...
##  $ 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 ...
##  $ 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 ...
##  $ 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 ...
##  $ 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 ...
##  $ 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 ...
summary(GermanCredit)
##     Duration        Amount      InstallmentRatePercentage ResidenceDuration
##  Min.   : 4.0   Min.   :  250   Min.   :1.000             Min.   :1.000    
##  1st Qu.:12.0   1st Qu.: 1366   1st Qu.:2.000             1st Qu.:2.000    
##  Median :18.0   Median : 2320   Median :3.000             Median :3.000    
##  Mean   :20.9   Mean   : 3271   Mean   :2.973             Mean   :2.845    
##  3rd Qu.:24.0   3rd Qu.: 3972   3rd Qu.:4.000             3rd Qu.:4.000    
##  Max.   :72.0   Max.   :18424   Max.   :4.000             Max.   :4.000    
##       Age        NumberExistingCredits NumberPeopleMaintenance   Telephone    
##  Min.   :19.00   Min.   :1.000         Min.   :1.000           Min.   :0.000  
##  1st Qu.:27.00   1st Qu.:1.000         1st Qu.:1.000           1st Qu.:0.000  
##  Median :33.00   Median :1.000         Median :1.000           Median :1.000  
##  Mean   :35.55   Mean   :1.407         Mean   :1.155           Mean   :0.596  
##  3rd Qu.:42.00   3rd Qu.:2.000         3rd Qu.:1.000           3rd Qu.:1.000  
##  Max.   :75.00   Max.   :4.000         Max.   :2.000           Max.   :1.000  
##  ForeignWorker   Class   CheckingAccountStatus.lt.0
##  Min.   :0.000   0:300   Min.   :0.000             
##  1st Qu.:1.000   1:700   1st Qu.:0.000             
##  Median :1.000           Median :0.000             
##  Mean   :0.963           Mean   :0.274             
##  3rd Qu.:1.000           3rd Qu.:1.000             
##  Max.   :1.000           Max.   :1.000             
##  CheckingAccountStatus.0.to.200 CheckingAccountStatus.gt.200
##  Min.   :0.000                  Min.   :0.000               
##  1st Qu.:0.000                  1st Qu.:0.000               
##  Median :0.000                  Median :0.000               
##  Mean   :0.269                  Mean   :0.063               
##  3rd Qu.:1.000                  3rd Qu.:0.000               
##  Max.   :1.000                  Max.   :1.000               
##  CreditHistory.NoCredit.AllPaid CreditHistory.ThisBank.AllPaid
##  Min.   :0.00                   Min.   :0.000                 
##  1st Qu.:0.00                   1st Qu.:0.000                 
##  Median :0.00                   Median :0.000                 
##  Mean   :0.04                   Mean   :0.049                 
##  3rd Qu.:0.00                   3rd Qu.:0.000                 
##  Max.   :1.00                   Max.   :1.000                 
##  CreditHistory.PaidDuly CreditHistory.Delay Purpose.NewCar  Purpose.UsedCar
##  Min.   :0.00           Min.   :0.000       Min.   :0.000   Min.   :0.000  
##  1st Qu.:0.00           1st Qu.:0.000       1st Qu.:0.000   1st Qu.:0.000  
##  Median :1.00           Median :0.000       Median :0.000   Median :0.000  
##  Mean   :0.53           Mean   :0.088       Mean   :0.234   Mean   :0.103  
##  3rd Qu.:1.00           3rd Qu.:0.000       3rd Qu.:0.000   3rd Qu.:0.000  
##  Max.   :1.00           Max.   :1.000       Max.   :1.000   Max.   :1.000  
##  Purpose.Furniture.Equipment Purpose.Radio.Television Purpose.DomesticAppliance
##  Min.   :0.000               Min.   :0.00             Min.   :0.000            
##  1st Qu.:0.000               1st Qu.:0.00             1st Qu.:0.000            
##  Median :0.000               Median :0.00             Median :0.000            
##  Mean   :0.181               Mean   :0.28             Mean   :0.012            
##  3rd Qu.:0.000               3rd Qu.:1.00             3rd Qu.:0.000            
##  Max.   :1.000               Max.   :1.00             Max.   :1.000            
##  Purpose.Repairs Purpose.Education Purpose.Retraining Purpose.Business
##  Min.   :0.000   Min.   :0.00      Min.   :0.000      Min.   :0.000   
##  1st Qu.:0.000   1st Qu.:0.00      1st Qu.:0.000      1st Qu.:0.000   
##  Median :0.000   Median :0.00      Median :0.000      Median :0.000   
##  Mean   :0.022   Mean   :0.05      Mean   :0.009      Mean   :0.097   
##  3rd Qu.:0.000   3rd Qu.:0.00      3rd Qu.:0.000      3rd Qu.:0.000   
##  Max.   :1.000   Max.   :1.00      Max.   :1.000      Max.   :1.000   
##  SavingsAccountBonds.lt.100 SavingsAccountBonds.100.to.500
##  Min.   :0.000              Min.   :0.000                 
##  1st Qu.:0.000              1st Qu.:0.000                 
##  Median :1.000              Median :0.000                 
##  Mean   :0.603              Mean   :0.103                 
##  3rd Qu.:1.000              3rd Qu.:0.000                 
##  Max.   :1.000              Max.   :1.000                 
##  SavingsAccountBonds.500.to.1000 SavingsAccountBonds.gt.1000
##  Min.   :0.000                   Min.   :0.000              
##  1st Qu.:0.000                   1st Qu.:0.000              
##  Median :0.000                   Median :0.000              
##  Mean   :0.063                   Mean   :0.048              
##  3rd Qu.:0.000                   3rd Qu.:0.000              
##  Max.   :1.000                   Max.   :1.000              
##  EmploymentDuration.lt.1 EmploymentDuration.1.to.4 EmploymentDuration.4.to.7
##  Min.   :0.000           Min.   :0.000             Min.   :0.000            
##  1st Qu.:0.000           1st Qu.:0.000             1st Qu.:0.000            
##  Median :0.000           Median :0.000             Median :0.000            
##  Mean   :0.172           Mean   :0.339             Mean   :0.174            
##  3rd Qu.:0.000           3rd Qu.:1.000             3rd Qu.:0.000            
##  Max.   :1.000           Max.   :1.000             Max.   :1.000            
##  EmploymentDuration.gt.7 Personal.Male.Divorced.Seperated
##  Min.   :0.000           Min.   :0.00                    
##  1st Qu.:0.000           1st Qu.:0.00                    
##  Median :0.000           Median :0.00                    
##  Mean   :0.253           Mean   :0.05                    
##  3rd Qu.:1.000           3rd Qu.:0.00                    
##  Max.   :1.000           Max.   :1.00                    
##  Personal.Female.NotSingle Personal.Male.Single OtherDebtorsGuarantors.None
##  Min.   :0.00              Min.   :0.000        Min.   :0.000              
##  1st Qu.:0.00              1st Qu.:0.000        1st Qu.:1.000              
##  Median :0.00              Median :1.000        Median :1.000              
##  Mean   :0.31              Mean   :0.548        Mean   :0.907              
##  3rd Qu.:1.00              3rd Qu.:1.000        3rd Qu.:1.000              
##  Max.   :1.00              Max.   :1.000        Max.   :1.000              
##  OtherDebtorsGuarantors.CoApplicant Property.RealEstate Property.Insurance
##  Min.   :0.000                      Min.   :0.000       Min.   :0.000     
##  1st Qu.:0.000                      1st Qu.:0.000       1st Qu.:0.000     
##  Median :0.000                      Median :0.000       Median :0.000     
##  Mean   :0.041                      Mean   :0.282       Mean   :0.232     
##  3rd Qu.:0.000                      3rd Qu.:1.000       3rd Qu.:0.000     
##  Max.   :1.000                      Max.   :1.000       Max.   :1.000     
##  Property.CarOther OtherInstallmentPlans.Bank OtherInstallmentPlans.Stores
##  Min.   :0.000     Min.   :0.000              Min.   :0.000               
##  1st Qu.:0.000     1st Qu.:0.000              1st Qu.:0.000               
##  Median :0.000     Median :0.000              Median :0.000               
##  Mean   :0.332     Mean   :0.139              Mean   :0.047               
##  3rd Qu.:1.000     3rd Qu.:0.000              3rd Qu.:0.000               
##  Max.   :1.000     Max.   :1.000              Max.   :1.000               
##   Housing.Rent    Housing.Own    Job.UnemployedUnskilled Job.UnskilledResident
##  Min.   :0.000   Min.   :0.000   Min.   :0.000           Min.   :0.0          
##  1st Qu.:0.000   1st Qu.:0.000   1st Qu.:0.000           1st Qu.:0.0          
##  Median :0.000   Median :1.000   Median :0.000           Median :0.0          
##  Mean   :0.179   Mean   :0.713   Mean   :0.022           Mean   :0.2          
##  3rd Qu.:0.000   3rd Qu.:1.000   3rd Qu.:0.000           3rd Qu.:0.0          
##  Max.   :1.000   Max.   :1.000   Max.   :1.000           Max.   :1.0          
##  Job.SkilledEmployee
##  Min.   :0.00       
##  1st Qu.:0.00       
##  Median :1.00       
##  Mean   :0.63       
##  3rd Qu.:1.00       
##  Max.   :1.00
table(GermanCredit$Class)
## 
##   0   1 
## 300 700
sum(is.na(GermanCredit))
## [1] 0

Your observation: The GermanCredit dataset contains both numerical and categorical variables that describe customers’ credit information. The Class variable identifies whether a customer has good or bad credit. Exploring the dataset using summary statistics and structure functions helps us understand the variables, their data types, and the distribution of credit classifications before building the SVM model.

3. Split the dataset into training and test set with 80-20 split. Please use the random seed as 2024 for reproducibility. (2.5pts)

# Set the seed 
set.seed(2024)

trainIndex <- createDataPartition(
  GermanCredit$Class,
  p = 0.8,
  list = FALSE
)

training <- GermanCredit[trainIndex, ]

testing <- GermanCredit[-trainIndex, ]

# Check dataset dimensions
dim(training)
## [1] 800  49
dim(testing)
## [1] 200  49

Your observation: The dataset was divided into 80% training data and 20% testing data. Using set.seed(2024) ensures that the same random split can be reproduced each time the code is run. The createDataPartition() function also maintains a similar proportion of good and bad credit observations in both datasets.

Task 2: SVM without weighted class cost (15pts)

1. Fit a SVM model using the training set with linear kernel. Please use all variables, but make sure the variable types are right. If running on old laptop, could take some time! (5pts)

library(e1071)
## 
## Attaching package: 'e1071'
## The following object is masked from 'package:ggplot2':
## 
##     element
# Fit the SVM model using the training data
svm_model <- svm(
  Class ~ .,
  data = training,
  kernel = "linear"
)

# Display the model results
print(svm_model)
## 
## Call:
## svm(formula = Class ~ ., data = training, kernel = "linear")
## 
## 
## Parameters:
##    SVM-Type:  C-classification 
##  SVM-Kernel:  linear 
##        cost:  1 
## 
## Number of Support Vectors:  403

Your observation: The SVM model was trained using the training dataset with a linear kernel. All available predictor variables were included to predict whether a customer has good or bad credit. The response variable was kept as a factor so the model could perform classification.

2. Use the training set to get predicted classes. (2.5pts)

# Predict classes using the training data
svm_train_pred <- predict(svm_model, newdata = training)

# View the first six predictions
head(svm_train_pred)
## 1 2 3 4 5 6 
## 1 0 1 1 0 1 
## Levels: 0 1

Your observation: The trained SVM model was used to predict credit classifications for the training dataset. The predictions identify whether each customer is classified as having good or bad credit.

3. Obtain confusion matrix and MR on training set. (2.5pts)

# Obtain the confusion matrix
confusion_matrix <- table(
  Actual = training$Class,
  Predicted = svm_train_pred
)

print(confusion_matrix)
##       Predicted
## Actual   0   1
##      0 148  92
##      1  68 492
# Calculate misclassification rate
MR_train <- mean(svm_train_pred != training$Class)

print(paste("Training Misclassification Rate:", MR_train))
## [1] "Training Misclassification Rate: 0.2"

Your observation: The confusion matrix compares the actual credit classifications with the classifications predicted by the SVM model. The misclassification rate measures the percentage of incorrectly classified observations. A lower misclassification rate indicates better prediction accuracy on the training dataset.

4. Use the testing set to get predicted classes. (2.5pts)

svm_test_pred <- predict(svm_model, newdata = testing)

head(svm_test_pred)
## 17 21 24 28 33 46 
##  1  1  1  1  1  1 
## Levels: 0 1

Your observation: The trained SVM model was used to predict credit classifications for the testing dataset. These predictions show whether each customer is classified as having good or bad credit.

5. Obtain confusion matrix and MR on testing set. (2.5pts)

confusion_matrix_test <- table(
  Actual = testing$Class,
  Predicted = svm_test_pred
)

print(confusion_matrix_test)
##       Predicted
## Actual   0   1
##      0  31  29
##      1  24 116
MR_test <- mean(svm_test_pred != testing$Class)
print(paste("Testing Misclassification Rate:", MR_test))
## [1] "Testing Misclassification Rate: 0.265"

Your observation: The confusion matrix compares the actual credit classifications in the testing dataset with the classifications predicted by the SVM model. The testing misclassification rate measures the proportion of predictions that were incorrect. This helps evaluate how well the model performs on data it was not trained on.

Task 3: SVM with weighted class cost, and probabilities enabled (17.5pts ,each 2.5pts)

1. Fit a SVM model using the training set with weight of 2 on “1” and weight of 1 on “0”. Please use all variables, but make sure the variable types are right. Also, enable probability fitting with probability = TRUE.

svm_weighted <- svm(
  Class ~ .,
  data = training,
  kernel = "linear",
  class.weights = c("0" = 1, "1" = 2),
  probability = TRUE
)

print(svm_weighted)
## 
## Call:
## svm(formula = Class ~ ., data = training, kernel = "linear", class.weights = c(`0` = 1, 
##     `1` = 2), probability = TRUE)
## 
## 
## Parameters:
##    SVM-Type:  C-classification 
##  SVM-Kernel:  linear 
##        cost:  1 
## 
## Number of Support Vectors:  378

Your observation: The weighted SVM model was trained using the training dataset with a linear kernel. A weight of 2 was assigned to class 1 and a weight of 1 to class 0 to give greater importance to correctly classifying class 1. Probability fitting was also enabled to allow the model to estimate classification probabilities.

2. Use the training set to get predicted probabilities and classes.

# Predict classes
svm_train_pred_weighted <- predict(
  svm_weighted,
  newdata = training,
  probability = TRUE
)

# Extract predicted probabilities
svm_train_prob <- attr(svm_train_pred_weighted, "probabilities")

# View predicted classes
head(svm_train_pred_weighted)
## 1 2 3 4 5 6 
## 1 0 1 1 0 1 
## Levels: 0 1
# View predicted probabilities
head(svm_train_prob)
##           1          0
## 1 0.8407723 0.15922768
## 2 0.4059899 0.59401014
## 3 0.9206866 0.07931335
## 4 0.7775040 0.22249604
## 5 0.2748831 0.72511691
## 6 0.7380708 0.26192923

Your observation: The weighted SVM model was used to predict credit classifications and their corresponding probabilities for the training dataset. The predicted classes show whether each customer is classified as having good or bad credit, while the probabilities indicate the model’s confidence in each classification.

3. Obtain confusion matrix and MR on training set (use predicted classes).

confusion_matrix_weighted_train <- table(
  Actual = training$Class,
  Predicted = svm_train_pred_weighted
)

print(confusion_matrix_weighted_train)
##       Predicted
## Actual   0   1
##      0 101 139
##      1  24 536
MR_weighted_train <- mean(
  svm_train_pred_weighted != training$Class
)

print(paste("Training Misclassification Rate:", MR_weighted_train))
## [1] "Training Misclassification Rate: 0.20375"

Your observation: The confusion matrix compares the actual credit classifications with the classes predicted by the weighted SVM model. The misclassification rate measures the proportion of incorrect predictions on the training set.

4. Obtain ROC and AUC on training set (use predicted probabilities).

library(pROC)
## Type 'citation("pROC")' for a citation.
## 
## Attaching package: 'pROC'
## The following objects are masked from 'package:stats':
## 
##     cov, smooth, var
# Obtain probability of class 1
train_roc <- roc(
  response = training$Class,
  predictor = svm_train_prob[, "1"]
)
## Setting levels: control = 0, case = 1
## Setting direction: controls < cases
# Plot ROC curve
plot(train_roc, main = "ROC Curve - Weighted SVM Training Set")

# Calculate AUC
auc(train_roc)
## Area under the curve: 0.825

Your observation: The ROC curve evaluates how well the weighted SVM model distinguishes between the two credit classifications. The AUC measures the model’s ability to separate the classes, with a higher AUC indicating better classification performance.

5. Use the testing set to get predicted probabilities and classes.

# Predict classes
svm_test_pred_weighted <- predict(
  svm_weighted,
  newdata = testing,
  probability = TRUE
)

# Extract predicted probabilities
svm_test_prob <- attr(svm_test_pred_weighted, "probabilities")

# View predicted classes
head(svm_test_pred_weighted)
## 17 21 24 28 33 46 
##  1  1  1  1  1  1 
## Levels: 0 1
# View predicted probabilities
head(svm_test_prob)
##            1         0
## 17 0.8571835 0.1428165
## 21 0.8560695 0.1439305
## 24 0.8688477 0.1311523
## 28 0.8136918 0.1863082
## 33 0.7015288 0.2984712
## 46 0.7625487 0.2374513

Your observation: The weighted SVM model was used to predict credit classifications and their corresponding probabilities for the testing dataset. The predicted classes show whether each customer is classified as having good or bad credit, while the probabilities indicate the model’s confidence in each prediction.

6. Obtain confusion matrix and MR on testing set. (use predicted classes).

svm_test_pred_weighted <- predict(
  svm_weighted,
  newdata = testing,
  probability = TRUE
)

svm_test_prob <- attr(
  svm_test_pred_weighted,
  "probabilities"
)

head(svm_test_pred_weighted)
## 17 21 24 28 33 46 
##  1  1  1  1  1  1 
## Levels: 0 1
head(svm_test_prob)
##            1         0
## 17 0.8571835 0.1428165
## 21 0.8560695 0.1439305
## 24 0.8688477 0.1311523
## 28 0.8136918 0.1863082
## 33 0.7015288 0.2984712
## 46 0.7625487 0.2374513
confusion_matrix_weighted_test <- table(
  Actual = testing$Class,
  Predicted = svm_test_pred_weighted
)

print(confusion_matrix_weighted_test)
##       Predicted
## Actual   0   1
##      0  21  39
##      1  14 126
MR_weighted_test <- mean(
  svm_test_pred_weighted != testing$Class
)

print(paste("Testing Misclassification Rate:", MR_weighted_test))
## [1] "Testing Misclassification Rate: 0.265"

Your observation:

7. Obtain ROC and AUC on testing set. (use predicted probabilities).

test_roc <- roc(
  response = testing$Class,
  predictor = svm_test_prob[, "1"]
)
## Setting levels: control = 0, case = 1
## Setting direction: controls < cases
# Plot ROC curve
plot(test_roc, main = "ROC Curve - Weighted SVM Testing Set")

# Calculate AUC
auc(test_roc)
## Area under the curve: 0.7115

Your observation:

Task 4: Conclusion (7.5pts)

1. Summarize your findings and discuss what you observed from the above analysis. (2.5pts)

The SVM analysis showed how well the model could predict whether customers had good or bad credit. Using weighted class costs gave more importance to correctly identifying class 1 by assigning it twice the weight of class 0. The confusion matrices and misclassification rates helped evaluate the model’s accuracy on both the training and testing datasets. The ROC curves and AUC values provided another way to measure how well the model separated the two credit classes. Overall, comparing the training and testing results helps determine how well the model performs on new data rather than just the data it was trained on.

2. Please recall the results from last homework, how do you compare SVM to logistic regression? No coding is required for this question, just discuss. (5pts)

Both SVM and logistic regression were used to predict whether customers had good or bad credit using the GermanCredit dataset. Logistic regression estimates the probability of belonging to a class and makes it easier to interpret how individual variables affect the prediction. SVM focuses on finding the best boundary between the two classes. The weighted SVM model also gives more importance to class 1, which can help address differences in class importance. Overall, both methods can be useful for classification, but their performance should be compared using testing misclassification rates and AUC values to determine which model predicts credit classifications more accurately.

The previous logistic regression homework used the same GermanCredit dataset and a 700-observation training set with a 300-observation testing set. However, I don’t have the actual logistic regression testing MR or AUC results available, so I don’t want to claim that one model performed better without comparing the numbers.

3. (Optional) Change the kernel to others such as radial, and see if you got a better result.