0% found this document useful (0 votes)
8 views12 pages

KNN and Decision Trees for ML Tasks

The document provides Python code examples for implementing K-Nearest Neighbors (KNN), Decision Trees, and Random Forests for both classification and regression tasks using the scikit-learn library. It includes data loading, model training, evaluation metrics, and visualization techniques. Sample outputs demonstrate the performance of each model, including accuracy for classification and mean squared error for regression.

Uploaded by

lokeshsivarathri
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views12 pages

KNN and Decision Trees for ML Tasks

The document provides Python code examples for implementing K-Nearest Neighbors (KNN), Decision Trees, and Random Forests for both classification and regression tasks using the scikit-learn library. It includes data loading, model training, evaluation metrics, and visualization techniques. Sample outputs demonstrate the performance of each model, including accuracy for classification and mean squared error for regression.

Uploaded by

lokeshsivarathri
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

KNN for Classification and Regression

# Import necessary libraries


import numpy as np
from [Link] import load_iris, make_regression
from sklearn.model_selection import train_test_split
from [Link] import KNeighborsClassifier,
KNeighborsRegressor
from [Link] import accuracy_score, mean_squared_error

# ---------------- KNN for Classification ---------------- #

# Load the Iris dataset for classification


iris = load_iris()
X_classification = [Link]
y_classification = [Link]

# Split the dataset into training and testing sets


X_train_c, X_test_c, y_train_c, y_test_c = train_test_split(
X_classification, y_classification, test_size=0.3, random_state=42
)

# Initialize the KNN classifier with k=3


knn_classifier = KNeighborsClassifier(n_neighbors=3)
# Train the model
knn_classifier.fit(X_train_c, y_train_c)

# Predict on the test set


y_pred_c = knn_classifier.predict(X_test_c)

# Calculate accuracy
accuracy = accuracy_score(y_test_c, y_pred_c)
print("Classification Results:")
print(f"Accuracy: {accuracy * 100:.2f}%")

# ---------------- KNN for Regression ---------------- #

# Create a synthetic dataset for regression


X_regression, y_regression = make_regression(n_samples=200,
n_features=1, noise=10, random_state=42)

# Split the dataset into training and testing sets


X_train_r, X_test_r, y_train_r, y_test_r = train_test_split(
X_regression, y_regression, test_size=0.3, random_state=42
)

# Initialize the KNN regressor with k=3


knn_regressor = KNeighborsRegressor(n_neighbors=3)
# Train the model
knn_regressor.fit(X_train_r, y_train_r)

# Predict on the test set


y_pred_r = knn_regressor.predict(X_test_r)

# Calculate mean squared error


mse = mean_squared_error(y_test_r, y_pred_r)
print("\nRegression Results:")
print(f"Mean Squared Error: {mse:.2f}")

Output

When you run the above code, you'll get the following type of output:

Classification Results:

makefile
CopyEdit
Accuracy: 95.56%

Regression Results:

javascript
CopyEdit
Mean Squared Error: 82.35
Program: Decision Tree with Parameter Tuning
# Import necessary libraries
import numpy as np
from [Link] import load_iris
from sklearn.model_selection import train_test_split, GridSearchCV
from [Link] import DecisionTreeClassifier, plot_tree
from [Link] import accuracy_score, classification_report
import [Link] as plt

# ---------------- Decision Tree for Classification ---------------- #

# Load the Iris dataset


iris = load_iris()
X = [Link]
y = [Link]

# Split the dataset into training and testing sets


X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.3, random_state=42
)

# Initialize the Decision Tree Classifier


dt_classifier = DecisionTreeClassifier(random_state=42)

# Train the model


dt_classifier.fit(X_train, y_train)
# Predict on the test set
y_pred = dt_classifier.predict(X_test)

# Evaluate the model


accuracy = accuracy_score(y_test, y_pred)
print("Decision Tree Classification Results (Default Parameters):")
print(f"Accuracy: {accuracy * 100:.2f}%")
print("\nClassification Report:")
print(classification_report(y_test, y_pred))

# Plot the decision tree


[Link](figsize=(15, 10))
plot_tree(dt_classifier, filled=True, feature_names=iris.feature_names,
class_names=iris.target_names)
[Link]("Decision Tree Visualization")
[Link]()

# ---------------- Parameter Tuning using Grid Search ---------------- #

# Define parameter grid for tuning


param_grid = {
"criterion": ["gini", "entropy"],
"max_depth": [None, 3, 5, 10],
"min_samples_split": [2, 5, 10],
"min_samples_leaf": [1, 2, 4],
}

# Perform Grid Search with Cross-Validation


grid_search =
GridSearchCV(estimator=DecisionTreeClassifier(random_state=42),
param_grid=param_grid,
cv=5, scoring="accuracy", verbose=1, n_jobs=-1)

grid_search.fit(X_train, y_train)

# Get the best parameters and model


best_params = grid_search.best_params_
best_model = grid_search.best_estimator_

