Skip to Main Content
Is-what-Is

MSc Data Science / Module

Credit Classification

The project compared three machine learning classification methods for credit rating prediction: logistic regression, a perceptron and a decision tree. Logistic regression had the highest reported accuracy. The perceptron was second and the decision tree was third. The next stage of the project adds a random forest model and a Python web application for credit score classification.

Context

Background and Motivation

Online banking increases the amount of customer data that is available for credit assessment. Lenders must assess potential borrowers and make credit decisions with reliable methods.

Machine learning can use this data to support credit decisions. It does not replace a full credit assessment.

Context

Problem Statement

Can machine learning classification models accurately predict a person's credit rating?

Implementation

Data

The project uses the open-source Credit Score Classification dataset on Kaggle (opens in a new tab). The data contains customer information, financial characteristics, payment behaviour and a credit rating label for each record.

The dataset has two CSV files:

  • Training file. 100,000 records and 28 attributes, including the Credit_Score label.
  • Test file. 50,000 records and 27 attributes. This file has no Credit_Score label. This project did not use the test file.

Table 1. Dataset attributes. Column names are as in the source files.

AttributeDescription
IDUnique identifier for a data entry.
Customer_IDUnique identifier for a customer.
MonthMonth associated with the record.
NameCustomer's name.
AgeCustomer's age.
SSNCustomer's Social Security Number.
OccupationCustomer's occupation.
Annual_IncomeCustomer's annual income.
Monthly_Inhand_SalaryCustomer's monthly base salary.
Num_Bank_AccountsNumber of bank accounts held by the customer.
Num_Credit_CardNumber of credit cards held by the customer.
Interest_RateInterest rate on credit cards.
Num_of_LoanNumber of loans taken from a bank.
Type_of_LoanTypes of loans taken by the customer.
Delay_from_due_dateAverage number of days a payment is late.
Num_of_Delayed_PaymentAverage number of delayed payments.
Changed_Credit_LimitPercentage change in the credit card limit.
Num_Credit_InquiriesNumber of credit inquiries about the customer.
Credit_MixClassification of the customer's credit mix.
Outstanding_DebtRemaining debt, measured in USD.
Credit_Utilization_RatioProportion of available credit currently used.
Credit_History_AgeLength of the customer's credit history.
Payment_of_Min_AmountIndicates whether the customer paid only the minimum amount due.
Total_EMI_per_monthTotal monthly Equated Monthly Instalment (EMI) payments, measured in USD.
Amount_invested_monthlyAmount invested by the customer each month, measured in USD.
Payment_BehaviourCustomer spending and payment patterns.
Monthly_BalanceCustomer's monthly balance, measured in USD.
Credit_ScoreCredit rating category: Poor, Standard or Good.

Theory

Methodology: Google Data Analytics Framework

The project follows the phases of the Google Data Analytics framework. The first phase, Ask, is the Problem Statement above. The other five phases are Prepare, Process, Analyse, Share and Act.

1. Prepare

The training and test CSV files were loaded and combined into one pandas DataFrame for data preparation and analysis.

The test file has no Credit_Score labels. Thus, all its rows were removed when rows without a label were removed (Process, step 2). All models therefore use records from the training file only. Each model has its own split into a training set and a test set (Process, step 10).

2. Process

  1. Check completeness. Find the number of missing values in each column.
  2. Remove missing values. Remove rows that have no Credit_Score. After type conversion, remove all rows that still have a missing value.
  3. Convert data types. Some numeric columns contain text errors. Convert them to numbers with coercion, which changes values that are not valid numbers to missing values. Change Credit_History_Age from text (for example, "22 Years and 1 Months") to whole years. Change Occupation, Payment_of_Min_Amount and Payment_Behaviour to dummy variables, which are 0/1 columns, one for each category.
  4. Remove invalid values and outliers. Remove impossible values, such as a negative age, an age of 100 or more, or a negative number of loans. Then remove rows above an upper limit of median + 5 × IQR for seven features with extreme values. IQR is the interquartile range.
  5. Describe the data. Calculate descriptive statistics. Examine the distribution of each numeric variable (Figures 1 and 2).
  6. Find multicollinearity. Make a correlation matrix (Figure 3). Multicollinearity occurs when two or more features have a strong linear relationship. Annual_Income and Monthly_Inhand_Salary have a correlation of 1.0, so Annual_Income was removed from the binary models.
  7. Remove fields that the prediction does not need. Remove ID, Customer_ID, Month, Name and SSN. Also remove Type_of_Loan, which has too many category combinations, and Credit_Mix, which is very similar to the target.
  8. Make one dataset for each task. The binary dataset has 21,740 records. The three-class dataset has 51,038 records.
  9. Prepare the targets. For logistic regression and the perceptron, Poor = 0 and Good = 1. These models do not use the Standard category. For the decision tree, Poor = 0, Standard = 1 and Good = 2.
  10. Split the data. The binary models use a random 70/30 split into training and test sets (6,522 test records). Each binary model has its own random split, so the test sets are not identical. The decision tree uses a stratified 75/25 split (12,760 test records).

