If you have any query feel free to chat us!
Happy Coding! Happy Learning!
Here's a simple example of how you can implement a Decision Tree classifier using Python and the scikit-learn
library for a classification task:
from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split from sklearn.tree import DecisionTreeClassifier from sklearn.metrics import accuracy_score # Load the Iris dataset (you can replace this with your own dataset) iris = load_iris() X = iris.data y = iris.target # Split data into training and testing sets X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) # Create and train the Decision Tree classifier model = DecisionTreeClassifier(random_state=42) model.fit(X_train, y_train) # Make predictions on the test set y_pred = model.predict(X_test) # Calculate accuracy accuracy = accuracy_score(y_test, y_pred) print(f"Accuracy: {accuracy:.2f}")
This code snippet demonstrates the following steps:
sklearn
modules).DecisionTreeClassifier
model from scikit-learn
.You can replace the dataset loading and preprocessing steps with your own data if you're working with a different dataset. Additionally, you might need to adjust hyperparameters of the Decision Tree, such as the maximum depth of the tree or the criterion used for splitting (e.g., Gini impurity or entropy).
This example covers a simple classification task, but you can adapt the code for regression tasks using DecisionTreeRegressor
from scikit-learn
.
Comments: 0