Skip to main content
Machine Learning beginner Lesson 3 of 11

Introduction to Machine Learning Models

Build, train, and evaluate your first classification model using Scikit-Learn.

Machine learning focuses on algorithms that learn patterns from datasets. In this tutorial, we will build a classification model to predict iris species using scikit-learn.

Environment Setup

Install the required scientific packages:

pip install scikit-learn numpy pandas

Model Training Lifecycle

The machine learning lifecycle consists of:

  1. Loading and cleaning data.
  2. Splitting into training and test datasets.
  3. Defining and training the model estimator.
  4. Evaluating metrics.
import pandas as pd
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score, classification_report

# 1. Load Dataset
raw_data = load_iris()
X = pd.DataFrame(raw_data.data, columns=raw_data.feature_names)
y = raw_data.target

# 2. Split Data (80% Train, 20% Test)
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42, stratify=y
)

# 3. Initialize and Train Model
classifier = RandomForestClassifier(n_estimators=100, random_state=42)
classifier.fit(X_train, y_train)

# 4. Predict and Evaluate
predictions = classifier.predict(X_test)
accuracy = accuracy_score(y_test, predictions)

print(f"Model Accuracy: {accuracy:.4f}")
print("\nClassification Report:")
print(classification_report(y_test, predictions, target_names=raw_data.target_names))

Tracking Parameters

In production environments, avoid running scripts blind. Use MLOps systems like MLflow to track parameters:

import mlflow

with mlflow.start_run():
    mlflow.log_param("n_estimators", 100)
    mlflow.log_metric("accuracy", accuracy)
    mlflow.sklearn.log_model(classifier, "model")