Below is an example Python program that uses a simple machine learning algorithm (logistic regression) to classify the Iris dataset. This program uses the popular scikit-learn library. You can run this code in your Python environment—make sure you have scikit-learn installed (e.g., with pip install scikit-learn).
python
import numpy as np
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import classification_report, accuracy_score
def main():
# Load the Iris dataset
iris = load_iris()
X = iris.data # Features: sepal length, sepal width, petal length, petal width
y = iris.target # Labels (species indices)
# Split the dataset into training (80%) and testing (20%)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# Instantiate the Logistic Regression classifier
clf = LogisticRegression(max_iter=200, solver='lbfgs', multi_class='auto')
# Train the classifier on the training set
clf.fit(X_train, y_train)
# Predict the classes for the test set
predictions = clf.predict(X_test)
# Evaluate the classifier's performance
accuracy = accuracy_score(y_test, predictions)
report = classification_report(y_test, predictions, target_names=iris.target_names)
print(f"Accuracy: {accuracy:.2f}")
print("Classification Report:")
print(report)
if __name__ == "__main__":
main()
How It Works
Loading the Data:
The Iris dataset is loaded via load_iris(), which provides both the features (X) and the labels (y).
Splitting the Data:
The data is split into a training set (80%) and a testing set (20%) with train_test_split(). Setting the random_state parameter ensures reproducibility.
Building and Training the Model:
A logistic regression model is created and then trained on the training data using the fit() method.
Making Predictions and Evaluation:
The trained model is used to predict the labels for the test data, and the performance is evaluated by calculating the accuracy and generating a classification report.
Feel free to modify or extend this program—for example, by using a different dataset or experimenting with different machine learning algorithms!