Step 1: Import Required Libraries
import numpy as np # Used for numerical operations import pandas as pd # Used for handling tabular data from pathlib import Path # Used for handling file paths from sklearn.metrics import confusion_matrix, classification_report # Evaluation metrics from sklearn.model_selection import train_test_split # Splitting dataset from sklearn.linear_model import LogisticRegression # Logistic regression model numpy helps with numerical computations. pandas allows us to manipulate tabular data (CSV files). Path makes it easier to work with file paths. train_test_split is used to split the dataset into training and testing sets. LogisticRegression is the classification model we use. Step 2: Load and Inspect Data
df = pd.read_csv("Resources/lending_data.csv")
df.head() Reads the CSV file containing lending data. Displays the first few rows for review. Step 3: Define Features (X) and Labels (y)
y = df["loan_status"]
X = df.drop(columns=["loan_status"])
print(y.value_counts()) # Check how many healthy/high-risk loans
print(X.head()) # Display first 5 rows of features y (target variable) contains loan status: 0 = Healthy Loan 1 = High-Risk Loan X (features) contains borrower attributes (income, credit score, etc.). value_counts() helps check the distribution of 0s and 1s. Step 4: Split Data into Training and Testing Sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=1)
print("Training set shape:", X_train.shape, y_train.shape) print("Testing set shape:", X_test.shape, y_test.shape) train_test_split divides data: 80% training (X_train, y_train) 20% testing (X_test, y_test) random_state=1 ensures consistent results. Step 5: Train the Logistic Regression Model
model = LogisticRegression(random_state=1)
model.fit(X_train, y_train) Creates a logistic regression model. Fits (trains) it using the training data.
Step 6: Make Predictions
y_pred = model.predict(X_test)
print("Predicted labels:", y_pred[:10]) Uses the trained model to predict loan status on test data. Step 7: Evaluate the Model Confusion Matrix
cm = confusion_matrix(y_test, y_pred) print("Confusion Matrix:\n", cm) Shows how many predictions were correct and incorrect. Classification Report
report = classification_report(y_test, y_pred) print("Classification Report:\n", report) Gives accuracy, precision, and recall for both classes (0 and 1).