You are given two files, trainData.csv and testData.csv. Look at these files first. You will see that the
training data has 750 entries, each with two attribute values in the first two columns, and a class label
in the third column. The test dataset has 250 entries of the same type. (see attached notebook)
(a) Use scikit-learn to create a Decision Tree classifier using default parameters and fit the training data
to it.
(b) How will you list the default parameters used by the classifier? (These are the parameters you could
supply to the tree constructor)
If clf is the classifier from:
from sklearn.tree import DecisionTreeClassifier
clf = DecisionTreeClassifier()
clf.get_params() will output the list of parameters
(c) Find the predictions made by the model for the test
data, and compare with the actual class labels to see how
good your model is (calculate 'accuracy')
(d) Repeat (a)-(c) by using ‘entropy’ criterion instead of the default ‘gini’ for splitting.
(e) Is there a significant difference in terms of test accuracy between using ‘gini’ and ‘entropy’?
Assistant
Certainly! Let's walk through each part of the problem step-by-step using Python's scikit-learn library. We'll assume that you have a Jupyter notebook environment set up and that the trainData.csv and testData.csv files are accessible in your working directory.
Prerequisites
Before diving into the specific parts, ensure you have the necessary libraries installed. If not, you can install them using pip:
python
!pip install pandas scikit-learn
Import the required libraries:
python
import pandas as pd
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score
Part (a): Create and Fit a Decision Tree Classifier with Default Parameters
Objective: Use scikit-learn to create a Decision Tree classifier using default parameters and fit the training data.
Steps:
Load the Training Data
Separate Features and Labels
Instantiate the Classifier with Default Parameters
Fit the Model to the Training Data
Code and Explanation:
python
# Step 1: Load the Training Data
train_data = pd.read_csv('trainData.csv', header=None)
print("Training Data Shape:", train_data.shape)
train_data.head()
Assumption: The CSV files do not have headers. If they do, remove header=None or set header= 'your_header_row'.
python
# Step 2: Separate Features and Labels
X_train = train_data.iloc[:, :-1] # First two columns as features
y_train = train_data.iloc[:, -1] # Third column as labels
print("Features Shape:", X_train.shape)
print("Labels Shape:", y_train.shape)
python
# Step 3: Instantiate the Classifier with Default Parameters
clf = DecisionTreeClassifier()
python
# Step 4: Fit the Model to the Training Data
clf.fit(X_train, y_train)
print("Decision Tree model has been trained with default parameters.")
Output:
code
Decision Tree model has been trained with default parameters.
Part (b): List the Default Parameters Used by the Classifier
Objective: List the default parameters used by the DecisionTreeClassifier.
Approach: Use the get_params() method to retrieve all parameters and their default values.
Code and Explanation:
python
# List default parameters
default_params = clf.get_params()
print("Default Parameters of DecisionTreeClassifier:")
for param, value in default_params.items():
print(f"{param}: {value}")
Note: The actual output will list all default parameters. Some parameters are omitted here for brevity.
Part (c): Predict on Test Data and Calculate Accuracy
Objective: Make predictions on the test dataset and calculate the accuracy of the model.
Steps:
Load the Test Data
Separate Features and Labels
Make Predictions
Calculate Accuracy
Code and Explanation:
python
# Step 1: Load the Test Data
test_data = pd.read_csv('testData.csv', header=None)
print("Test Data Shape:", test_data.shape)
test_data.head()
python
# Step 2: Separate Features and Labels
X_test = test_data.iloc[:, :-1] # First two columns as features
y_test = test_data.iloc[:, -1] # Third column as labels
print("Test Features Shape:", X_test.shape)
print("Test Labels Shape:", y_test.shape)
python
# Step 3: Make Predictions
y_pred = clf.predict(X_test)
print("Predictions on Test Data:")
print(y_pred)
python
# Step 4: Calculate Accuracy
accuracy = accuracy_score(y_test, y_pred)
print(f"Accuracy of Decision Tree (default parameters) on Test Data: {accuracy * 100:.2f}%")
Sample Output:
code
Accuracy of Decision Tree (default parameters) on Test Data: 85.60%
Note: The actual accuracy may vary based on the dataset.
Part (d): Repeat Parts (a)-(c) Using 'entropy' Criterion Instead of 'gini'
Objective: Create and evaluate a Decision Tree classifier using the 'entropy' criterion for splitting.
Steps:
Instantiate the Classifier with 'entropy' Criterion
Fit the Model
Make Predictions
Calculate Accuracy
Code and Explanation:
python
# Step 1: Instantiate the Classifier with 'entropy' Criterion
clf_entropy = DecisionTreeClassifier(criterion='entropy')
python
# Step 2: Fit the Model
clf_entropy.fit(X_train, y_train)
print("Decision Tree model has been trained with 'entropy' criterion.")
Output:
code
Decision Tree model has been trained with 'entropy' criterion.
python
# Step 3: Make Predictions
y_pred_entropy = clf_entropy.predict(X_test)
print("Predictions on Test Data using 'entropy':")
print(y_pred_entropy)
python
# Step 4: Calculate Accuracy
accuracy_entropy = accuracy_score(y_test, y_pred_entropy)
print(f"Accuracy of Decision Tree ('entropy' criterion) on Test Data: {accuracy_entropy * 100:.2f}%")
Sample Output:
code
Accuracy of Decision Tree ('entropy' criterion) on Test Data: 86.00%
Note: The actual accuracy may vary based on the dataset.
Part (e): Compare Test Accuracies Between 'gini' and 'entropy' Criteria
Objective: Determine whether there's a significant difference in test accuracy between using 'gini' and 'entropy' as the splitting criteria.
Approach:
Compare the Two Accuracies
Statistical Significance (Optional)
Provide Interpretation
Code and Explanation:
python
print(f"Accuracy with 'gini' criterion: {accuracy * 100:.2f}%")
print(f"Accuracy with 'entropy' criterion: {accuracy_entropy * 100:.2f}%")
Sample Output:
code
Accuracy with 'gini' criterion: 85.60%
Accuracy with 'entropy' criterion: 86.00%
Interpretation:
Difference in Accuracy: In this example, the 'entropy' criterion slightly outperforms 'gini' by 0.4%.
Statistical Significance: To determine if this difference is statistically significant, one might perform hypothesis testing (e.g., McNemar's test) considering the predictions on the same test set. However, a mere 0.4% difference is typically not considered significant, especially if it's within the margin of error.
Conclusion: There is no significant difference in test accuracy between using 'gini' and 'entropy' criteria based on this example. Both criteria perform similarly, and the choice between them can be based on other factors such as computational efficiency or interpretability.
Additional Consideration (Optional):
If you wish to perform a statistical test to check the significance of the difference, you can use McNemar's test. Here's how you might do it:
python
from sklearn.metrics import confusion_matrix
# Create a confusion matrix for the differences between the two models
cm = confusion_matrix(y_test, y_pred) + confusion_matrix(y_test, y_pred_entropy)
print("Confusion Matrix combining both models:")
print(cm)
# However, implementing McNemar's test requires a more detailed setup.
# For simplicity, we can use statsmodels library.
!pip install statsmodels
from statsmodels.stats.contingency_tables import mcnemar
# Calculate where predictions differ
diff = (y_pred != y_test).astype(int) + (y_pred_entropy != y_test).astype(int)
# Prepare contingency table
both_correct = ((y_pred == y_test) & (y_pred_entropy == y_test)).sum()
clf_correct = ((y_pred == y_test) & (y_pred_entropy != y_test)).sum()
clf_entropy_correct = ((y_pred != y_test) & (y_pred_entropy == y_test)).sum()
both_incorrect = ((y_pred != y_test) & (y_pred_entropy != y_test)).sum()
table = [[both_correct, clf_correct],
[clf_entropy_correct, both_incorrect]]
result = mcnemar(table, exact=True)
print('McNemar’s test statistic=%.3f, p-value=%.3f' % (result.statistic, result.pvalue))
if result.pvalue < 0.05:
print("The difference is statistically significant.")
else:
print("The difference is not statistically significant.")
Note: Implementing McNemar's test requires careful construction of the contingency table based on the predictions of both models compared to the true labels. The above code provides a simplified version and assumes binary classification. Adjust accordingly for multi-class scenarios.
Summary
Part (a): You trained a Decision Tree classifier with default parameters (gini criterion).
Part (b): Listed all default parameters using clf.get_params().
Part (c): Made predictions on the test set and calculated the accuracy.
Part (d): Repeated the process using the entropy criterion instead of gini.
Part (e): Compared the accuracies and concluded that there's no significant difference between the two criteria based on the observed accuracies.
Both gini and entropy criteria are popular for measuring the quality of splits in decision trees. While they often yield similar results, minor differences can occur depending on the dataset. It's good practice to experiment with both to see which performs better for your specific case.