Module 13 · Decision trees and random forests · Lesson 52 of 66
Project: will the loan be repaid?
Predict which LendingClub borrowers won't pay back in full.
In this lesson · about 30 minutes
- Explore lending data with Seaborn
- Encode a category column
- Compare a decision tree with a random forest
LendingClub connects borrowers with investors. As an investor you'd want to back people likely to repay. We'll use public loan data from 2007 to 2010 and try to predict not.fully.paid (1 if the borrower didn't repay in full). Some columns:
credit.policy: 1 if the borrower meets LendingClub's credit rulespurpose: what the loan is for, such asdebt_consolidationorcredit_cardint.rate: the interest rate (0.11 means 11%), higher for riskier borrowersinstallment: the monthly paymentfico: the borrower's credit scoreinq.last.6mths,delinq.2yrs,pub.rec: recent credit checks, late payments and public records
Exercise
1. Credit scores by policy
On one chart, draw two histograms of fico with 30 bins and alpha=0.5: one for rows where credit.policy is 1 (blue, labeled 'Credit.Policy=1'), one where it's 0 (red, labeled 'Credit.Policy=0'). Add a legend and label the x axis 'FICO'.
Code that runs before yours
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
loans = pd.read_csv('loan_data.csv')Exercise
2. Loans by purpose
Draw a count plot of purpose, split by not.fully.paid with hue and the 'Set1' palette.
Code that runs before yours
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
loans = pd.read_csv('loan_data.csv')3. Credit score and interest rate
Exercise
4. Encode the purpose
purpose is text. Make final_data with pd.get_dummies(loans, columns=['purpose'], drop_first=True, dtype=int), then split it: X is every column except not.fully.paid, y is that column, with test_size=0.30 and random_state=101.
Code that runs before yours
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
loans = pd.read_csv('loan_data.csv')Exercise
5. A single tree
Train a DecisionTreeClassifier(random_state=101) called dtree, save its predictions as predictions, and print a classification report.
Code that runs before yours
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
loans = pd.read_csv('loan_data.csv')
from sklearn.model_selection import train_test_split
final_data = pd.get_dummies(loans, columns=['purpose'], drop_first=True, dtype=int)
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.30, random_state=101)Exercise
6. A random forest
Train a RandomForestClassifier(n_estimators=100, random_state=101) called rfc, save its predictions as rfc_pred, and print a classification report. (The course notebook uses 600 trees; 100 keeps it quick in the browser.)
Code that runs before yours
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
loans = pd.read_csv('loan_data.csv')
from sklearn.model_selection import train_test_split
final_data = pd.get_dummies(loans, columns=['purpose'], drop_first=True, dtype=int)
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.30, random_state=101)Which did better?
The forest has higher overall accuracy, but look at the recall for class 1: it finds very few of the loans that went bad, while the single tree finds more. Which is better depends on what you care about. An investor who wants to avoid bad loans needs recall on class 1, and neither model is good enough yet. The next steps would be more feature engineering, or telling the model that class 1 matters more (class_weight='balanced').
Exercises solved: 0 of 5
Noviq Academy's Data Science course is free and for learning. Python runs in your browser with Pyodide, which downloads about 20 MB the first time, plus a few more for scikit-learn. Your code and progress stay on this device. The salaries data is a sample of San Francisco's public pay records; the purchases, customers, housing, advertising and classified data are made up. The Titanic, tips, flights and iris data sets come from Seaborn's examples; the maps use public 2011 to 2014 US and world figures. The 911 data is a 20,000-call sample of Montgomery County, Pennsylvania's public 911 records; the movie ratings are the MovieLens 100K data from GroupLens Research; the reviews are a 3,000-review sample from the Yelp Dataset Challenge; the loans are public LendingClub data; the colleges are the College data from An Introduction to Statistical Learning; the bank notes, kyphosis and breast cancer data come from the UCI Machine Learning Repository. Spark and TensorFlow can't run in a browser, so those lessons use stand-ins that run here, and show the code for the real tools.