PDS Spring 2026 - ITU
Intended Learning Outcomes (ILOs)
You should be able to:
2019-2022 - B.Sc. in Business Informatics
DHBW, Germany
2022-2023 - Software Developer
ECOVIS RTS, Germany
2022-2024 - Full-Stack Engineer
Outreach360, Remote
2023-2025 - M.Sc. in Data Science
ITU, Denmark
2025-2026 - Research Assistant
PURRlab, ITU, Denmark
2026-Now - PhD Student
PURRlab, ITU, Denmark

Features: weight, size, freshness, season
Task: Predict the price of a fish based on its features.
Features: job satisfaction, salary, commute time
Task: Predict if a person should stay in their job or not.
How expensive is a fish that weighs 4.5 kg?
We seek a simple formula that captures the relationship between weight and price.
Plot.plot({
width: 460,
height: 360,
marginTop: 30,
marginBottom: 40,
style: { fontSize: "13px", background: "transparent" },
grid: true,
marks: [
Plot.ruleX([0]),
Plot.ruleY([0]),
Plot.dot(fish_data, {x: "weight", y: "price", fill: "#377eb8", r: 5}),
],
x: { label: "Weight (kg)", domain: [0, 7] },
y: { label: "Price (€)", domain: [0, 60] }
})Hypothesis (prediction) function
\[ h_{\theta}(x) = \theta_0 + \theta_1 x \]
School / Math Notation
\[ y = mx + b \]
Multiple Linear Regression Model (m features)
\[ h_{\theta}(x^{(i)}) = \theta_0 + \theta_1 x^{(i)}_1 + \theta_2 x^{(i)}_2 + \cdots + \theta_m x^{(i)}_m \]
Plot.plot({
width: 460,
height: 230,
marginTop: 30,
marginBottom: 40,
style: { fontSize: "13px", background: "transparent" },
grid: true,
marks: [
Plot.ruleX([0]),
Plot.ruleY([0]),
Plot.line(
[{weight: 0, price: 10}, {weight: 7, price: 45}],
{x: "weight", y: "price", stroke: "#EE7733", strokeWidth: 2}
),
Plot.line(
[{weight: 0, price: 0}, {weight: 7, price: 55}],
{x: "weight", y: "price", stroke: "#009988", strokeWidth: 2}
),
Plot.dot(fish_data, {x: "weight", y: "price", fill: "#377eb8", r: 5}),
Plot.text(
[{weight: 7, price: 55, label: "A"}],
{x: "weight", y: "price", text: "label", fill: "#009988", fontWeight: "bold", dy: -8}
),
Plot.text(
[{weight: 7, price: 45, label: "B"}],
{x: "weight", y: "price", text: "label", fill: "#EE7733", fontWeight: "bold", dy: -8}
),
],
x: { label: "Weight (kg)", domain: [0, 7] },
y: { label: "Price (€)", domain: [0, 60] }
})The error (residual) for each point is the difference between the predicted value and the actual value (predicted price - actual price):
Error (Residual)
\[ e^{(i)} = h_\theta(x^{(i)}) - y^{(i)} \]
Plot.plot({
width: 460,
height: 360,
marginTop: 30,
marginBottom: 40,
style: { fontSize: "13px", background: "transparent" },
grid: true,
marks: [
Plot.ruleX([0]),
Plot.ruleY([0]),
// Regression line
Plot.line(
[{weight: 0, price: 10}, {weight: 7, price: 10 + 5 * 7}],
{x: "weight", y: "price", stroke: "#ff7f00", strokeWidth: 2}
),
// Residual lines (observed -> predicted)
...fish_data.map(d => {
const predicted = 10 + 5 * d.weight;
return Plot.line(
[{x: d.weight, y: d.price}, {x: d.weight, y: predicted}],
{x: "x", y: "y", stroke: "#808080", strokeWidth: 1.5, strokeDasharray: "4 2", strokeOpacity: 0.6}
);
}),
// Data points
Plot.dot(fish_data, {x: "weight", y: "price", fill: "#377eb8", r: 5}),
// Predicted points on the line
Plot.dot(fish_data.map(d => ({weight: d.weight, price: 10 + 5 * d.weight})),
{x: "weight", y: "price", fill: "#808080", r: 3, symbol: "diamond"}
),
],
x: { label: "Weight (kg)", domain: [0, 7] },
y: { label: "Price (€)", domain: [0, 60] }
})Mean Squared Error (MSE)
\[\text{MSE} = \frac{1}{n} \sum_{i=1}^{n} e^{(i)2}\]
Mean Absolute Error (MAE)
\[\text{MAE} = \frac{1}{n} \sum_{i=1}^{n} |e^{(i)}|\]
function calculateMSE(fish_data, intercept, slope) {
const mse = fish_data.reduce((sum, d) => {
const predictedPrice = intercept + slope * d.weight;
const error = d.price - predictedPrice;
return sum + error * error; // Squared error
}, 0) / fish_data.length; // Divide by number of data points
return mse;
}
function calculateMAE(fish_data, intercept, slope) {
const mae = fish_data.reduce((sum, d) => {
const predictedPrice = intercept + slope * d.weight;
const error = Math.abs(d.price - predictedPrice);
return sum + error; // Absolute error
}, 0) / fish_data.length; // Divide by number of data points
return mae;
}
// Output the MSE value
function displayMSE(fish_data, intercept, slope) {
const mse = calculateMSE(fish_data, intercept, slope);
const mae = calculateMAE(fish_data, intercept, slope);
return html`
<div>
<strong>Mean Squared Error (MSE):</strong> ${mse.toFixed(2)}
<br>
<strong>Mean Absolute Error (MAE):</strong> ${mae.toFixed(2)}
</div>
`;
}
displayMSE(fish_data, intercept, slope)function plotRegression(fish_data, intercept, slope) {
// Regression line endpoints (spans full x-axis)
const minWeight = 0;
const maxWeight = Math.max(...fish_data.map(d => d.weight));
const regressionLine = [
{ weight: minWeight, price: intercept + slope * minWeight },
{ weight: 7, price: intercept + slope * 7 }
];
// Predicted points for actual data (diamonds)
const predictedPoints = fish_data.map(d => ({
weight: d.weight,
price: intercept + slope * d.weight
}));
// Residuals: vertical lines from actual -> predicted
const residuals = fish_data.map(d => [
{ x: d.weight, y: d.price },
{ x: d.weight, y: intercept + slope * d.weight }
]);
return Plot.plot({
width: 460,
height: 360,
marginTop: 30,
marginBottom: 40,
style: { fontSize: "13px", background: "transparent" },
grid: true,
marks: [
Plot.ruleX([0]),
Plot.ruleY([0]),
// Regression line (orange)
Plot.line(regressionLine, {
x: "weight",
y: "price",
stroke: "#ff7f00",
strokeWidth: 2
}),
// Residual lines (gray, dashed)
...residuals.map(line =>
Plot.line(line, {
x: "x",
y: "y",
stroke: "#808080",
strokeWidth: 1.5,
strokeDasharray: "4 2",
strokeOpacity: 0.6
})
),
// Data points (blue)
Plot.dot(fish_data, { x: "weight", y: "price", fill: "#377eb8", r: 5 }),
// Predicted points on regression line (gray diamonds)
Plot.dot(predictedPoints, {
x: "weight",
y: "price",
fill: "#808080",
r: 3,
symbol: "diamond"
})
],
x: { label: "Weight (kg)", domain: [0, 7] },
y: { label: "Price (€)", domain: [0, 60] }
});
}
plotRegression(fish_data, intercept, slope);Check out MLU-EXPLAIN for more:

