Commercial banks receive a lot of applications for credit cards. Many of them get rejected for many reasons, like high loan balances, low income levels, or too many inquiries on an individual's credit report, for example. Manually analyzing these applications is mundane, error-prone, and time-consuming (and time is money!). Luckily, this task can be automated with the power of machine learning and pretty much every commercial bank does so nowadays. In this workbook, you will build an automatic credit card approval predictor using machine learning techniques, just like real banks do.
The Data
The data is a small subset of the Credit Card Approval dataset from the UCI Machine Learning Repository showing the credit card applications a bank receives. This dataset has been loaded as a pandas DataFrame called cc_apps. The last column in the dataset is the target value.
# Import necessary libraries
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.preprocessing import StandardScaler, LabelEncoder
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score
# Load the dataset
cc_apps = pd.read_csv("cc_approvals.data", header=None)
cc_apps.head()# Replace '?' with NaN and drop rows with missing target
cc_apps.replace('?', np.nan, inplace=True)
cc_apps.dropna(subset=[cc_apps.columns[-1]], inplace=True)
# Fill missing values with the most frequent value for each column
for col in cc_apps.columns:
if cc_apps[col].dtype == object:
cc_apps[col].fillna(cc_apps[col].mode()[0], inplace=True)
else:
cc_apps[col].fillna(cc_apps[col].mean(), inplace=True)
# Convert categorical columns to numeric
le = LabelEncoder()
for col in cc_apps.columns:
if cc_apps[col].dtype == object:
cc_apps[col] = le.fit_transform(cc_apps[col])
# Split features and target
X = cc_apps.iloc[:, :-1]
y = cc_apps.iloc[:, -1]
# Split into training and test sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# Scale features
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)
# Define models and parameters for grid search
models = {
"LogisticRegression": {
"model": LogisticRegression(max_iter=1000),
"params": {
"C": [0.1, 1, 10]
}
},
"RandomForest": {
"model": RandomForestClassifier(),
"params": {
"n_estimators": [50, 100],
"max_depth": [5, 10]
}
},
"SVM": {
"model": SVC(),
"params": {
"C": [0.1, 1],
"kernel": ['linear', 'rbf']
}
}
}
# Perform grid search and find the best model
best_score = 0
best_model = None
for name, mp in models.items():
grid = GridSearchCV(mp["model"], mp["params"], cv=5, scoring='accuracy')
grid.fit(X_train, y_train)
score = grid.score(X_test, y_test)
print(f"{name} Accuracy: {score:.4f}")
if score > best_score:
best_score = score
best_model = grid.best_estimator_
print(f"\nBest Model: {best_model}")
print(f"Best Accuracy Score: {best_score:.4f}")