Question
Predict if a student will Pass or Fail based on study hours and sleep hours using Decision Tree algorithm.
Solution
β Verified
# Import libraries
from sklearn.tree import DecisionTreeClassifier, export_text
# Sample data
# Features: [study_hours, sleep_hours]
X = [
[5, 7], # studied 5 hrs, slept 7 hrs
[3, 6],
[8, 5],
[1, 4],
[4, 8]
]
# Labels: Pass = 1, Fail = 0
y = [1, 0, 1, 0, 1]
# Create model
model = DecisionTreeClassifier()
model.fit(X, y)
# Show the tree in text form
tree_rules = export_text(model, feature_names=["study_hours", "sleep_hours"])
print(tree_rules)
# Predict for a new student
new_student = [[2, 7]] # studies 2 hrs, sleeps 7 hrs
prediction = model.predict(new_student)
print("Prediction:", "Pass" if prediction[0] == 1 else "Fail")
Output:--
|--- study_hours <= 3.50
| |--- class: 0
|--- study_hours > 3.50
| |--- class: 1
Prediction: Fail β
Click here to download practice questions on
Decision Tree