We can evaluate how good a line fits the data but how do we find the best parameters \(\theta\)?
Imagine you’re standing on a hill in thick fog. You can’t see the valley below, but you can feel the slope under your feet. Take a small step in the direction of steepest descent, feel the new slope, and repeat.
Terminology
Gradient Descent Algorithm
Start with random parameters \(\theta = [\theta_0, \theta_1, \dots, \theta_m]\)
Define a cost function \(J(\theta)\)
Compute the gradient (the direction of steepest ascent)
\[
\nabla J(\theta) = \left[ \frac{\partial J}{\partial \theta_0}, \frac{\partial J}{\partial \theta_1}, \dots, \frac{\partial J}{\partial \theta_m} \right]
\]
Update parameters in the direction of steepest descent \[ \theta_m := \theta_m - \alpha \frac{\partial J}{\partial \theta_m} \]
Repeat steps 3 and 4 until convergence (gradient close to zero)
Least squares method
Choose the parameters \(\theta\) that minimize the sum of squared errors:
\[ J(\theta) = \sum_{i=1}^{n} (h_\theta(x^{(i)}) - y^{(i)})^2 \]
Questions:
{
// Loss function: f(x) = (x - 3)^2 + 1 (minimum at x=3, f=1)
const curve = Array.from({length: 200}, (_, i) => {
const x = -2 + i * 0.05;
return {x, y: (x - 3) * (x - 3) + 1};
});
// Gradient descent path
const path = [];
let x = gd_start;
for (let i = 0; i < gd_steps; i++) {
const y = (x - 3) * (x - 3) + 1;
path.push({x, y, step: i});
const grad = 2 * (x - 3);
x = x - gd_lr * grad;
if (x < -2 || x > 8) break;
}
// Add final position
path.push({x, y: (x - 3) * (x - 3) + 1, step: path.length});
return Plot.plot({
width: 480,
height: 380,
marginTop: 30,
marginBottom: 40,
style: { fontSize: "13px", background: "transparent" },
grid: true,
marks: [
Plot.line(curve, {x: "x", y: "y", stroke: "#aaa", strokeWidth: 2}),
Plot.line(path, {x: "x", y: "y", stroke: "#e63946", strokeWidth: 1.5, strokeDasharray: "4 2"}),
Plot.dot(path.slice(0, -1), {x: "x", y: "y", fill: "#e63946", r: 4}),
Plot.dot(path.slice(-1), {x: "x", y: "y", fill: "#2a9d8f", r: 6, stroke: "#2a9d8f", strokeWidth: 2}),
Plot.dot([{x: 3, y: 1}], {x: "x", y: "y", fill: "none", stroke: "#aaa", r: 8, strokeWidth: 1.5, strokeDasharray: "3 3"}),
],
x: { label: "θ", domain: [-2, 8] },
y: { label: "J(θ)", domain: [0, 30] }
});
}Example: Gradient Descent Algorithm (1 iteration)
Data (weight, price):
\[ (0.5, 8), (1.0, 10), (1.5, 22), (2.0, 24), (2.5, 28), \] \[ (3.0, 30), (3.5, 38), (4.0, 25), (5.0, 45), (6.0, 57) \]
Predictions: \(h_\theta(x^{(i)}) = \theta_0 + \theta_1 x^{(i)}_1 = 20 + 0 \, x^{(i)}_1\)
Define the cost function (Mean Squared Error): \[ J(\theta_0, \theta_1) = \frac{1}{n} \sum_{i=1}^{n} (h_\theta(x^{(i)}) - y^{(i)})^2 \]
Compute the gradients (using the chain rule)
\[ \frac{\partial J}{\partial \theta_0} = \frac{2}{n} \sum_{i=1}^{n} (h_\theta(x^{(i)}) - y^{(i)}) \cdot \frac{\partial h_\theta(x^{(i)})}{\partial \theta_0} = \frac{2}{n} \sum_{i=1}^{n} (h_\theta(x^{(i)}) - y^{(i)}) \cdot 1 = -17,4 \]
\[ \frac{\partial J}{\partial \theta_1} = \frac{2}{n} \sum_{i=1}^{n} (h_\theta(x^{(i)}) - y^{(i)}) \cdot \frac{\partial h_\theta(x^{(i)})}{\partial \theta_1} = \frac{2}{n} \sum_{i=1}^{n} (h_\theta(x^{(i)}) - y^{(i)}) \cdot x^{(i)}_1 = -95 \]
Plot.plot({
width: 460,
height: 330,
marginTop: 30,
marginBottom: 40,
style: { fontSize: "13px", background: "transparent" },
grid: true,
marks: [
Plot.ruleX([0]),
Plot.ruleY([0]),
Plot.line(
[{weight: 0, price: 20}, {weight: 7, price: 20}],
{x: "weight", y: "price", stroke: "#EE7733", strokeWidth: 2}
),
Plot.line(
[{weight: 0, price: 20.174}, {weight: 7, price: 20.174 + 7*0.95}],
{x: "weight", y: "price", stroke: "#009988", strokeWidth: 2}
),
Plot.dot(fish_data, {x: "weight", y: "price", fill: "#377eb8", r: 5}),
Plot.text(
[{weight: 6, price: 13, label: "Initial"}],
{x: "weight", y: "price", text: "label", fill: "#EE7733", fontWeight: "bold", dy: -8}
),
Plot.text(
[{weight: 6, price: 20.174 + 7*0.95, label: "After 1 step"}],
{x: "weight", y: "price", text: "label", fill: "#009988", fontWeight: "bold", dy: -8}
),
],
x: { label: "Weight (kg)", domain: [0, 7] },
y: { label: "Price (€)", domain: [0, 60] }
})Using least squares allows us to compute the optimal parameters \(\theta\) directly without iteration.
Closed-form solution
1. Define the data and parameters (Matrix notation)
\[ X = \begin{pmatrix} 1 & x_1^{(1)} & x_2^{(1)} & \dots & x_m^{(1)} \\ 1 & x_1^{(2)} & x_2^{(2)} & \dots & x_m^{(2)} \\ \vdots & \vdots & \vdots & & \vdots \\ 1 & x_1^{(n)} & x_2^{(n)} & \dots & x_m^{(n)} \end{pmatrix}_{n \times (m+1)}, \quad \theta = \begin{pmatrix} \theta_0 \\ \theta_1 \\ \vdots \\ \theta_m \end{pmatrix}_{(m+1) \times 1}, \quad y = \begin{pmatrix} y_1 \\ y_2 \\ \vdots \\ y_n \end{pmatrix}_{n \times 1} \]
The prediction for all points can be written in vector form:
\[ h_\theta(X) = X \theta \quad \text{remember for one point: } h_\theta(x^{(i)}) = \theta_0 + \theta_1 x_1^{(i)} + \cdots + \theta_m x_m^{(i)}\text{)} \]
2. Define the cost function in matrix form
\[ J(\theta) = \sum_{i=1}^{n} (h_\theta(x^{(i)}) - y^{(i)})^2 = \| X \theta - y \|_2^2 = (X\theta - y)^\top (X\theta - y) \]
3. Closed-form solution
Set the gradient of the cost function to zero and solve for \(\theta\):
\[ \theta = (X^\top X)^{-1} X^\top y \]
\[\text{$(X^\top X)$ must be invertible (features are linearly independent)}\]
Equivalent idea for a single parameter (e.g., \(\theta_1\)): \(\frac{2}{n} \sum_{i=1}^{n} (h_\theta(x^{(i)}) - y^{(i)}) \cdot x^{(i)}_1 = 0\)
This gives the exact solution for linear regression without iteration.
# import libraries
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, mean_absolute_error
# define input data (e.g., weight and length of fish) and labels (price)
X = np.array([[1.0, 20], [1.5, 24], [2.0, 28], [2.5, 30]]) # input features (weight, length)
y = np.array([8, 10, 22, 24]) # target variable (price)
# fit linear regression model
reg_model = LinearRegression().fit(X, y)
# evaluation
y_pred = reg_model.predict(X)
mse = mean_squared_error(y, y_pred)
mae = mean_absolute_error(y, y_pred)
# coefficients (weights) and intercept (bias)
print("Coefficients: \n", reg_model.coef_)
print("Intercept: \n", reg_model.intercept_)
# new predictions
new_X = np.array([[3.0, 33]])
new_y_pred = reg_model.predict(new_X)
print(f"New predictions: {new_y_pred}")Predict a continuous target variable (e.g., price) based on one or more input features (e.g., weight, length).
\[ h_{\theta}(x^{(i)}) = \theta_0 + \theta_1 x^{(i)}_1 + \theta_2 x^{(i)}_2 + \cdots + \theta_m x^{(i)}_m \]
Least squares method: minimize the sum of squared errors between predictions and true values.
\[ J(\theta) = \sum_{i=1}^{n} (h_\theta(x^{(i)}) - y^{(i)})^2 \]
Predict whether a patient is sick based on their body temperature.
We are no longer trying to predict a continuous number (like price), but a binary category: sick (1) or healthy (0).
Plot.plot({
width: 460,
height: 300,
marginTop: 30,
marginBottom: 40,
style: { fontSize: "13px", background: "transparent" },
grid: true,
marks: [
Plot.ruleX([35.5]),
Plot.ruleY([0]),
Plot.dot(sick_data, {
x: "temp",
y: "sick",
fill: d => d.sick === 1 ? "#e63946" : "#2a9d8f",
r: 6
}),
Plot.ruleY([0.5], {stroke: "#aaa", strokeDasharray: "4 2", strokeWidth: 1}),
],
x: { label: "Body Temperature (°C)", domain: [35.5, 41] },
y: { label: "Sick (0 = no, 1 = yes)", domain: [-0.1, 1.1] }
})Sigmoid function (logistic function)
\[ \sigma(z) = \frac{1}{1 + e^{-z}} \]
{
// Sigmoid curve fitted to sick_data (approx: boundary ≈ 37.8, steepness ≈ 3)
const s_b0 = -3 * 37.8;
const s_b1 = 3;
const curve = Array.from({length: 200}, (_, i) => {
const x = 35.5 + i * (5.5 / 200);
const z = s_b0 + s_b1 * x;
const p = 1 / (1 + Math.exp(-z));
return {temp: x, prob: p};
});
return Plot.plot({
width: 460,
height: 300,
marginTop: 30,
marginBottom: 40,
style: { fontSize: "13px", background: "transparent" },
grid: true,
marks: [
Plot.ruleX([35.5]),
Plot.ruleY([0]),
// Sigmoid curve
Plot.line(curve, {x: "temp", y: "prob", stroke: "#e63946", strokeWidth: 2.5}),
// Decision boundary at p = 0.5
Plot.ruleY([0.5], {stroke: "#aaa", strokeDasharray: "4 2", strokeWidth: 1}),
// Data points
Plot.dot(sick_data, {
x: "temp",
y: "sick",
fill: d => d.sick === 1 ? "#e63946" : "#2a9d8f",
r: 6
}),
],
x: { label: "Body Temperature (°C)", domain: [35.5, 41] },
y: { label: "P(Sick)", domain: [-0.1, 1.1] }
});
}Hypothesis (prediction) function
In logistic regression, we apply the sigmoid function to a linear combination of inputs:
\[ h_{\theta}(x^{(i)}) = \sigma(z) = \frac{1}{1 + e^{-z}}, \quad z = \theta_0 + \theta_1 x^{(i)}_1 \]
Logistic Regression Model (m features)
\[ h_{\theta}(x^{(i)}) = \sigma(\theta_0 + \theta_1 x^{(i)}_1 + \cdots + \theta_m x^{(i)}_m) \]
See lecture about classification, evaluation.

