Menu

Predictive Analytics - (LAB PROGRAMS)


Aim:

  CART - Classification And Regression Trees

Solution :


Library Installation:

To install required library files, Open Command Prompt or Terminal and execute the following commands


$ pip install scikit-learn

$ pip install pandas


Dataset (sample_dataset.csv) :


X1,X2,X3,Y
5.1,3.5,1.4,0
4.9,3.0,1.4,0
4.7,3.2,1.3,0
4.6,3.1,1.5,0
5.0,3.6,1.4,0
5.4,3.9,1.7,0
4.6,3.4,1.4,0
5.0,3.4,1.5,0
5.4,3.7,1.5,0
4.8,3.4,1.6,0
7.0,3.2,4.7,1
6.4,3.2,4.5,1
6.9,3.1,4.9,1
5.5,2.3,4.0,1
6.5,2.8,4.6,1
5.7,2.8,4.5,1
6.3,3.3,4.7,1
4.9,2.4,3.3,1
6.6,2.9,4.6,1
5.2,2.7,3.9,1
6.3,3.3,6.0,2
5.8,2.7,5.1,2
7.1,3.0,5.9,2
6.3,2.9,5.6,2
6.5,3.0,5.8,2
7.6,3.0,6.6,2
4.9,2.5,4.5,2
7.3,2.9,6.3,2
6.7,2.5,5.8,2
7.2,3.6,6.1,2

PROGRAM: (CART.py)

 
 # Import libraries
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score, confusion_matrix, classification_report
# Example dataset
df = pd.read_csv('sample_dataset.csv')
X = df[['X1', 'X2', 'X3']]
Y = df['Y']
# Split dataset
X_train, X_test, Y_train, Y_test = train_test_split(
    X, Y, test_size=0.2, random_state=42
)
# Initialize CART model
cart_model = DecisionTreeClassifier(
    criterion='gini',
    max_depth=3,
    min_samples_split=10,
    random_state=42
)
# Train model
cart_model.fit(X_train, Y_train)

# Predict
Y_pred = cart_model.predict(X_test)
# Evaluation
accuracy = accuracy_score(Y_test, Y_pred)
print(f"Accuracy: {accuracy * 100:.2f}%")
print(f"Confusion Matrix:\n{confusion_matrix(Y_test, Y_pred)}")
print(f"Classification Report:\n{classification_report(Y_test, Y_pred)}")


OUTPUT:

 
Accuracy: 100.00%
Confusion Matrix:
[[2 0 0]
 [0 2 0]
 [0 0 2]]
Classification Report:
              precision    recall  f1-score   support

           0       1.00      1.00      1.00         2
           1       1.00      1.00      1.00         2
           2       1.00      1.00      1.00         2

    accuracy                           1.00         6
   macro avg       1.00      1.00      1.00         6
weighted avg       1.00      1.00      1.00         6




Related Content :

1. Simple Linear regression.   View Solution


2. Multiple Linear regression.   View Solution


3. Logistic Regression.   View Solution


4. CHAID.   View Solution


5. CART.   View Solution


6. ARIMA - stock market data.   View Solution


7. Exponential Smoothing.   View Solution


8. Hierarchical clustering.   View Solution


9. Ward's method of clustering.   View Solution


10. Crowdsource predictive analytics- Netflix data.   View Solution