The binary models do not use the Standard category, so they cannot classify a Standard customer. Standard is the largest category: 27,373 of the 51,038 records in the three-class dataset. To separate Poor from Good is also an easier task than to separate three classes. Thus, binary results and three-class results are not directly comparable.

Ten histograms of numeric columns: Age, Annual_Income, Monthly_Inhand_Salary, Num_Bank_Accounts, Num_Credit_Card, Interest_Rate, Num_of_Loan, Delay_from_due_date, Num_of_Delayed_Payment and Changed_Credit_Limit. Age, salary, delay and credit limit change have spread distributions. The other six show almost all values in one bar near zero, because a few extreme values stretch the axis.
Figure 1.

Histograms of ten numeric columns after the removal of impossible values and before the removal of outliers.

Open full size
Ten box plots of the same numeric columns. Most columns have many outliers far above the box. For example, Interest_Rate reaches almost 6,000 and Num_Bank_Accounts reaches about 1,800. Age has one outlier near 100.
Figure 2.

Box plots of the same columns. The extreme values show the need for outlier removal.

Open full size
Correlation matrix of all binary-dataset features, coloured from blue (negative) to red (positive). Annual_Income and Monthly_Inhand_Salary have a correlation of 1.0. Credit_Score has negative correlations with Interest_Rate (−0.62), Outstanding_Debt (−0.53) and Payment_of_Min_Amount_Yes (−0.58), and a positive correlation with Payment_of_Min_Amount_No (0.59).
Figure 3.

Correlation matrix of the binary dataset after outlier removal. Red shows positive correlation and blue shows negative correlation.

Open full size

3. Analyse

The models were evaluated with confusion matrices and classification metrics. A confusion matrix compares the actual class of each test record with the predicted class.

For a binary model, one class is the positive class. The other class is the negative class. In this project, Good is the positive class for the ROC curve. A classification report calculates precision, recall and F1-score for each class in turn, with that class as the positive class.

The four cells of a confusion matrix are:

  • TP (true positive). The record is positive and the model predicts positive.
  • TN (true negative). The record is negative and the model predicts negative.
  • FP (false positive). The record is negative, but the model predicts positive.
  • FN (false negative). The record is positive, but the model predicts negative.

"True" or "False" tells if the prediction is correct. "Positive" or "Negative" is the predicted class.

Table 2. Layout of a binary confusion matrix. Rows show the actual class. Columns show the predicted class.

Predicted positivePredicted negative
Actual positiveTP (correct)FN (missed positive)
Actual negativeFP (false alarm)TN (correct)

The scikit-learn plots in this write-up show class 0 in the first row and column. With Good (1) as the positive class, the bottom-right cell is TP and the top-left cell is TN.

Accuracy is the proportion of all predictions that are correct.

Accuracy=TP+TNTP+TN+FP+FN\text{Accuracy}=\frac{TP+TN}{TP+TN+FP+FN}

Use accuracy when both classes are important and the classes are approximately balanced. When one class is much more common, accuracy can be misleading. A model that always predicts the common class can have a high accuracy.

Precision is the proportion of positive predictions that are correct.

Precision=TPTP+FP\text{Precision}=\frac{TP}{TP+FP}

Use precision when a false positive has a high cost.

Recall is the proportion of actual positive cases that the model finds.

Recall=TPTP+FN\text{Recall}=\frac{TP}{TP+FN}

