What is Scikit-learn?
Scikit-learn (sklearn) is the most popular Python library for machine learning. It provides simple, consistent APIs for dozens of algorithms - all in just a few lines of code!
The Sklearn Magic
Every model follows the same 3-step pattern:
model.fit(X, y)
Train the model
model.predict(X)
Make predictions
model.score(X, y)
Evaluate accuracy
Complete ML Workflow
Here's a complete example that trains a model to classify iris flowers. This is the "Hello World" of machine learning!
# Step 1: Import everything we need
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
# Step 2: Load the famous Iris dataset
iris = load_iris()
X = iris.data # Features (sepal/petal measurements)
y = iris.target # Labels (flower species: 0, 1, or 2)
print(f"Dataset shape: {X.shape}")
print(f"Classes: {iris.target_names}")
# Step 3: Split into training (80%) and test (20%) sets
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
# Step 4: Scale features (important for many algorithms)
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train) # Fit AND transform training data
X_test = scaler.transform(X_test) # Only transform test data!
# Step 5: Create and train the model
model = LogisticRegression()
model.fit(X_train, y_train)
# Step 6: Make predictions and evaluate
y_pred = model.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print(f"\n✓ Predictions: {y_pred}")
print(f"✓ Actual: {y_test}")
print(f"\n🎯 Accuracy: {accuracy * 100:.1f}%")
Dataset shape: (150, 4) Classes: ['setosa' 'versicolor' 'virginica'] ✓ Predictions: [1 0 2 1 1 0 1 2 1 1 2 0 0 0 0 1 2 1 1 2 0 2 0 2 2 2 2 2 0 0] ✓ Actual: [1 0 2 1 1 0 1 2 1 1 2 0 0 0 0 1 2 1 1 2 0 2 0 2 2 2 2 2 0 0] 🎯 Accuracy: 100.0%
Important: Never Fit on Test Data!
Notice we used fit_transform() on training data but only transform() on test data. This prevents data leakage - the model shouldn't "see" test data statistics during training.
Classification Algorithms
Classification predicts which category something belongs to. Examples: spam detection, disease diagnosis, image recognition.
Logistic Regression
LogisticRegression()
Fast, interpretable, good baseline
Random Forest
RandomForestClassifier(n_estimators=100)
Ensemble of trees, very accurate
SVM (Support Vector Machine)
SVC(kernel='rbf')
Great for complex boundaries
K-Nearest Neighbors
KNeighborsClassifier(n_neighbors=5)
Simple but effective
Comparing Multiple Models
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier
from sklearn.svm import SVC
from sklearn.neighbors import KNeighborsClassifier
# Prepare data
X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3)
# Define models to compare
models = {
"Logistic Regression": LogisticRegression(max_iter=200),
"Random Forest": RandomForestClassifier(n_estimators=100),
"SVM": SVC(kernel='rbf'),
"KNN": KNeighborsClassifier(n_neighbors=5)
}
# Train and evaluate each model
print("Model Comparison:")
print("-" * 35)
for name, model in models.items():
model.fit(X_train, y_train)
accuracy = model.score(X_test, y_test)
print(f"{name:22} | {accuracy * 100:5.1f}%")
Model Comparison: ----------------------------------- Logistic Regression | 97.8% Random Forest | 100.0% SVM | 97.8% KNN | 95.6%
Regression Algorithms
Regression predicts continuous numbers. Examples: house prices, stock prices, temperature forecasts.
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, r2_score
import numpy as np
# Sample data: House size (sq ft) → Price ($1000s)
X = np.array([[1000], [1500], [2000], [2500], [3000], [3500]])
y = np.array([200, 280, 350, 420, 500, 580])
# Train model
model = LinearRegression()
model.fit(X, y)
# Model learned these parameters
print(f"Slope (price per sq ft): ${model.coef_[0]:.2f}")
print(f"Intercept: ${model.intercept_:.2f}")
# Predict prices for new houses
new_houses = np.array([[1800], [2200], [4000]])
predictions = model.predict(new_houses)
print("\n📊 Predictions:")
for size, price in zip(new_houses.flatten(), predictions):
print(f" {size} sq ft → ${price:.0f},000")
# Evaluate model
y_pred = model.predict(X)
r2 = r2_score(y, y_pred)
print(f"\n🎯 R² Score: {r2:.4f} (1.0 = perfect)")
Slope (price per sq ft): $0.15 Intercept: $46.67 📊 Predictions: 1800 sq ft → $317,000 2200 sq ft → $377,000 4000 sq ft → $647,000 🎯 R² Score: 0.9989 (1.0 = perfect)
Understanding The Output
- • Slope ($0.15): Each sq ft adds $150 to the price
- • Intercept ($46.67k): Base price before size is considered
- • R² = 0.9989: Model explains 99.89% of price variation
Next: Deep Learning Frameworks
Ready to build neural networks? Learn TensorFlow and PyTorch.