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_Scorelabel. - Test file. 50,000 records and 27 attributes. This file has no
Credit_Scorelabel. This project did not use the test file.
Table 1. Dataset attributes. Column names are as in the source files.
| Attribute | Description |
|---|---|
ID | Unique identifier for a data entry. |
Customer_ID | Unique identifier for a customer. |
Month | Month associated with the record. |
Name | Customer's name. |
Age | Customer's age. |
SSN | Customer's Social Security Number. |
Occupation | Customer's occupation. |
Annual_Income | Customer's annual income. |
Monthly_Inhand_Salary | Customer's monthly base salary. |
Num_Bank_Accounts | Number of bank accounts held by the customer. |
Num_Credit_Card | Number of credit cards held by the customer. |
Interest_Rate | Interest rate on credit cards. |
Num_of_Loan | Number of loans taken from a bank. |
Type_of_Loan | Types of loans taken by the customer. |
Delay_from_due_date | Average number of days a payment is late. |
Num_of_Delayed_Payment | Average number of delayed payments. |
Changed_Credit_Limit | Percentage change in the credit card limit. |
Num_Credit_Inquiries | Number of credit inquiries about the customer. |
Credit_Mix | Classification of the customer's credit mix. |
Outstanding_Debt | Remaining debt, measured in USD. |
Credit_Utilization_Ratio | Proportion of available credit currently used. |
Credit_History_Age | Length of the customer's credit history. |
Payment_of_Min_Amount | Indicates whether the customer paid only the minimum amount due. |
Total_EMI_per_month | Total monthly Equated Monthly Instalment (EMI) payments, measured in USD. |
Amount_invested_monthly | Amount invested by the customer each month, measured in USD. |
Payment_Behaviour | Customer spending and payment patterns. |
Monthly_Balance | Customer's monthly balance, measured in USD. |
Credit_Score | Credit 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
- Check completeness. Find the number of missing values in each column.
- Remove missing values. Remove rows that have no
Credit_Score. After type conversion, remove all rows that still have a missing value. - 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_Agefrom text (for example, "22 Years and 1 Months") to whole years. ChangeOccupation,Payment_of_Min_AmountandPayment_Behaviourto dummy variables, which are 0/1 columns, one for each category. - 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.
- Describe the data. Calculate descriptive statistics. Examine the distribution of each numeric variable (Figures 1 and 2).
- Find multicollinearity. Make a correlation matrix (Figure 3). Multicollinearity occurs when two or more features have a strong linear relationship.
Annual_IncomeandMonthly_Inhand_Salaryhave a correlation of 1.0, soAnnual_Incomewas removed from the binary models. - Remove fields that the prediction does not need. Remove
ID,Customer_ID,Month,NameandSSN. Also removeType_of_Loan, which has too many category combinations, andCredit_Mix, which is very similar to the target. - Make one dataset for each task. The binary dataset has 21,740 records. The three-class dataset has 51,038 records.
- 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.
- 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.