Use recall when a false negative has a high cost and the model must find as many positive cases as possible.

F1-score is the harmonic mean of precision and recall.

F1=2 Precision×RecallPrecision+RecallF1=2\,\frac{\text{Precision}\times\text{Recall}}{\text{Precision}+\text{Recall}}

Use F1-score when precision and recall are both important and one summary value is useful.

Specificity is the proportion of actual negative cases that the model identifies correctly.

Specificity=TNTN+FP\text{Specificity}=\frac{TN}{TN+FP}

Use specificity when the correct identification of negative cases is important.

These metrics have trade-offs. If the decision threshold changes so that the model predicts the positive class more often, recall usually increases and precision usually decreases. The best metric depends on the cost of each type of error. For a lender, an FP can be a loan to a high-risk customer. An FN can be a refusal to a good customer.

4. Share

The Video Explanation and the Theory, Implementation and Results section below show the findings.

5. Act

The next stage adds a random forest model and an interactive Python application for credit rating classification. These enhancements are not complete. Their sections below are placeholders.

Results

Theory, Implementation and Results

Logistic Regression

Theory

Logistic regression estimates the probability of a binary outcome from input features. The process has four steps:

  1. The model calculates a weighted sum of the input features, z=b+βTxz = b + \boldsymbol{\beta}^{T}\mathbf{x}. Here, bb is the intercept, β\boldsymbol{\beta} is the vector of coefficients and x\mathbf{x} is the vector of input features. The value zz is the log-odds of class 1.
  2. It applies the sigmoid function to zz.
  3. The sigmoid function changes zz to a probability between zero and one.
  4. A decision threshold changes the probability to a predicted class. If the probability is equal to or more than the threshold, the model predicts class 1. The threshold can be adjusted. For example, with a threshold of 0.9, the model classifies a record as Good only if the predicted probability of Good is 0.9 or more. This project used the scikit-learn default threshold of 0.5.
σ(z)=11+e−z\sigma(z)=\frac{1}{1+e^{-z}}
Diagram that compares a straight blue line, the linear model y = b0 + b1 x, with an orange S-shaped curve, the logistic model p = 1 / (1 + e^-(b0 + b1 x)). The straight line goes below 0 and above 1. The S-curve stays between 0 and 1.
Figure 4.

A linear model can predict values below 0 or above 1. The logistic model keeps the output between 0 and 1, so it can be a probability.

Open full size

Training finds the values of bb and β\boldsymbol{\beta} that minimise binary cross-entropy, also called log loss. Here, yiy_i is the actual class (0 or 1) and pip_i is the predicted probability of class 1 for record ii of nn:

L=−1n∑i=1n[yilog⁡(pi)+(1−yi)log⁡(1−pi)]L=-\frac{1}{n}\sum_{i=1}^{n}\left[y_i\log(p_i)+(1-y_i)\log(1-p_i)\right]

Log loss gives a large penalty to a confident prediction that is wrong. It is not the same as the mean squared error, which linear regression usually minimises. There is no closed-form solution, so the training uses an iterative optimisation method. In this case, the scikit-learn liblinear solver was used.

Regularisation adds a penalty to the loss. The penalty makes large coefficients less likely and can reduce overfitting. In scikit-learn, the parameter CC is the inverse of the penalty strength λ\lambda: a smaller CC gives a stronger penalty.

  • L1 (Lasso) regularisation adds a penalty based on the absolute values of the coefficients, λ∑j∣βj∣\lambda\sum_j |\beta_j|. It can make some coefficients exactly zero. Thus, it can reduce model complexity and help select features.
  • L2 (Ridge) regularisation adds a penalty based on the squared coefficients, λ∑jβj2\lambda\sum_j \beta_j^2. It makes coefficients smaller but usually not zero.

Implementation

The first experiments used four simple logistic regression models, LR1 to LR4. Each model has one independent variable. Their test accuracies were between 0.69 (salary) and 0.79 (interest rate).

Four scatter plots, LR1 to LR4. Each plot shows the credit rating, 0 for Poor or 1 for Good, against one feature, with a red fitted logistic curve. LR1, monthly in-hand salary: the probability of Good increases slowly with salary. LR2, delay from due date: the probability decreases to near zero at 40 days. LR3, outstanding debt: the probability decreases to near zero at about 3,000 USD. LR4, interest rate: the probability decreases quickly to near zero at about 20%.
Figure 5.