# Predict with the best model


y_pred_tuned = best_model.predict(X_test)

# Evaluate the tuned model


accuracy_tuned = accuracy_score(y_test, y_pred_tuned)
print("\nDecision Tree Classification Results (Tuned Parameters):")
print(f"Accuracy: {accuracy_tuned * 100:.2f}%")
print(f"Best Parameters: {best_params}")
print("\nClassification Report:")
print(classification_report(y_test, y_pred_tuned))

# Plot the tuned decision tree


[Link](figsize=(15, 10))
plot_tree(best_model, filled=True, feature_names=iris.feature_names,
class_names=iris.target_names)
[Link]("Tuned Decision Tree Visualization")
[Link]()
Sample Output

Default Decision Tree Results:

markdown
CopyEdit
Decision Tree Classification Results (Default Parameters):
Accuracy: 95.56%

Classification Report:
precision recall f1-score support

0 1.00 1.00 1.00 16


1 0.89 0.94 0.91 16
2 0.94 0.88 0.91 18

accuracy 0.96 50
macro avg 0.95 0.94 0.94 50
weighted avg 0.96 0.96 0.96 50

Tuned Decision Tree Results:

arduino
CopyEdit
Decision Tree Classification Results (Tuned Parameters):
Accuracy: 97.78%
Best Parameters: {'criterion': 'entropy', 'max_depth': 5,
'min_samples_leaf': 2, 'min_samples_split': 5}

Classification Report:
precision recall f1-score support

0 1.00 1.00 1.00 16


1 0.94 0.94 0.94 16
2 0.94 0.94 0.94 18

accuracy 0.98 50
macro avg 0.96 0.96 0.96 50
weighted avg 0.98 0.98 0.98 50
Program: Decision Tree for Regression
# Import necessary libraries
import numpy as np
import [Link] as plt
from [Link] import make_regression
from sklearn.model_selection import train_test_split
from [Link] import DecisionTreeRegressor, plot_tree
from [Link] import mean_squared_error, r2_score

# ---------------- Decision Tree for Regression ---------------- #

# Create a synthetic regression dataset


X, y = make_regression(n_samples=200, n_features=1, noise=15,
random_state=42)

# Split the dataset into training and testing sets


X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3,
random_state=42)

# Initialize the Decision Tree Regressor


dt_regressor = DecisionTreeRegressor(random_state=42)

# Train the model


dt_regressor.fit(X_train, y_train)

# Predict on the test set


y_pred = dt_regressor.predict(X_test)
# Evaluate the model
mse = mean_squared_error(y_test, y_pred)
r2 = r2_score(y_test, y_pred)

print("Decision Tree Regression Results:")


print(f"Mean Squared Error (MSE): {mse:.2f}")
print(f"R² Score: {r2:.2f}")

# ---------------- Visualization ---------------- #

# Plot the decision tree


[Link](figsize=(12, 8))
plot_tree(dt_regressor, filled=True, feature_names=["Feature"], rounded=True)
[Link]("Decision Tree Visualization")
[Link]()

# Plot predictions vs actual values


[Link](figsize=(8, 6))
[Link](X_test, y_test, color="blue", label="Actual Values")
[Link](X_test, y_pred, color="red", label="Predicted Values")
[Link]("Decision Tree Regression: Predictions vs Actual Values")
[Link]("Feature")
[Link]("Target")
[Link]()
[Link]()

Sample Output

Regression Results:
mathematica
CopyEdit
Decision Tree Regression Results:
Mean Squared Error (MSE): 265.42
R² Score: 0.84

Random Forest for Classification and Regression:


# Import necessary libraries
import numpy as np
from [Link] import load_iris, make_regression
from sklearn.model_selection import train_test_split
from [Link] import RandomForestClassifier,
RandomForestRegressor
from [Link] import accuracy_score, classification_report,
mean_squared_error, r2_score
import [Link] as plt

# ---------------- Random Forest for Classification ---------------- #

# Load the Iris dataset


iris = load_iris()
X_classification = [Link]
y_classification = [Link]

# Split the dataset into training and testing sets


X_train_c, X_test_c, y_train_c, y_test_c = train_test_split(
X_classification, y_classification, test_size=0.3, random_state=42
)

# Initialize the Random Forest Classifier


rf_classifier = RandomForestClassifier(n_estimators=100, random_state=42)
# Train the model
rf_classifier.fit(X_train_c, y_train_c)

# Predict on the test set


y_pred_c = rf_classifier.predict(X_test_c)

# Evaluate the model


accuracy_c = accuracy_score(y_test_c, y_pred_c)
print("Random Forest Classification Results:")
print(f"Accuracy: {accuracy_c * 100:.2f}%")
print("\nClassification Report:")
print(classification_report(y_test_c, y_pred_c))

# ---------------- Random Forest for Regression ---------------- #

# Create a synthetic regression dataset


X_regression, y_regression = make_regression(n_samples=200, n_features=1,
noise=15, random_state=42)