Accuracy: 85%, AUC: 0.55

Accuracy: 59%, AUC: 0.72
{
const xMin = 35.5;
const xMax = 41;
const n = 300;
// Numerically stable sigmoid
const sigmoid = z => {
if (z >= 0) return 1 / (1 + Math.exp(-z));
const ez = Math.exp(z);
return ez / (1 + ez);
};
// Midpoint form: p(x) = σ(k * (x - boundary))
const curve = Array.from({length: n}, (_, i) => {
const x = xMin + i * ((xMax - xMin) / (n - 1));
const z = steepness * (x - boundary);
return { temp: x, prob: sigmoid(z) };
});
const threshold_x = boundary;
return Plot.plot({
width: 480,
height: 380,
marginTop: 30,
marginBottom: 40,
style: { fontSize: "13px", background: "transparent" },
grid: true,
marks: [
Plot.line(curve, {x: "temp", y: "prob", stroke: "#e63946", strokeWidth: 2}),
Plot.dot(sick_data, {
x: "temp",
y: "sick",
fill: d => d.sick === 1 ? "#e63946" : "#2a9d8f",
r: 6
}),
Plot.ruleY([0.5], {stroke: "#aaa", strokeDasharray: "4 2", strokeWidth: 1}),
Plot.ruleX([threshold_x], {stroke: "#aaa", strokeDasharray: "4 2", strokeWidth: 1})
],
x: { label: "Body Temperature (°C)", domain: [xMin, xMax] },
y: { label: "P(Sick)", domain: [-0.05, 1.05] }
});
}Check out MLU-EXPLAIN for more:
log_slope = steepness
log_intercept = -steepness * boundary
sigmoid = z => {
if (z >= 0) return 1 / (1 + Math.exp(-z));
const ez = Math.exp(z);
return ez / (1 + ez);
};
log_loss = {
const eps = 1e-12;
return sick_data.reduce((sum, d) => {
const z = steepness * (d.temp - boundary);
const p = Math.max(eps, Math.min(1 - eps, sigmoid(z)));
return sum - (d.sick * Math.log(p) + (1 - d.sick) * Math.log(1 - p));
}, 0) / sick_data.length;
}
accuracy = {
let correct = 0;
for (const d of sick_data) {
const z = steepness * (d.temp - boundary);
const p = sigmoid(z);
const predicted = p >= 0.5 ? 1 : 0;
if (predicted === d.sick) correct++;
}
return correct / sick_data.length;
}
html`
<div class="fit-panel" style="
border: 1px solid #e5e7eb;
border-radius: 12px;
padding: 12px 14px;
background: #ffffffcc;
box-shadow: 0 2px 10px #00000010;
">
<div style="font-size: 12px; color: #6b7280; margin-bottom: 6px;">Model</div>
<div class="equation-display" style="font-size: 1.5rem; margin-bottom: 10px;">
${tex`h_\theta(x^{(i)})=\frac{1}{1+e^{-(${log_intercept.toFixed(1)}+${log_slope.toFixed(2)}x^{(i)})}}`}
</div>
<div style="display:flex; align-items:center; justify-content:space-between;">
<span style="
font-size: 12px;
color: #374151;
background: #f3f4f6;
padding: 3px 8px;
border-radius: 999px;
">Log loss</span>
<strong style="font-size: 1rem; color: #111827;">${log_loss.toFixed(3)}</strong>
</div>
</div>
`Logistic regression in log-odds space
Let’s transform the axis of probabilities to log-odds. \[ \text{logit}(p) = \log\!\left(\frac{p}{1-p}\right) \]
The raw data is being pushed to ±∞ in log-odds space which is why we can’t use least squares to find the best parameters. Instead, we use maximum likelihood estimation (MLE) to find the parameters that make the data most probable.
MLE for logistic regression
1. Model log-odds as a linear function
\[ \text{logit}(p) = \theta_0 + \theta_1 x \]
2. Convert to probability using the sigmoid function
\[ h_\theta(x^{(i)}) = \sigma(\theta_0 + \theta_1 x^{(i)}) = \frac{1}{1 + e^{-(\theta_0 + \theta_1 x^{(i)})}} \]
3. Calculate likelihood
\[ L(\theta) = \prod_{i=1}^{n} h_\theta(x^{(i)})^{y^{(i)}} (1 - h_\theta(x^{(i)}))^{1 - y^{(i)}} \]
Or equivalently, the log-likelihood (turns products into sums):
\[ \log L(\theta) = \sum_{i=1}^{n} \bigl[y^{(i)} \log h_\theta(x^{(i)}) + (1 - y^{(i)}) \log(1 - h_\theta(x^{(i)}))\bigr] \]
4. Adjust parameters with the goal of maximizing likelihood
{
// Sigmoid curve fitted to sick_data (approx: boundary ≈ 37.8, steepness ≈ 3)
const s_b0 = -3 * 37.8;
const s_b1 = 3;
const curve = Array.from({length: 200}, (_, i) => {
const x = 35.5 + i * (5.5 / 200);
const z = s_b0 + s_b1 * x;
const p = 1 / (1 + Math.exp(-z));
return {temp: x, prob: p};
});
return Plot.plot({
width: 460,
height: 280,
marginTop: 30,
marginBottom: 40,
style: { fontSize: "13px", background: "transparent" },
grid: true,
marks: [
Plot.ruleX([35.5]),
Plot.ruleY([0]),
// Sigmoid curve
Plot.line(curve, {x: "temp", y: "prob", stroke: "#e63946", strokeWidth: 2.5}),
// Decision boundary at p = 0.5
Plot.ruleY([0.5], {stroke: "#aaa", strokeDasharray: "4 2", strokeWidth: 1}),
// Data points
Plot.dot(sick_data, {
x: "temp",
y: "sick",
fill: d => d.sick === 1 ? "#e63946" : "#2a9d8f",
r: 6
}),
],
x: { label: "Body Temperature (°C)", domain: [35.5, 41] },
y: { label: "P(Sick)", domain: [-0.1, 1.1] }
});
}{
// Sigmoid parameters
const s_b0 = -3 * 37.8;
const s_b1 = 3;
// Linear line in log-odds space
const line_logodds = Array.from({length: 200}, (_, i) => {
const x = 35.5 + i * (5.5 / 200);
const log_odds = s_b0 + s_b1 * x;
return {temp: x, log_odds: log_odds};
});
// Clamp data points to domain edges to represent ±∞
const transformed_data = sick_data.map(d => ({
temp: d.temp,
log_odds: d.sick === 1 ? 10 : -10,
log_odds_proj: s_b0 + s_b1 * d.temp,
sick: d.sick
}));
return Plot.plot({
width: 460,
height: 280,
marginTop: 30,
marginBottom: 40,
style: { fontSize: "13px", background: "transparent" },
grid: true,
marks: [
Plot.ruleY([0]),
// Log-odds line (finite)
Plot.line(line_logodds, {x: "temp", y: "log_odds", stroke: "#e63946", strokeWidth: 2.5}),
// Dashed projection lines from true points to line
Plot.link(transformed_data, {
x1: "temp", y1: "log_odds",
x2: "temp", y2: "log_odds_proj",
stroke: d => d.sick === 1 ? "#e63946" : "#2a9d8f",
strokeDasharray: "4 2",
strokeOpacity: 0.6
}),
// Diamond markers where projections land on the line
Plot.dot(transformed_data, {
x: "temp",
y: "log_odds_proj",
fill: d => d.sick === 1 ? "#e63946" : "#2a9d8f",
symbol: "diamond",
r: 5
}),
// Data points at ±∞ edges
Plot.dot(transformed_data, {
x: "temp",
y: "log_odds",
fill: d => d.sick === 1 ? "#e63946" : "#2a9d8f",
r: 6,
opacity: 0.8
}),
// Decision boundary at log-odds = 0
Plot.ruleY([0], {stroke: "#aaa", strokeDasharray: "4 2", strokeWidth: 1})
],
x: { label: "Body Temperature (°C)", domain: [35.5, 41] },
y: { label: "Log-Odds of Being Sick", domain: [-10, 10], tickFormat: d => d === 10 ? "+∞" : d === -10 ? "-∞" : d }
});
}Example: Gradient Descent Algorithm (1 iteration)
Data (temperature, sick):
\[(36.0, 0), (36.3, 0), (36.5, 0), (36.8, 0), (37.0, 0), (37.2, 0), (37.5, 1),
\]
\[ (37.8, 0), (38.0, 1), (38.3, 1), (38.7, 1), (39.0, 1), (39.5, 1), (40.0, 1) \]
1. Start with random parameters: \(\theta_0 = -115, \theta_1 = 3\)
\[ \text{Predictions: } h_\theta(x^{(i)}) = \sigma(\theta_0 + \theta_1 x^{(i)}) = \frac{1}{1 + e^{-(\theta_0 + \theta_1 x^{(i)})}} \]
2. Cost Function (Log Loss / Cross-Entropy Loss)
We want to minimize the negative log-likelihood, which is equivalent to maximizing the log-likelihood:
\[ J(\theta) = - \frac{1}{n}\sum_{i=1}^{n} \left[ y_i \log(h_\theta(x^{(i)})) + (1 - y_i)\log(1 - h_\theta(x^{(i)})) \right] \]
3. Compute the gradients
\[ \frac{\partial J(\theta)}{\partial \theta_0} = \frac{1}{n}\sum_{i=1}^{n} (h_\theta(x^{(i)}) - y^{(i)}) = \frac{1}{n}\sum_{i=1}^{n} (\frac{1}{1 + e^{-(\theta_0 + \theta_1 x^{(i)})}} - y^{(i)}) = - 0.168 \]
\[ \frac{\partial J(\theta)}{\partial \theta_1} = \frac{1}{n}\sum_{i=1}^{n} (h_\theta(x^{(i)}) - y^{(i)}) \cdot x^{(i)} = \frac{1}{n}\sum_{i=1}^{n} (\frac{1}{1 + e^{-(\theta_0 + \theta_1 x^{(i)})}} - y^{(i)}) \cdot x^{(i)} = -6.388 \]
4. Update Parameters (Learning Rate \(\alpha = 0.01\))
\[ \theta_0 := \theta_0 - \alpha \cdot \frac{\partial J(\theta)}{\partial \theta_0} = -114.998 \quad \theta_1 := \theta_1 - \alpha \cdot \frac{\partial J(\theta)}{\partial \theta_1} = 3.06388 \]
{
const theta0_init = -115;
const theta1_init = 3.0;
const theta0_new = -114.998;
const theta1_new = 3.06388;
function sigmoid(z) {
return 1 / (1 + Math.exp(-z));
}
function makeCurve(theta0, theta1) {
return Array.from({length: 200}, (_, i) => {
const x = 35.5 + i * (5.5 / 200);
const z = theta0 + theta1 * x;
return {temp: x, prob: sigmoid(z)};
});
}
const curve_init = makeCurve(theta0_init, theta1_init);
const curve_new = makeCurve(theta0_new, theta1_new);
return Plot.plot({
width: 460,
height: 330,
marginTop: 30,
marginBottom: 40,
style: { fontSize: "13px", background: "transparent" },
grid: true,
marks: [
Plot.ruleY([0]),
Plot.ruleY([0.5], {stroke: "#aaa", strokeDasharray: "4 2"}),
Plot.line(curve_init, {
x: "temp",
y: "prob",
stroke: "#EE7733",
strokeWidth: 2.5
}),
Plot.line(curve_new, {
x: "temp",
y: "prob",
stroke: "#009988",
strokeWidth: 2.5
}),
Plot.dot(sick_data, {
x: "temp",
y: "sick",
fill: d => d.sick === 1 ? "#e63946" : "#2a9d8f",
r: 6
}),
Plot.text(
[{temp: 38.5, prob: 0.2, label: "Initial"}],
{x: "temp", y: "prob", text: "label", fill: "#EE7733", fontWeight: "bold"}
),
Plot.text(
[{temp: 37.0, prob: 0.8, label: "After 1 step"}],
{x: "temp", y: "prob", text: "label", fill: "#009988", fontWeight: "bold"}
)
],
x: { label: "Body Temperature (°C)", domain: [35.5, 41] },
y: { label: "P(Sick)", domain: [-0.1, 1.1] }
});
}In cases of imbalanced datasets, we can assign different weights to classes to help the model focus more on the minority class.
Bring all features to the same scale as different scales can affect the convergence of the optimization algorithm used.
Note: Apply feature scaling after creating the train, validation, and test sets to avoid data leakage.
Scikit-learn supports different optimization algorithms (solvers) for fitting a model.
# import libraries
import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score, accuracy_score
# define input data
X = np.array([[36.0], [36.3], [36.5], [36.8], [37.0], [37.2],
[37.5], [37.8], [38.0], [38.3], [38.7], [39.0], [39.5], [40.0]])
y = np.array([0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1])
# fit logistic regression model
model = LogisticRegression(random_state=42, class_weight='balanced').fit(X, y)
# evaluation
y_pred = model.predict(X)
y_prob = model.predict_proba(X)[:, 1] # probability of class 1 (sick)
acc = accuracy_score(y, y_pred)
auc = roc_auc_score(y, y_prob)
# coefficients (weights) and intercept (bias)
print("Intercept: \n", model.intercept_)
print("Coefficients: \n", model.coef_)
# new predictions
new_X = np.array([[41.0]])
new_y_pred = model.predict(new_X)
print("New predictions: \n", new_y_pred)Predict the probability of a binary outcome
(e.g. sick = 1, healthy = 0).
\[ h_{\theta}(x^{(i)}) = \frac{1}{1 + e^{-(\theta_0 + \theta_1 x_1^{(i)} + \cdots + \theta_m x_m^{(i)})}} \]
Convert probability into a class using a threshold: \[ label^{(i)} = \begin{cases} 1 & \text{if } h_\theta(x^{(i)}) \ge 0.5 \\ 0 & \text{otherwise} \end{cases} \]
Fit parameters by minimizing the negative log-likelihood: \[ J(\theta) = - \frac{1}{n}\sum_{i=1}^{n} \left[ y^{(i)} \log(h_\theta(x^{(i)})) + (1 - y^{(i)})\log(1 - h_\theta(x^{(i)})) \right] \]

Reference: https://arxiv.org/abs/2504.11415
