Code a python program that uses machine learning.
- User
Code a python program that uses machine learning.
Assistant
Here's a Python program that uses machine learning to classify iris flowers using the Iris dataset. The program uses logistic regression for classification and evaluates its performance:
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 accuracy_score, classification_report # Load the Iris dataset iris = load_iris() X = iris.data y = iris.target # Print dataset details print("Features:", iris.feature_names) print("Target names:", iris.target_names) # Split dataset into training set and test set X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, random_state=42) # Initialize Logistic Regression Model model = LogisticRegression(max_iter=200) model.fit(X_train, y_train) # Predictions on test data predictions = model.predict(X_test) # Evaluate the model print("\nModel Accuracy:", accuracy_score(y_test, predictions)) print("\nClassification Report:\n", classification_report(y_test, predictions))Explanation:
-
Dataset: Uses the Iris dataset (built-in in scikit-learn) which contains measurements of 150 iris flowers from 3 different species.
-
Splitting Data: Splits data into 80% training and 20% testing sets for evaluation.
-
Model: Uses Logistic Regression for classification. The
max_iter=200parameter ensures convergence. -
Evaluation:
- Accuracy: Overall correctness of predictions
- Classification Report: Shows precision, recall, and F1-score for each class
Output Example:
Features: ['sepal length (cm)', 'sepal width (cm)', 'petal length (cm)', 'petal width (cm)'] Target names: ['setosa' 'versicolor' 'virginica'] Model Accuracy: 0.9666666666666667 Classification Report: precision recall f1-score support setosa 1.00 1.00 1.00 11 versicolor 0.95 0.95 0.95 10 virginica 0.95 0.95 0.95 9 accuracy 0.97 30 macro avg 0.97 0.97 0.97 30 weighted avg 0.97 0.97 0.97 30Key Concepts Demonstrated:
- Data loading and preparation
- Train/Test split
- Model training and prediction
- Performance evaluation metrics
- Handling multi-class classification
You can modify this code to try different models (e.g., Decision Tree, SVM) or datasets by replacing the
load_iris()part.-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.