# Step 0: Load Required Packages
library(rpart)      # For decision trees
library(rpart.plot) # For plotting decision trees
library(class)      # For KNN predictions

# Step 1: Create Loan Default Dataset
loan_data_text <- "Income,CreditScore,LoanAmount,YearsEmployed,Age,Married,Default
28000,580,12000,1,23,No,Yes
75000,760,20000,8,42,Yes,No
45000,640,15000,3,28,No,No
60000,710,18000,5,34,Yes,Yes
32000,600,10000,2,26,No,Yes
82000,780,22000,10,46,Yes,No
50000,670,14000,4,30,No,Yes
69000,720,19000,7,37,Yes,No
37000,620,11000,2,25,No,No
78000,755,21000,9,44,Yes,Yes
42000,635,11500,3,27,No,Yes
66000,730,18000,6,36,Yes,No
48000,650,13000,4,31,No,No
71000,740,20000,8,39,Yes,Yes
35000,610,9500,2,24,No,No
68000,715,18500,7,37,Yes,No
39000,635,12000,3,28,No,Yes
74000,755,20500,8,41,Yes,No
30000,590,9000,1,22,No,Yes
72000,730,19000,7,38,Yes,No"

loan_data <- read.csv(text = loan_data_text, stringsAsFactors = FALSE)
loan_data$Married <- factor(loan_data$Married)
loan_data$Default <- factor(loan_data$Default, levels = c("No","Yes"))

# Step 2: Explore Loan Data
print("First few borrowers:")
head(loan_data)

print("Summary of loan data:")
summary(loan_data)

print("How many borrowers defaulted?")
table(loan_data$Default)

print("Average income by default:")
aggregate(Income ~ Default, data = loan_data, mean)

print("Average credit score by default:")
aggregate(CreditScore ~ Default, data = loan_data, mean)

# Step 3: Split Data and Build Logistic Regression
set.seed(123)
train_indices <- sample(seq_len(nrow(loan_data)), size = 0.7 * nrow(loan_data))
train_data <- loan_data[train_indices, ]
test_data <- loan_data[-train_indices, ]

logistic_model <- glm(Default ~ Income + CreditScore + LoanAmount,
                      data = train_data, family = binomial)

logistic_probabilities <- predict(logistic_model, newdata = test_data, type = "response")
logistic_predictions <- factor(ifelse(logistic_probabilities > 0.5, "Yes", "No"), 
                               levels = c("No","Yes"))

confusion_matrix <- table(Predicted = logistic_predictions, Actual = test_data$Default)
print("Logistic Regression Results:")
print(confusion_matrix)

accuracy <- mean(logistic_predictions == test_data$Default)
print(paste("Accuracy:", round(accuracy * 100, 1), "%"))

# Step 4: Decision Tree
tree_model <- rpart(Default ~ Income + CreditScore + LoanAmount,
                    data = train_data, method = "class")

rpart.plot(tree_model, main = "Decision Tree for Loan Default")

tree_predictions <- predict(tree_model, test_data, type = "class")
confusion_matrix_tree <- table(Predicted = tree_predictions, Actual = test_data$Default)
print("Decision Tree Results:")
print(confusion_matrix_tree)

tree_accuracy <- mean(tree_predictions == test_data$Default)
print(paste("Accuracy:", round(tree_accuracy * 100, 1), "%"))

# Step 5: KNN
train_X <- scale(train_data[, c("Income","CreditScore","LoanAmount")])
test_X <- scale(test_data[, c("Income","CreditScore","LoanAmount")],
                center = attr(train_X, "scaled:center"),
                scale = attr(train_X, "scaled:scale"))
train_Y <- train_data$Default

knn_predictions <- knn(train_X, test_X, cl = train_Y, k = 3)
confusion_matrix_knn <- table(Predicted = knn_predictions, Actual = test_data$Default)
print("KNN Results:")
print(confusion_matrix_knn)

knn_accuracy <- mean(knn_predictions == test_data$Default)
print(paste("Accuracy:", round(knn_accuracy * 100, 1), "%"))
