Search Knowledge

© 2026 LIBREUNI PROJECT

Python for Scientific Computing / Scikit-Learn Deep Dive

Scikit-Learn: Machine Learning Principles

The Scikit-Learn Ecosystem

Scikit-Learn (frequently abbreviated as sklearn) is the primary library for classical machine learning in Python. Built on top of NumPy, SciPy, and Matplotlib, it provides simple and efficient tools for predictive data analysis.

Key Concepts and the Estimator API

The brilliance of Scikit-Learn lies in its consistent API. Whether you are performing linear regression, support vector machines, or random forests, the workflow is almost identical.

Code
skinparam componentStyle rectangle

package "Data Preparation" {
[Features (X)]
[Target (y)]
}

node "Scikit-Learn Workflow" {
component "Instantiate Model" as MK
component "fit(X, y)" as FIT
component "predict(X_new)" as PRED
}

[Features (X)] --> MK
[Target (y)] --> MK
MK --> FIT : "Training"
FIT --> PRED : "Inference"
Data PreparationScikit-Learn WorkflowFeatures (X)Target (y)Instantiate Modelfit(X, y)predict(X_new)TrainingInference

The Three Main Steps:

  1. Instantiate: Choose your model class and set hyperparameters.
  2. Fit: Train the model on your data using the fit() method.
  3. Predict: Apply the trained model to new data using predict() or transform().

Data Representation in Scikit-Learn

Scikit-Learn expects data in a specific format:

  • X (Feature Matrix): A 2D array or DataFrame of shape [n_samples, n_features].
  • y (Target Vector): A 1D array or Series of length n_samples.

A Simple Example: Linear Regression

Let’s see how we can predict a continuous value using Scikit-Learn.

python
1 
2from sklearn.linear_model import LinearRegression
3import numpy as np
4 
5# 1. Create Data
6X = np.array([[1], [2], [3], [4]]) # Feature matrix
7y = np.array([2, 4, 6, 8]) # Target vector (y = 2*x)
8 
9# 2. Instantiate Model
10model = LinearRegression()
11 
12# 3. Fit Model
13model.fit(X, y)
14 
15# 4. Predict
16X_new = np.array([[5], [10]])
17predictions = model.predict(X_new)
18 
19print(f"Predictions for 5 and 10: {predictions}")
20print(f"Coefficient (Slope): {model.coef_[0]}")
21print(f"Intercept: {model.intercept_}")
22 

The Machine Learning Workflow

A real-world project involves more than just fitting a model. It requires rigorous evaluation.

Train/Test Splitting

We must never evaluate a model on the same data it was trained on. Scikit-Learn provides train_test_split to handle this.

python
1 
2from sklearn.model_selection import train_test_split
3from sklearn.datasets import load_iris
4 
5# Load sample data
6iris = load_iris()
7X, y = iris.data, iris.target
8 
9# Split into 80% training, 20% testing
10X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
11 
12print(f"Training set size: {X_train.shape[0]}")
13print(f"Testing set size: {X_test.shape[0]}")
14 

Preprocessing: Scaling and Encoding

Machine learning models are sensitive to the scale of features. For example, a model might give more weight to a feature ranging from 0 to 1000 than to one ranging from 0 to 1.

python
1 
2from sklearn.preprocessing import StandardScaler
3import numpy as np
4 
5data = np.array([[10, 0.001], [20, 0.002], [30, 0.003]])
6scaler = StandardScaler()
7 
8scaled_data = scaler.fit_transform(data)
9print("Original Data:\n", data)
10print("\nScaled Data (mean=0, std=1):\n", scaled_data)
11 

Evaluation Metrics

How do we know if our model is any good? Scikit-Learn offers a suite of metrics.

  • For Regression: Mean Squared Error (MSE), R-squared.
  • For Classification: Accuracy, Precision, Recall, F1-Score.
python
1 
2from sklearn.metrics import accuracy_score
3 
4# Simulated ground truth and predictions
5y_true = [0, 1, 2, 0, 1]
6y_pred = [0, 2, 1, 0, 1]
7 
8acc = accuracy_score(y_true, y_pred)
9print(f"Model Accuracy: {acc * 100:.1f}%")
10 

In the next module, we will explore supervised learning models like Decision Trees and Random Forests in much greater detail.