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
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import confusion_matrix
from sklearn.model_selection import GridSearchCV
# Load the dataset
cc_apps = pd.read_csv("cc_approvals.data", header=None)
cc_apps.head()
# Replace any missing value with np.Nan
cc_apps_missing= cc_apps.replace("?", np.NaN)
cc_apps_missing
cc_apps_copy = cc_apps_missing.copy()
# Loop over the columns of the DataFrame
for col in cc_apps_copy.columns:
if cc_apps_copy[col].dtypes == "object":
cc_apps_copy[col]= cc_apps_copy[col].fillna(cc_apps_copy[col].value_counts().index[0])
else:
cc_apps_copy[col] = cc_apps_copy[col].fillna(cc_apps_copy[col].mean())
# Performing One-hot encoding
cc_apps_missing = pd.get_dummies(cc_apps, drop_first=True)
cc_apps_missing.head()
# Input the target variables
X = cc_apps_missing.iloc[:, :-1].values
y = cc_apps_missing.iloc[:, -1].values
# Train and split to 80% train and 20% test
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# Scale your data
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)
# Train the model
logreg = LogisticRegression()
logreg.fit(X_train_scaled, y_train)
y_pred = logreg.predict(X_test_scaled)
confusion_matrix(y_test, y_pred)
# Defining grid search parameters
params = {'C': [0.1, 1, 10, 100],
'penalty': ['l1', 'l2'],
'solver': ['liblinear', 'saga']
}
# Perform a GridSearch
searcher = GridSearchCV(logreg, param_grid=params, cv=5)
searcher_fit = searcher.fit(X_train_scaled, y_train)
# Finding the best score
searcher_estimator = searcher_fit.best_estimator_
searcher_estimator.fit(X_test_scaled, y_test)
best_score = searcher_estimator.score(X_test_scaled, y_test)
best_score