For this project we will be exploring publicly available data from LendingClub.com. Lending Club connects people who need money (borrowers) with people who have money (investors). Hopefully, as an investor you would want to invest in people who showed a profile of having a high probability of paying you back. We will try to create a model that will help predict this.
Lending club had a very interesting year in 2016, so let's check out some of their data and keep the context in mind. This data is from before they even went public.
We will use lending data from 2007-2010 and be trying to classify and predict whether or not the borrower paid back their loan in full. You can download the data from here or just use the csv already provided. It's recommended you use the csv provided as it has been cleaned of NA values.
Here are what the columns represent:
Import the usual libraries for pandas and plotting. You can import sklearn later on.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
sns.set_style("darkgrid")
import warnings
warnings.filterwarnings('ignore')
Use pandas to read loan_data.csv as a dataframe called loans.
loans = pd.read_csv('loan_data.csv')
Check out the info(), head(), and describe() methods on loans.
loans.info()
loans.describe()
loans.head()
Let's do some data visualization! We'll use seaborn and pandas built-in plotting capabilities, but feel free to use whatever library you want. Don't worry about the colors matching, just worry about getting the main idea of the plot.
Create a histogram of two FICO distributions on top of each other, one for each credit.policy outcome.
Note: This is pretty tricky, feel free to reference the solutions. You'll probably need one line of code for each histogram, I also recommend just using pandas built in .hist()
plt.subplots(figsize = (10,6))
sns.distplot(loans[loans['credit.policy'] == 0]['fico'], bins = 35, kde = False, color = 'red', label = 'Credit Policy = 0')
sns.distplot(loans[loans['credit.policy'] == 1]['fico'], bins = 35, kde = False, color = 'blue', label = 'Credit Policy = 1')
plt.xlim(600,850)
plt.ylim(0,900)
plt.legend(loc = 1)
plt.xlabel('FICO')
Create a similar figure, except this time select by the not.fully.paid column.
plt.subplots(figsize = (10,6))
sns.distplot(loans[loans['not.fully.paid'] == 0]['fico'], bins = 35, kde = False, color = 'red', label = 'Not Fully Paid = 0')
sns.distplot(loans[loans['not.fully.paid'] == 1]['fico'], bins = 35, kde = False, color = 'blue', label = 'Not Fully Paid = 1')
plt.xlim(600,850)
plt.ylim(0,900)
plt.legend(loc = 1)
plt.xlabel('FICO')
Create a countplot using seaborn showing the counts of loans by purpose, with the color hue defined by not.fully.paid.
plt.subplots(figsize = (12,6))
sns.countplot(x = 'purpose', hue = 'not.fully.paid', data = loans)
Let's see the trend between FICO score and interest rate. Recreate the following jointplot.
sns.jointplot(x = 'fico', y = 'int.rate', data = loans)
Create the following lmplots to see if the trend differed between not.fully.paid and credit.policy. Check the documentation for lmplot() if you can't figure out how to separate it into columns.
sns.lmplot(x = 'fico', y = 'int.rate', col = 'not.fully.paid', hue = 'credit.policy', data = loans)
Let's get ready to set up our data for our Random Forest Classification Model!
Check loans.info() again.
loans.info()
Notice that the purpose column as categorical
That means we need to transform them using dummy variables so sklearn will be able to understand them. Let's do this in one clean step using pd.get_dummies.
Let's show you a way of dealing with these columns that can be expanded to multiple categorical features if necessary.
Create a list of 1 element containing the string 'purpose'. Call this list cat_feats.
cat_feats = ['purpose']
Now use pd.get_dummies(loans,columns=cat_feats,drop_first=True) to create a fixed larger dataframe that has new feature columns with dummy variables. Set this dataframe as final_data.
final_data = pd.get_dummies(loans, columns = cat_feats, drop_first = True)
final_data.head()
Now its time to split our data into a training set and a testing set!
Use sklearn to split your data into a training set and a testing set as we've done in the past.
from sklearn.model_selection import train_test_split
X = final_data.drop('not.fully.paid', axis = 1)
y = final_data['not.fully.paid']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.3 , random_state= 101)
Let's start by training a single decision tree first!
Import DecisionTreeClassifier
from sklearn.tree import DecisionTreeClassifier
Create an instance of DecisionTreeClassifier() called dtree and fit it to the training data.
dtree = DecisionTreeClassifier()
dtree.fit(X_train, y_train)
Create predictions from the test set and create a classification report and a confusion matrix.
y_predict = dtree.predict(X_test)
from sklearn.metrics import confusion_matrix, classification_report
print(classification_report(y_test, y_predict))
print(confusion_matrix(y_test, y_predict))
Now its time to train our model!
Create an instance of the RandomForestClassifier class and fit it to our training data from the previous step.
from sklearn.ensemble import RandomForestClassifier
rforest = RandomForestClassifier(n_estimators = 300)
rforest.fit(X_train, y_train)
Let's predict off the y_test values and evaluate our model.
Predict the class of not.fully.paid for the X_test data.
y_predict = rforest.predict(X_test)
Now create a classification report from the results. Do you get anything strange or some sort of warning?
print(classification_report(y_test,y_predict))
Show the Confusion Matrix for the predictions.
print(confusion_matrix(y_test,y_predict))
What performed better the random forest or the decision tree?
Overall the Random Forest performed better than the single decision tree. However, in certain cases such as recall and f1-score for class = 1 the single decision tree performed better than the Random Forest. Therefore, the actual choice will depend on what metric the analyzer cares about the most.