Umlimit ai frame
Here's a demonstration of a simple AI using a decision tree classifier with Python and the scikit-learn library. The example demonstrates how to train a model, evaluate its performance, and predict new data.
scikit-learn library. The example demonstrates how to train a model, evaluate its performance, and predict new data.Install Required Libraries:
pip install scikit-learn matplotlibExample Code: Decision Tree Classification
# Import necessary libraries
import numpy as np
import matplotlib.pyplot as plt
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, confusion_matrix, classification_report
# Load the Iris dataset
data = load_iris()
X = data.data # Features
y = data.target # Labels
# Split the dataset into training and test sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
# Create a Decision Tree Classifier
clf = DecisionTreeClassifier(random_state=42)
# Train the model
clf.fit(X_train, y_train)
# Make predictions
y_pred = clf.predict(X_test)
# Evaluate the model
accuracy = accuracy_score(y_test, y_pred)
print(f"Accuracy: {accuracy * 100:.2f}%")
# Display the confusion matrix
conf_matrix = confusion_matrix(y_test, y_pred)
print("\nConfusion Matrix:")
print(conf_matrix)
# Display the classification report
print("\nClassification Report:")
print(classification_report(y_test, y_pred))
# Visualize the Decision Tree
from sklearn.tree import plot_tree
plt.figure(figsize=(15, 10))
plot_tree(clf, filled=True, feature_names=data.feature_names, class_names=data.target_names)
plt.title("Decision Tree for Iris Dataset")
plt.show()
Explanation of the Code:
Sample Output:
Code Explanation:
Summary:
Last updated