Four simple logistic regressions, each fitted to one feature. The red curve is the predicted probability of a Good rating.

Open full size

Next, a model with all features was trained. Annual_Income and Monthly_Inhand_Salary are perfectly correlated, and this made the coefficients unstable. Annual_Income was removed. All features were standardised (scaled to a mean of 0 and a standard deviation of 1).

L1 regularisation was then used to find features with small effects. Grid search with cross-validation selected the value of CC:

  • Grid search tests a defined set of hyperparameter values. A hyperparameter is a setting that is chosen before training.
  • Cross-validation divides the training data into kk parts, called folds.
  • The model is trained on k−1k-1 folds and validated on the remaining fold. This repeats until each fold has been the validation fold once.
  • The selected value has the best mean score on the validation folds.

The L1 search tested 100 values of CC from 10−510^{-5} to 100.510^{0.5}, with 3-fold cross-validation and accuracy as the score. The best value was C≈0.245C \approx 0.245, with a mean cross-validation accuracy of 0.848.

The L1 coefficients and the p-values of a statsmodels logistic regression were then used to select features. The occupation features were not statistically significant, so they were removed. The final model uses 15 features: Monthly_Inhand_Salary, Outstanding_Debt, Num_Credit_Card, Interest_Rate, Num_of_Delayed_Payment, Delay_from_due_date, Num_of_Loan, two Payment_of_Min_Amount dummy variables and six Payment_Behaviour dummy variables.

The final model uses L2 regularisation, because all 15 features were kept. A second grid search tested 100 values of CC from 10−510^{-5} to 1010, with 5-fold cross-validation and accuracy as the score. The best value was C≈0.351C \approx 0.351, with a mean cross-validation accuracy of 0.841. The final model uses unscaled features.

Results

Confusion matrix of the final logistic regression model, accuracy 0.84. Actual Poor (0): 3,458 predicted Poor and 636 predicted Good. Actual Good (1): 401 predicted Poor and 2,027 predicted Good.
Figure 6.

Confusion matrix of the final logistic regression model. 0 = Poor, 1 = Good. With Good as the positive class: TN = 3,458, FP = 636, FN = 401 and TP = 2,027. The plot title shows the name of an earlier model (SCLR). The values are from the final model.

Open full size

Table 3. Classification report for the final logistic regression model on 6,522 test records. 0 = Poor, 1 = Good.

ClassPrecisionRecallF1-scoreSupport
0 (Poor)0.900.840.874,094
1 (Good)0.760.830.802,428
AccuracyNot applicableNot applicable0.846,522
Macro average0.830.840.836,522
Weighted average0.850.840.846,522
  • Poor (0): precision 0.90. Of the records predicted as Poor, 90% are Poor.
  • Poor (0): recall 0.84. The model finds 84% of the actual Poor records.
  • Good (1): precision 0.76. Of the records predicted as Good, 76% are Good.
  • Good (1): recall 0.83. The model finds 83% of the actual Good records.
  • F1-scores of 0.87 (Poor) and 0.80 (Good) show the balance between precision and recall for each class.
  • Accuracy is 0.84. The model classifies 84% of the 6,522 test records correctly.
  • Averages. The macro average gives equal weight to each class. The weighted average gives weight by the number of records in each class.

With Good as the positive class, the specificity is the recall for Poor: 3,458 / 4,094 = 0.84.

ROC curve for the final logistic regression model, with Good as the positive class. The curve rises steeply to a true positive rate of about 0.9 at a false positive rate of about 0.2, then flattens near 1.0. The area under the curve is 0.91. A dashed diagonal line shows a random guess with an area of 0.5.
Figure 7.

ROC curve for the final logistic regression model. Good is the positive class.

Open full size

The receiver operating characteristic (ROC) curve shows the true positive rate (recall) against the false positive rate (1 − specificity) at different decision thresholds.

The area under the ROC curve (AUC) is 0.91, with 1 being the best score possible and 0.5 the score of a random guess. This shows strong separation between Good and Poor records in this test set. The AUC is not the proportion of correct predictions.

