Consider the data given in data_t2.csv file. The aim is to develop a binary classification model for the
data, where the class variable is the last column, 1 or 0.
(40 points)
(a) Do a 90%-10% split into train test data, using a random_state of 102. Is stratification warranted? If
so, do it.
(b) You are going to try three different classifiers
Decision Tree (with max_depth=3 and the same random_state of 102)
Support Vector classifier (rbf kernel and C=1000)
Random Forest classifier with default parameters.
(c) For each model, list the metric report (precision, recall, f1-score, accuracy) for the two classes.
(You may use metrics.classification_report() ).
(d) Draw decision boundaries for each classifier, displaying the test data on top of the decision
contour plots. Provide appropriate titles for your figures.
you take take data like this: x y class
1 105.651303747892 234.103265743244 1
2 121.393520992769 289.122956287957 1
3 131.0609108511 291.336802160888 1
4 151.637348993749 247.911783767132 1
5 123.467110482344 221.835832778682 1
6 83.9273028429849 249.688843263296 1
7 118.484126134291 261.221075594259 1
8 144.491171324571 207.711967016533 1
9 106.528174611012 258.334597762796 1
10 148.03357068677 216.727973638597 1
11 120.426966247009 261.801872571243 1
12 127.077592372005 191.260047013697 1
13 105.441465557795 250.705811142053 1
Assistant
Certainly! Let's walk through the steps required to develop a binary classification model using the provided dataset. We'll use Python along with libraries such as pandas, scikit-learn, and matplotlib to accomplish the tasks. Here's a comprehensive guide covering each part of your question.
1. (a) Train-Test Split with Stratification
Objective:
Split the dataset into training and testing sets with a 90%-10% ratio using a random_state of 102. Determine if stratification is necessary and apply it if warranted.
Why Stratification?
Stratification ensures that the proportion of classes in the training and testing sets mirrors that of the original dataset. This is particularly important if the classes are imbalanced.
Implementation:
python
import pandas as pd
from sklearn.model_selection import train_test_split
from collections import Counter
# Load the dataset
# Assuming the CSV file has columns: index, x, y, class
data = pd.read_csv('data_t2.csv')
# Features and target variable
X = data[['x', 'y']]
y = data['class']
# Check class distribution
class_counts = Counter(y)
print("Class distribution:", class_counts)
# Determine if stratification is needed
# Generally, use stratify if classes are imbalanced
stratify = True if len(class_counts) > 1 else False
# Perform train-test split
X_train, X_test, y_train, y_test = train_test_split(
X, y,
test_size=0.10,
random_state=102,
stratify=y if stratify else None
)
# Verify the split
print("Training set class distribution:", Counter(y_train))
print("Testing set class distribution:", Counter(y_test))
Explanation:
Loading Data: We begin by loading the dataset using pandas.read_csv.
Feature and Target Separation: The features are x and y, and the target variable is class.
Class Distribution: Using Counter, we check the distribution of classes to decide on stratification.
Stratification Decision: If there are multiple classes and they are imbalanced, stratification is applied.
Train-Test Split: Using train_test_split, we split the data accordingly.
Verification: Finally, we print out the class distributions in both training and testing sets to ensure stratification.
1. (b) Initializing Classifiers
Objective:
Initialize three different classifiers:
Decision Tree with max_depth=3 and random_state=102.
Support Vector Classifier (SVC) with an RBF kernel and C=1000.
Random Forest Classifier with default parameters.
Implementation:
python
from sklearn.tree import DecisionTreeClassifier
from sklearn.svm import SVC
from sklearn.ensemble import RandomForestClassifier
# Initialize classifiers
dt_classifier = DecisionTreeClassifier(max_depth=3, random_state=102)
svc_classifier = SVC(kernel='rbf', C=1000, probability=True, random_state=102)
rf_classifier = RandomForestClassifier(random_state=102)
Explanation:
Decision Tree: Limited to a depth of 3 to prevent overfitting.
SVC: Uses the Radial Basis Function (RBF) kernel with a high penalty parameter C=1000 to allow for a smaller margin. The probability=True parameter enables probability estimates which can be useful for certain applications.
Random Forest: Utilizes default settings, which generally provide robust performance.
1. (c) Generating Classification Reports
Objective:
For each classifier, generate a classification report that includes precision, recall, f1-score, and accuracy for both classes.
Implementation:
python
from sklearn.metrics import classification_report, accuracy_score
# Function to train and evaluate classifiers
def evaluate_classifier(clf, X_train, y_train, X_test, y_test, clf_name):
# Train the classifier
clf.fit(X_train, y_train)
# Predict on the test set
y_pred = clf.predict(X_test)
# Calculate accuracy
accuracy = accuracy_score(y_test, y_pred)
# Generate classification report
report = classification_report(y_test, y_pred, digits=4)
print(f"=== {clf_name} ===")
print(f"Accuracy: {accuracy:.4f}")
print("Classification Report:")
print(report)
print("\n")
# Evaluate Decision Tree
evaluate_classifier(dt_classifier, X_train, y_train, X_test, y_test, "Decision Tree")
# Evaluate SVC
evaluate_classifier(svc_classifier, X_train, y_train, X_test, y_test, "Support Vector Classifier")
# Evaluate Random Forest
evaluate_classifier(rf_classifier, X_train, y_train, X_test, y_test, "Random Forest")
Note: The above metrics are illustrative. Your actual results may vary based on the dataset.
Explanation:
Training: Each classifier is trained on the training set.
Prediction: Predictions are made on the test set.
Evaluation: For each classifier, we compute the accuracy and generate a detailed classification report using classification_report from scikit-learn.
1. (d) Visualizing Decision Boundaries
Objective:
Draw decision boundaries for each classifier, overlaying the test data on top of the decision contour plots with appropriate titles.
Implementation:
To visualize decision boundaries, we'll use a mesh grid to plot the regions predicted by each classifier and overlay the test data points.
python
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
# Define a function to plot decision boundaries
def plot_decision_boundary(clf, X, y, X_test, y_test, title):
# Define the mesh grid boundaries
x_min, x_max = X['x'].min() - 10, X['x'].max() + 10
y_min, y_max = X['y'].min() - 10, X['y'].max() + 10
h = 0.5 # step size in the mesh
xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
np.arange(y_min, y_max, h))
# Predict for each point in the mesh
Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)
# Define custom colors
cmap_light = ListedColormap(['#FFAAAA', '#AAFFAA'])
cmap_bold = ListedColormap(['#FF0000', '#00FF00'])
plt.figure(figsize=(8,6))
plt.contourf(xx, yy, Z, alpha=0.3, cmap=cmap_light)
plt.scatter(X_test['x'], X_test['y'], c=y_test, cmap=cmap_bold, edgecolor='k', s=50)
plt.xlabel('x')
plt.ylabel('y')
plt.title(title)
plt.show()
# Plot Decision Tree Decision Boundary
plot_decision_boundary(dt_classifier, X_train, y_train, X_test, y_test, "Decision Tree Decision Boundary")
# Plot SVC Decision Boundary
plot_decision_boundary(svc_classifier, X_train, y_train, X_test, y_test, "Support Vector Classifier Decision Boundary")
# Plot Random Forest Decision Boundary
plot_decision_boundary(rf_classifier, X_train, y_train, X_test, y_test, "Random Forest Decision Boundary")
Explanation:
Mesh Grid Creation:
We create a grid of points spanning the feature space to evaluate the classifier's predictions. The h parameter determines the resolution of the grid.
Prediction Over Grid:
For each point in the grid, we use the trained classifier to predict the class, reshaping the results to match the grid's shape.
Plotting:
Contour Plot: Represents different regions predicted by the classifier with semi-transparent colors.
Test Data Overlay: The actual test data points are overlaid on the contour plot, colored by their true class.
Visualization:
Each plot is titled appropriately to indicate which classifier's decision boundary is being displayed.
Sample Plots:
As this is a text-based medium, I cannot display the actual plots here. However, running the above code in a Python environment will generate three separate plots visualizing the decision boundaries for each classifier.
Complete Code Overview
For convenience, here's the complete code assembled together:
python
Additional Considerations
Handling Imbalanced Data:
If your dataset has a significant class imbalance, consider techniques such as:
Resampling: Over-sampling the minority class or under-sampling the majority class.
Using Different Metrics: Precision, recall, and F1-score are often more informative than accuracy in such scenarios.
Algorithmic Approaches: Algorithms like BalancedRandomForestClassifier or using class weights can help.
Hyperparameter Tuning:
While we've used specific parameters for the classifiers, tuning hyperparameters using techniques like Grid Search or Randomized Search can potentially improve performance.
Cross-Validation:
Instead of a single train-test split, using cross-validation provides a more robust evaluation of model performance.
Feature Scaling:
For classifiers like SVC, feature scaling (e.g., using StandardScaler) can significantly impact performance.
Ensemble Methods:
Combining multiple classifiers can sometimes yield better results than individual models.
Feel free to execute the provided code in your Python environment. Ensure that the data_t2.csv file is correctly formatted and located in your working directory. The visualization part requires a graphical backend; if you're using environments like Jupyter Notebook, the plots will display inline. Otherwise, they will pop up in separate windows.
Not yet included in a published release.
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.svm import SVC
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import classification_report, accuracy_score
from collections import Counter
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
# 1. (a) Train-Test Split with Stratification
# Load the dataset
data = pd.read_csv('data_t2.csv')
# Features and target variable
X = data[['x', 'y']]
y = data['class']
# Check class distribution
class_counts = Counter(y)
print("Class distribution:", class_counts)
# Determine if stratification is needed
stratify = True if len(class_counts) > 1 else False
# Perform train-test split
X_train, X_test, y_train, y_test = train_test_split(
X, y,
test_size=0.10,
random_state=102,
stratify=y if stratify else None
)
# Verify the split
print("Training set class distribution:", Counter(y_train))
print("Testing set class distribution:", Counter(y_test))
# 1. (b) Initialize Classifiers
# Decision Tree
dt_classifier = DecisionTreeClassifier(max_depth=3, random_state=102)
# Support Vector Classifier
svc_classifier = SVC(kernel='rbf', C=1000, probability=True, random_state=102)
# Random Forest
rf_classifier = RandomForestClassifier(random_state=102)
# 1. (c) Generate Classification Reports
def evaluate_classifier(clf, X_train, y_train, X_test, y_test, clf_name):
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
report = classification_report(y_test, y_pred, digits=4)
print(f"=== {clf_name} ===")
print(f"Accuracy: {accuracy:.4f}")
print("Classification Report:")
print(report)
print("\n")
# Evaluate Decision Tree
evaluate_classifier(dt_classifier, X_train, y_train, X_test, y_test, "Decision Tree")
# Evaluate SVC
evaluate_classifier(svc_classifier, X_train, y_train, X_test, y_test, "Support Vector Classifier")
# Evaluate Random Forest
evaluate_classifier(rf_classifier, X_train, y_train, X_test, y_test, "Random Forest")
# 1. (d) Visualizing Decision Boundaries
def plot_decision_boundary(clf, X, y, X_test, y_test, title):
x_min, x_max = X['x'].min() - 10, X['x'].max() + 10
y_min, y_max = X['y'].min() - 10, X['y'].max() + 10
h = 0.5
xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
np.arange(y_min, y_max, h))
Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)
cmap_light = ListedColormap(['#FFAAAA', '#AAFFAA'])
cmap_bold = ListedColormap(['#FF0000', '#00FF00'])
plt.figure(figsize=(8,6))
plt.contourf(xx, yy, Z, alpha=0.3, cmap=cmap_light)
plt.scatter(X_test['x'], X_test['y'], c=y_test, cmap=cmap_bold, edgecolor='k', s=50)
plt.xlabel('x')
plt.ylabel('y')
plt.title(title)
plt.show()
# Plot Decision Tree Decision Boundary
plot_decision_boundary(dt_classifier, X_train, y_train, X_test, y_test, "Decision Tree Decision Boundary")
# Plot SVC Decision Boundary
plot_decision_boundary(svc_classifier, X_train, y_train, X_test, y_test, "Support Vector Classifier Decision Boundary")
# Plot Random Forest Decision Boundary
plot_decision_boundary(rf_classifier, X_train, y_train, X_test, y_test, "Random Forest Decision Boundary")