Histograms of ten numeric columns after the removal of impossible values and before the removal of outliers.
Open full size
Box plots of the same columns. The extreme values show the need for outlier removal.
Open full size
Correlation matrix of the binary dataset after outlier removal. Red shows positive correlation and blue shows negative correlation.
Open full size3. 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 positive | Predicted negative | |
|---|---|---|
| Actual positive | TP (correct) | FN (missed positive) |
| Actual negative | FP (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.
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.
Use precision when a false positive has a high cost.
Recall is the proportion of actual positive cases that the model finds.
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.
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.
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:
- The model calculates a weighted sum of the input features, . Here, is the intercept, is the vector of coefficients and is the vector of input features. The value is the log-odds of class 1.
- It applies the sigmoid function to .
- The sigmoid function changes to a probability between zero and one.
- 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.

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 sizeTraining finds the values of and that minimise binary cross-entropy, also called log loss. Here, is the actual class (0 or 1) and is the predicted probability of class 1 for record of :
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 is the inverse of the penalty strength : a smaller gives a stronger penalty.
- L1 (Lasso) regularisation adds a penalty based on the absolute values of the coefficients, . 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, . 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 simple logistic regressions, each fitted to one feature. The red curve is the predicted probability of a Good rating.
Open full sizeNext, 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 :
- 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 parts, called folds.
- The model is trained on 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 from to , with 3-fold cross-validation and accuracy as the score. The best value was , 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 from to , with 5-fold cross-validation and accuracy as the score. The best value was , with a mean cross-validation accuracy of 0.841. The final model uses unscaled features.
Results

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 sizeTable 3. Classification report for the final logistic regression model on 6,522 test records. 0 = Poor, 1 = Good.
| Class | Precision | Recall | F1-score | Support |
|---|---|---|---|---|
| 0 (Poor) | 0.90 | 0.84 | 0.87 | 4,094 |
| 1 (Good) | 0.76 | 0.83 | 0.80 | 2,428 |
| Accuracy | Not applicable | Not applicable | 0.84 | 6,522 |
| Macro average | 0.83 | 0.84 | 0.83 | 6,522 |
| Weighted average | 0.85 | 0.84 | 0.84 | 6,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. Good is the positive class.
Open full sizeThe 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

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 sizeA 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:
The activation function changes 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 , 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 , the loss for a record is:
The loss is zero for a correct prediction. For a wrong prediction, the weights change:
The learning rate (eta0 in scikit-learn) controls the size of each update. Figure 8 shows the same rule for classes 0 and 1: . The diagram uses the symbol 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. 0 = Poor, 1 = Good.
Open full sizeTable 4. Classification report for the final perceptron on 6,522 test records. 0 = Poor, 1 = Good.
| Class | Precision | Recall | F1-score | Support |
|---|---|---|---|---|
| 0 (Poor) | 0.86 | 0.81 | 0.83 | 4,154 |
| 1 (Good) | 0.69 | 0.77 | 0.73 | 2,368 |
| Accuracy | Not applicable | Not applicable | 0.79 | 6,522 |
| Macro average | 0.78 | 0.79 | 0.78 | 6,522 |
| Weighted average | 0.80 | 0.79 | 0.79 | 6,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

Parts of a decision tree: the root node, internal nodes that test features, and leaf nodes that give a class.
Open full sizeA 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:
Here, is the proportion of class in the node, and 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.

The default tree: 38 levels and 7,354 leaf nodes.
Open full sizeGrid 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 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 sizeResults
Table 5. Classification report for the tuned decision tree with all 42 features, on 12,760 test records. 0 = Poor, 1 = Standard, 2 = Good.
| Class | Precision | Recall | F1-score | Support |
|---|---|---|---|---|
| 0 (Poor) | 0.70 | 0.59 | 0.64 | 3,733 |
| 1 (Standard) | 0.64 | 0.85 | 0.73 | 6,844 |
| 2 (Good) | 0.77 | 0.17 | 0.28 | 2,183 |
| Accuracy | Not applicable | Not applicable | 0.66 | 12,760 |
| Macro average | 0.70 | 0.54 | 0.55 | 12,760 |
| Weighted average | 0.68 | 0.66 | 0.63 | 12,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.
| Model | Task | Test records | Accuracy | Macro F1-score |
|---|---|---|---|---|
| Logistic regression | Binary: Poor, Good | 6,522 | 0.84 | 0.83 |
| Perceptron | Binary: Poor, Good | 6,522 | 0.79 | 0.78 |
| Decision tree | Three-class: Poor, Standard, Good | 12,760 | 0.66 | 0.55 |
Implementation
Technical Implementation
The project is one Jupyter notebook in Python. It uses these libraries:
Table 7. Python libraries used in the notebook.
| Library | Use in this project |
|---|---|
| scikit-learn | Data splits, feature scaling, the three models, grid search with cross-validation and evaluation metrics. |
| pandas | Load the CSV files, clean the data and make dummy variables. |
| NumPy | Numeric arrays and hyperparameter ranges. |
| Matplotlib | Histograms, box plots, the correlation matrix, model curves and tree plots. |
| SciPy | Interquartile range for the outlier limits. |
| statsmodels | P-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

A random forest. Each tree makes a prediction, and the majority vote gives the output.
Open full sizeWhat 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
- 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".
- At each split, a tree looks at only a random subset of the features.
- Each tree grows on its own sample and makes its own prediction.
- 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

Confusion matrix of the random forest on the test set. Each row shows the proportions of one true class.
Open full sizeTable 8. Classification report for the random forest on 20,000 test records.
| Class | Precision | Recall | F1-score | Support |
|---|---|---|---|---|
| Good | 0.58 | 0.46 | 0.51 | 3,498 |
| Poor | 0.73 | 0.62 | 0.67 | 5,821 |
| Standard | 0.69 | 0.79 | 0.74 | 10,681 |
| Accuracy | Not applicable | Not applicable | 0.68 | 20,000 |
| Macro average | 0.66 | 0.62 | 0.64 | 20,000 |
| Weighted average | 0.68 | 0.68 | 0.68 | 20,000 |
Table 9. The random forest compared with the single decision tree.
| Model | Accuracy | Macro F1-score |
|---|---|---|
| Single decision tree | 0.70 | 0.67 |
| Random forest | 0.68 | 0.64 |
| Random forest (train set) | n/a | 1.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, , 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.
| Class | Precision | Recall | F1-score | Support |
|---|---|---|---|---|
| Poor | 0.95 | 0.79 | 0.86 | 5,850 |
| Good | 0.73 | 0.93 | 0.82 | 3,579 |
| Accuracy | Not applicable | Not applicable | 0.84 | 9,429 |
| Macro average | 0.84 | 0.86 | 0.84 | 9,429 |
The ROC AUC is 0.91.

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 sizeDecision 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.
Implementation
Source Code
Context