A lender can use the model to find potential credit candidates (Good) for further assessment. In this case, a missed Good customer is a false negative. A lower decision threshold increases the recall for Good. It also increases the number of false positives, so a further assessment stage is necessary.


Perceptron

Theory

Perceptron diagram. A bias input b and inputs X1 to Xn connect through weights w1 to wn to one unit. The unit calculates z = b + the sum of wi xi, then applies a threshold function f(z). The output y is 1 or 0. The error y − ŷ gives a weight change Δw = α(error)xk, and the weights are updated as wk+1 = wk + Δwk.
Figure 8.

A perceptron. The unit calculates a weighted sum of the inputs, applies a threshold function and uses the error to update the weights.

Open full size

A perceptron is a simple neural model with one computational unit. It multiplies each input feature by a learned weight, adds a bias and applies an activation function:

z=wTx+bz=\mathbf{w}^{T}\mathbf{x}+by^=f(z)={1if z>00otherwise\hat{y}=f(z)=\begin{cases}1 & \text{if } z>0\\ 0 & \text{otherwise}\end{cases}

The activation function changes zz into the output of the unit. A classic perceptron, as in this project, uses a threshold (step) function. Multilayer neural networks often use other activation functions. Examples are ReLU in hidden layers, sigmoid for a binary output and softmax for a multi-class output. The weights show how much each feature contributes to zz, and thus to the decision boundary.

This project uses the scikit-learn Perceptron. It trains with stochastic gradient descent (SGD), one record at a time, on the perceptron loss. With the classes written as yi∈{−1,+1}y_i \in \{-1, +1\}, the loss for a record is:

Li=max⁡(0, −yizi)L_i=\max\left(0,\,-y_i z_i\right)

The loss is zero for a correct prediction. For a wrong prediction, the weights change:

w←w+η yi xi,b←b+η yi\mathbf{w} \leftarrow \mathbf{w} + \eta\, y_i\, \mathbf{x}_i, \qquad b \leftarrow b + \eta\, y_i

The learning rate η\eta (eta0 in scikit-learn) controls the size of each update. Figure 8 shows the same rule for classes 0 and 1: Δw=η(y−y^)x\Delta w = \eta(y-\hat{y})x. The diagram uses the symbol α\alpha for the learning rate. In scikit-learn, alpha is the regularisation strength. Training stops after max_iter passes over the data, or when the loss improves by less than tol.

Implementation

The first perceptron used all 39 features of the binary dataset, with L1 regularisation. L1 regularisation pushes weights to zero, so it can help select features.

Grid search with 2-fold cross-validation and accuracy as the score selected the hyperparameters.

Some weights in this model were zero, for example most of the occupation features. A feature with a zero weight does not contribute directly to the linear decision function. A non-zero weight does not prove that a feature is important in general. The features were not standardised, so the size of a weight also depends on the scale of its feature.

After this step, a subset of 29 features was selected and used to train the perceptron with no regularisation penalty. This final model used manually set hyperparameters, not the grid search values.

Results

Confusion matrix of the final perceptron, accuracy 0.79. Actual Poor (0): 3,352 predicted Poor and 802 predicted Good. Actual Good (1): 554 predicted Poor and 1,814 predicted Good.
Figure 9.

Confusion matrix of the final perceptron. 0 = Poor, 1 = Good.

Open full size

Table 4. Classification report for the final perceptron on 6,522 test records. 0 = Poor, 1 = Good.

ClassPrecisionRecallF1-scoreSupport
0 (Poor)0.860.810.834,154
1 (Good)0.690.770.732,368
AccuracyNot applicableNot applicable0.796,522
Macro average0.780.790.786,522
Weighted average0.800.790.796,522
  • The accuracy is 0.79 on 6,522 test records.
  • Poor (0) has an F1-score of 0.83.
  • Good (1) has an F1-score of 0.73.
  • Good has lower precision (0.69) and lower recall (0.77) than Poor.
  • Thus, the performance is different for the two classes. The perceptron is less accurate than logistic regression for both classes.

Decision Tree

Theory

Decision tree diagram. A root node splits on Yes and No into two internal nodes. One internal node tests Age ≤ 30 and the other tests Income > 50k. Each test leads to two leaf nodes that give Class A or Class B.
Figure 10.

Parts of a decision tree: the root node, internal nodes that test features, and leaf nodes that give a class.

Open full size

A decision tree makes a prediction with a sequence of rules. Each internal node tests a feature. Each branch is one outcome of the test. A leaf node gives the predicted class.

The tree uses Gini impurity to measure how mixed the classes are in a node:

G=1−∑k=1Kpk2G=1-\sum_{k=1}^{K}p_k^2

Here, pkp_k is the proportion of class kk in the node, and KK is the number of classes. A Gini impurity of zero means that all samples in the node are in one class. A higher value shows a greater mixture of classes.

At each node, the algorithm evaluates the possible splits and selects the split that gives the largest decrease in impurity. This method is greedy: it selects each split for its immediate improvement only. Thus, it does not guarantee the best possible tree.

Implementation

The decision tree uses three target classes:

  • Poor = 0
  • Standard = 1
  • Good = 2

After cleaning, the three-class dataset has 51,038 records. The class counts for the full dataset, before the split, are:

  • Class 0 (Poor): 14,933
  • Class 1 (Standard): 27,373
  • Class 2 (Good): 8,732

The split into training and test sets is stratified. Stratified sampling keeps the class proportions the same in the training set and the test set. This makes the test results more reliable. Stratification does not correct class imbalance. Standard is still more than half of each set.

The first tree used the scikit-learn default hyperparameters on all 42 features. It has a depth of 38 levels and 7,354 leaf nodes (Figure 11). A tree of this size is difficult to interpret and can overfit, because it can learn details of the training data that do not apply to new data.

A very large decision tree with thousands of small coloured nodes in dense rows. The individual nodes and their labels are too small to read.
Figure 11.

The default tree: 38 levels and 7,354 leaf nodes.

Open full size

Grid search with 2-fold cross-validation was then used to tune the tree. The search tested these controls:

  • Maximum depth (max_depth): the maximum number of levels.
  • Maximum features (max_features): the number of features considered at each split.
  • Maximum leaf nodes (max_leaf_nodes).
  • Minimum impurity decrease (min_impurity_decrease): the smallest decrease in impurity that a split must give.
  • Minimum samples per leaf (min_samples_leaf) and per split (min_samples_split).
  • Cost-complexity pruning (ccp_alpha): a penalty that removes branches that add little.

The tuned tree used all 42 features, a maximum depth of 10, 15 features at each split, a maximum of 20 leaf nodes, at least 10 samples in each leaf and ccp_alpha = 0.0001. Table 5 shows its results.

Feature importance measures how much each feature decreases impurity across all the splits in the fitted tree. The feature importance values were used to select 11 features. A second grid search tuned a final tree on these 11 features. The final tree has a depth of 8 and 20 leaf nodes (Figure 12).

The final decision tree with 20 leaf nodes. The root node splits on Outstanding_Debt ≤ 1500.005. Lower splits use Payment_of_Min_Amount_Yes, Interest_Rate, Changed_Credit_Limit, Num_Credit_Card, Delay_from_due_date, Num_Bank_Accounts and Num_of_Delayed_Payment. Leaf colours show the predicted class: green for Standard, orange for Poor and purple for Good.
Figure 12.

The final tree with 11 features. Green leaves predict Standard, orange leaves predict Poor and purple leaves predict Good. Open the full-size image to read the split rules.

Open full size

Results

Table 5. Classification report for the tuned decision tree with all 42 features, on 12,760 test records. 0 = Poor, 1 = Standard, 2 = Good.

ClassPrecisionRecallF1-scoreSupport
0 (Poor)0.700.590.643,733
1 (Standard)0.640.850.736,844
2 (Good)0.770.170.282,183
AccuracyNot applicableNot applicable0.6612,760
Macro average0.700.540.5512,760
Weighted average0.680.660.6312,760
  • The accuracy is 0.66 on 12,760 test records.
  • Poor (0) has an F1-score of 0.64.
  • Standard (1) has an F1-score of 0.73 and a recall of 0.85.
  • Good (2) has a precision of 0.77 but a recall of only 0.17.
  • The low recall for Good means that the model misses most actual Good records.
  • The macro F1-score of 0.55 shows that the performance is not equal across the three classes.
  • The weighted F1-score of 0.63 gives weight by the number of test records in each class.

The classes are not balanced. Standard is 54% of the test set and Good is 17%. This imbalance can bias the tree towards Standard. It is possibly not the only cause of the low recall for Good. Other factors, such as the limits on tree size, can also have an effect.


Model comparison

Table 6. Test results for the three models. The binary and three-class tasks are different, so their accuracies are not directly comparable.

ModelTaskTest recordsAccuracyMacro F1-score
Logistic regressionBinary: Poor, Good6,5220.840.83
PerceptronBinary: Poor, Good6,5220.790.78
Decision treeThree-class: Poor, Standard, Good12,7600.660.55

Implementation

Technical Implementation

The project is one Jupyter notebook in Python. It uses these libraries:

Table 7. Python libraries used in the notebook.

LibraryUse in this project
scikit-learnData splits, feature scaling, the three models, grid search with cross-validation and evaluation metrics.
pandasLoad the CSV files, clean the data and make dummy variables.
NumPyNumeric arrays and hyperparameter ranges.
MatplotlibHistograms, box plots, the correlation matrix, model curves and tree plots.
SciPyInterquartile range for the outlier limits.
statsmodelsP-values of the logistic regression coefficients for feature selection.

Context

Lessons Learnt

Bias–variance trade-off

A model that is too simple underfits: it does not learn the pattern in the data. A model that is too complex overfits: it learns details of the training data that do not apply to new data. The default decision tree, with 7,354 leaf nodes, is an example of a complex model. Limits on model complexity and validation on data that the model has not seen help to balance these risks.

Hyperparameter optimisation

Grid search can need much computation, because it trains a model for each combination of values and each fold. For example, the perceptron search tested more than 14,000 combinations. Other methods, such as Bayesian optimisation, use the results of earlier evaluations to select the next values. In some cases, these methods need fewer evaluations to find good values. They do not guarantee a better model.

Feature scaling

Features with different numeric scales can affect some machine learning algorithms. Scaling is important for methods such as logistic regression and perceptrons, when their optimisation or regularisation is sensitive to scale. The final perceptron used unscaled features, so its weights are difficult to compare. Scaling is not necessary for every model. Decision trees usually do not need feature scaling, because each split uses one feature at a time.

Implementation

Enhancement – Random Forest

Diagram of a random forest. One training data instance goes to several decision trees. Each tree predicts a class: Class A, Class A and Class B. Bagging (voting majority) combines the predictions, and the prediction output is Class A.
Figure 13.

A random forest. Each tree makes a prediction, and the majority vote gives the output.

Open full size

What a random forest is

A random forest is a group of many decision trees. Each tree makes a prediction, and the forest uses the class that most trees predict. This model uses 300 trees.

How it works

  1. The model makes a random sample of the training data for each tree. Some rows can occur more than once in a sample. This is called "bootstrap sampling".
  2. At each split, a tree looks at only a random subset of the features.
  3. Each tree grows on its own sample and makes its own prediction.
  4. The forest counts the predictions and gives the majority class.

Why it is better than a single decision tree

A single decision tree learns the training data in close detail. A small change in the data can give a very different tree. The tree has high variance.

In a random forest, each tree sees different data and different features, so the trees make different errors. When the forest combines the trees, many of these errors cancel. This reduces variance, and the bias does not increase much.

The model also uses class_weight='balanced_subsample'. This gives more weight to the smaller classes in each tree's sample, because the classes are not balanced (Standard 53%, Poor 29%, Good 18%).

Data processing and data leakage

The dataset has eight monthly records for each customer. In the earlier work, a random train-test split put records from the same customer into both sets. The model then saw part of the test data during training, which is data leakage, and the test score was too high.

In this version, the data processing is better. I kept Customer_ID and used StratifiedGroupKFold to split the data. All records for one customer are in the train set or the test set, never both. The split also keeps the class proportions the same in the two sets (80% train, 20% test).

Results

Normalised confusion matrix of the random forest. Rows are the true labels and columns are the predicted labels, in the sequence Poor, Standard, Good. True Poor: 0.62 Poor, 0.34 Standard, 0.041 Good. True Standard: 0.12 Poor, 0.79 Standard, 0.088 Good. True Good: 0.013 Poor, 0.53 Standard, 0.46 Good.
Figure 14.

Confusion matrix of the random forest on the test set. Each row shows the proportions of one true class.

Open full size

Table 8. Classification report for the random forest on 20,000 test records.

ClassPrecisionRecallF1-scoreSupport
Good0.580.460.513,498
Poor0.730.620.675,821
Standard0.690.790.7410,681
AccuracyNot applicableNot applicable0.6820,000
Macro average0.660.620.6420,000
Weighted average0.680.680.6820,000

Table 9. The random forest compared with the single decision tree.

ModelAccuracyMacro F1-score
Single decision tree0.700.67
Random forest0.680.64
Random forest (train set)n/a1.00

Interpretation

The random forest did not do better than the single decision tree. The accuracy and macro F1 are almost the same.

The model is best at the Standard class and worst at the Good class. The recall for Good is 0.46, so the model misses more than half of the customers with a good credit score.

The train macro F1 is 1.00 and the test macro F1 is 0.64. This shows that the trees memorised the training data.

I think the main cause is the dataset. The data is synthetic and has many errors, for example negative ages and values that are not numbers. The features do not give a strong signal for the credit score. More trees cannot find a pattern that the data does not contain.

Also, the decision tree score came from a random split, which possibly had data leakage. The random forest score comes from a grouped split with no leakage. Thus the two results are close, but the random forest result is more honest.

Context

Video Explanation

Interactive

Interactive Application

Credit Rating Predictor App

What the app does

The Credit Rating Predictor is a web app that I made with Streamlit. A user enters ten financial details, and the app predicts if the user's credit rating is Good or Poor. The app also shows a confidence value for the prediction.

Model selection

Logistic regression gave the best results of all the classifiers that I tested, so the app uses it. I trained a new logistic regression model for the app.

The original dataset uses many features that a typical person does not know, for example the credit mix or the number of credit inquiries. For the app, I kept only ten features that a user can easily find:

  • Age
  • Monthly in-hand salary
  • Number of bank accounts
  • Number of credit cards
  • Interest rate
  • Number of loans
  • Outstanding debt
  • Credit history age
  • Amount invested monthly
  • Monthly balance

These ten features are the input fields in the app. I removed the Standard class, so the model has only two classes: Good and Poor.

Training

I used the same data processing as in the random forest work. The split uses Customer_ID, so all records for one customer are in the train set or the test set, never both. This prevents data leakage.

The model is a pipeline with a StandardScaler and a LogisticRegression. A grid search with grouped cross-validation found the best settings: L2 penalty, C=0.001C = 0.001, and balanced class weights. I saved the pipeline as model.pkl, and the app loads this file.

Results

Table 10. Classification report for the app model on 9,429 test records.

ClassPrecisionRecallF1-scoreSupport
Poor0.950.790.865,850
Good0.730.930.823,579
AccuracyNot applicableNot applicable0.849,429
Macro average0.840.860.849,429

The ROC AUC is 0.91.

Horizontal bar chart of the logistic regression coefficients. A positive value means a Good rating is more likely. Positive: Credit_History_Age (about 0.23), Age (about 0.11) and Monthly_Inhand_Salary (about 0.11). Near zero: Amount_invested_monthly and Monthly_Balance. Negative: Num_Bank_Accounts (about −0.24), Num_of_Loan (about −0.25), Outstanding_Debt (about −0.49), Num_Credit_Card (about −0.60) and Interest_Rate (about −0.75).
Figure 15.

Coefficients of the app model. A positive coefficient makes a Good rating more likely. The features are standardised, so the sizes can be compared.

Open full size

Decision threshold

The model gives the probability that the credit rating is Good. If this probability is 50% or more, the app shows Good. If it is less than 50%, the app shows Poor.

You can move this threshold. A higher threshold makes the model more careful before it predicts Good. I kept the threshold at 50% because it gives a high recall for the Good class (0.93). The model finds almost all users who have a good credit rating.

Confidence

The confidence value is the probability that the model gives for the predicted class:

  • If the prediction is Good, the confidence is the predicted probability.
  • If the prediction is Poor, the confidence is 1 minus the predicted probability.

The confidence is an estimate, not a guarantee. If the input values are far outside the values in the training data, the estimate is less reliable.

Open the Application

Implementation

Source Code

Context

All Projects