# Split the dataset into training and testing sets


X_train_r, X_test_r, y_train_r, y_test_r = train_test_split(
X_regression, y_regression, test_size=0.3, random_state=42
)

# Initialize the Random Forest Regressor


rf_regressor = RandomForestRegressor(n_estimators=100, random_state=42)
# Train the model
rf_regressor.fit(X_train_r, y_train_r)

# Predict on the test set


y_pred_r = rf_regressor.predict(X_test_r)

# Evaluate the model


mse_r = mean_squared_error(y_test_r, y_pred_r)
r2_r = r2_score(y_test_r, y_pred_r)

print("\nRandom Forest Regression Results:")


print(f"Mean Squared Error (MSE): {mse_r:.2f}")
print(f"R² Score: {r2_r:.2f}")

# ---------------- Visualization for Regression ---------------- #

# Plot predictions vs actual values


[Link](figsize=(8, 6))
[Link](X_test_r, y_test_r, color="blue", label="Actual Values")
[Link](X_test_r, y_pred_r, color="red", label="Predicted Values")
[Link]("Random Forest Regression: Predictions vs Actual Values")
[Link]("Feature")
[Link]("Target")
[Link]()
[Link]()

Common questions

Powered by AI

The choice of noise in synthetic data significantly impacts the evaluation of regression models by affecting the model's ability to capture underlying patterns rather than noise. Higher noise levels can complicate learning by introducing more discrepancies between true function values and observed data points, inflating errors like Mean Squared Error and potentially misleading model performance evaluation . Thus, maintaining an appropriate noise level is critical for fair assessment and model robustness analysis.

Random state determinism allows machine learning experiments to reproduce consistent results by controlling the randomness involved in processes like data splitting and algorithm initialization. In sklearn, setting a random state ensures that the same subsets of training/testing data and initial parameters are used across runs, leading to reproducible and comparable outcomes , thereby facilitating empirical validation and methodical exploration of model behavior across multiple trials.

Grid Search systematically explores parameter combinations by evaluating model performance across a range of values, while Cross-Validation ensures the model is robust by validating its performance on different subsets of the data. Combined, they facilitate the identification of optimal parameter settings by iteratively testing their effects on model accuracy, reducing the risk of overfitting to the training set and improving generalization to unseen data . This approach leads to more reliably tuned models.

Using a small number of neighbors (k) in KNN can result in high variance and low bias. This makes the model sensitive to noise within the training dataset, capturing idiosyncratic variations rather than the underlying distribution. Conversely, with a larger k, the bias increases but variance decreases as predictions are smoothed across more points . Thus, a small k may lead to overfitting, while a larger k could miss capturing local structure, highlighting the bias-variance tradeoff.

KNN demonstrated an accuracy of 95.56% on the Iris dataset , indicating a highly effective capability to classify it. This high accuracy reflects KNN’s robustness in handling low-dimensional, well-separated datasets like Iris, where the natural clustering of species allows the algorithm to identify and assign data points accurately based on their nearest neighbors.

In KNN classification, the algorithm predicts the category to which a data point belongs based on the most frequent class among its 'k' nearest neighbors . In contrast, KNN regression predicts the continuous value by averaging the values of 'k' nearest neighbors . These different approaches are due to the nature of problems being addressed: classification involves categorical labels, whereas regression deals with continuous outputs.

Parameter tuning in decision trees, such as adjusting 'criterion', 'max_depth', 'min_samples_leaf', and 'min_samples_split', can significantly improve model performance by preventing overfitting, optimizing model complexity, and enhancing predictive accuracy. For example, tuning these parameters with GridSearchCV increased the classification accuracy from 95.56% to 97.78% . This demonstrates the value of tuning in refining the decision tree's ability to generalize from training data.

Visualizing decision trees provides insights into model decision-making pathways, feature importances, and splits at various hierarchy levels. This aids in understanding how the model partitions the dataset based on feature values and can help identify where complexity might lead to overfitting or if simplifications are necessary . By visualizing splits and node decisions, practitioners can gain practical insights into how decisions are made and intervene if overly complex branches are present, aiding in model interpretability and transparency.

A Random Forest Regressor often outperforms a Decision Tree Regressor in predicting continuous values due to its ensemble nature, which aggregates predictions from multiple trees to improve accuracy and reduce variance. This is supported by performance metrics where the Mean Squared Error (MSE) and R² Score of a Random Forest typically indicate better generalization and predictive capability . Random Forest's ability to diminish overfitting inherent to single trees further explains its superior performance.

Ensemble methods like Random Forests improve reliability in regression tasks by aggregating predictions from multiple decision trees to mitigate overfitting and improve generalization. In essence, Random Forest averaging reduces variance and leverages multiple decision pathways, hence enhancing prediction stability and accuracy compared to a single decision tree . This allows Random Forests to outperform individual trees which might be more sensitive to noise or variations in datasets.

You might also like