Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

# Import necessary libraries from sklearn.model _ selection import train _ test _ split from sklearn.tree import DecisionTreeClassifier, plot _ tree from sklearn.metrics import classification

# Import necessary libraries
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier, plot_tree
from sklearn.metrics import classification_report
import pandas as pd
import matplotlib.pyplot as plt
# Sample data - replace this with your actual data
data ={
'Age': [24,38,34,44,23,56,45,60,71,18],
'Gender': ['Woman', 'Man', 'Man', 'Woman', 'Woman', 'Woman', 'Man', 'Woman', 'Man', 'Man'],
'Health Status': ['Good', 'Sick', 'Good', 'Sick', 'Sick', 'Good', 'Good', 'Sick', 'Good', 'Good'],
'Employment Status': ['Manager', 'Worker', 'Unemployed', 'Worker', 'Manager', 'Unemployed', 'Worker', 'Official', 'Official', 'Manager'],
'Salary': [1000,500,0,150,100,900,0,850,700,420],
'Loan Granted': ['Yes', 'Yes', 'No', 'Yes', 'No', 'Yes', 'No', 'Yes', 'No', 'Yes']
}
# Convert the data to a DataFrame
df = pd.DataFrame(data)
# Convert categorical variables to numerical using one-hot encoding
df_encoded = pd.get_dummies(df, columns=['Gender', 'Health Status', 'Employment Status'])
# Separate the features (X) and the target variable (y)
X = df_encoded.drop('Loan Granted', axis=1)
y = df_encoded['Loan Granted']
# Split the dataset into training (80%) and testing (20%) sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# Initialize the Decision Tree Classifier
clf = DecisionTreeClassifier()
# Train the model on the training set
clf.fit(X_train, y_train)
# Predict the target variable for the test set
y_pred = clf.predict(X_test)
# Evaluate the model's performance
report = classification_report(y_test, y_pred)
print("Classification Report:
", report)
# Visualize the decision tree
plt.figure(figsize=(12,8))
plot_tree(clf, filled=True, feature_names=X.columns, class_names=['No', 'Yes'])
plt.title("Decision Tree Visualization")
plt.show()

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Students also viewed these Databases questions