Can you please give me a sample machine learning code.
- User
Can you please give me a sample machine learning code.
- Assistant
Can you please give me a sample machine learning code.
Certainly! Below is a sample machine learning code using Python's scikit-learn library to perform a classification task on the Iris dataset. This example demonstrates how to:
We'll use a Decision Tree Classifier for this example, but you can easily switch to other classifiers like Logistic Regression, Support Vector Machines, etc.
Make sure you have the following libraries installed. You can install them using pip if you haven't already:
pip install numpy pandas scikit-learn matplotlib seaborn
# Import necessary libraries
import numpy as np
import pandas as pd
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import classification_report, confusion_matrix, accuracy_score
import matplotlib.pyplot as plt
import seaborn as sns
# 1. Load the Iris dataset
iris = load_iris()
X = iris.data # Features: sepal length, sepal width, petal length, petal width
y = iris.target # Target: Species (0: setosa, 1: versicolor, 2: virginica)
# Convert to a pandas DataFrame for better visualization
df = pd.DataFrame(X, columns=iris.feature_names)
df['species'] = y
print("First five rows of the dataset:")
print(df.head())
# 2. Visualize the data (optional but recommended)
sns.pairplot(df, hue='species', markers=["o", "s", "D"])
plt.show()
# 3. Split the data into training and testing sets
# - 80% for training and 20% for testing
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 4. Initialize and train the Decision Tree Classifier
clf = DecisionTreeClassifier(random_state=42)
clf.fit(X_train, y_train)
# 5. Make predictions on the test set
y_pred = clf.predict(X_test)
# 6. Evaluate the model
print("\nConfusion Matrix:")
conf_matrix = confusion_matrix(y_test, y_pred)
print(conf_matrix)
print("\nClassification Report:")
class_report = classification_report(y_test, y_pred, target_names=iris.target_names)
print(class_report)
accuracy = accuracy_score(y_test, y_pred)
print(f"Accuracy: {accuracy * 100:.2f}%")
# 7. (Optional) Visualize the Decision Tree
from sklearn import tree
plt.figure(figsize=(12,8))
tree.plot_tree(clf, feature_names=iris.feature_names, class_names=iris.target_names, filled=True)
plt.show()
Import Libraries:
Load the Dataset:
Data Visualization:
sns.pairplot creates a grid of scatter plots to visualize relationships between features colored by species.Data Splitting:
random_state ensures reproducibility.Model Training:
Making Predictions & Evaluation:
Visualizing the Decision Tree:
After running the code:
Data Head: You'll see the first five rows of the dataset showcasing feature values and the encoded species.
Pairplot: A visual representation of feature relationships. Different species will be colored differently, helping identify patterns.
Confusion Matrix: A table showing the number of correct and incorrect predictions made by the classifier.
Classification Report: Detailed metrics for each class, including:
Accuracy: The percentage of total correct predictions.
Decision Tree Visualization: A graphical representation of the decision rules used by the classifier.
Try Different Models: Replace DecisionTreeClassifier with other classifiers like LogisticRegression, SVC, or RandomForestClassifier to compare performance.
Hyperparameter Tuning: Optimize model parameters using techniques like Grid Search.
Cross-Validation: Use cross-validation to get a better estimate of the model's performance.
Feature Engineering: Explore adding or modifying features to improve model accuracy.
Handling Overfitting: Implement techniques like pruning for Decision Trees to prevent overfitting.
Feel free to customize and expand upon this sample code based on your specific project requirements!
Not yet included in a published release.