<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[The Hybrid Mind]]></title><description><![CDATA[The Hybrid Mind: Farhana Kabir's blog on applied AI, from machine learning and knowledge graphs to LLMs and AI business value, with hands-on Python.]]></description><link>https://fkabir.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Fri, 04 Dec 2026 22:34:18 GMT</lastBuildDate><atom:link href="https://fkabir.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[RapidMiner: An Easy Alternative to Coding in Python]]></title><description><![CDATA[How I built, tuned and compared seven machine learning models in RapidMiner without code, and what it taught me about clean, leak-free ML pipelines.]]></description><link>https://fkabir.hashnode.dev/rapidminer-an-easy-alternative-to-coding-in-python</link><guid isPermaLink="true">https://fkabir.hashnode.dev/rapidminer-an-easy-alternative-to-coding-in-python</guid><category><![CDATA[rapidminer]]></category><category><![CDATA[Machine Learning]]></category><category><![CDATA[AI]]></category><category><![CDATA[pattern recognition]]></category><category><![CDATA[Python]]></category><dc:creator><![CDATA[Farhana Kabir]]></dc:creator><pubDate>Wed, 02 Dec 2026 23:07:08 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6b0f76a874eff5c1bf91b426/859b5b48-baff-41ba-b718-a8b2b0d34772.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><strong>Key takeaways</strong></p>
<ul>
<li>RapidMiner builds a model as a <strong>process</strong>: operators connected by ports, where data flows from left to right, just like a scikit-learn pipeline drawn as boxes.</li>
<li>The most important design question is <strong>where each step sits</strong>. Preprocessing such as Normalize must sit <em>inside</em> cross-validation, so the test folds never influence training.</li>
<li>One process can train and compare many models fairly, using the same data, the same folds and the same random seed.</li>
</ul>
<hr />
<h2>1. Processes, operators and ports</h2>
<p>A RapidMiner process is a chain of <strong>operators</strong>. Each operator does one job and has input and output ports. Some operators, such as Cross Validation, contain <strong>subprocesses</strong> (for example a training side and a testing side). In our group project we grouped the preparation steps into one subprocess so the main process stayed readable.</p>
<p>The basic flow of our heart-disease project:</p>
<pre><code class="language-text">Retrieve data → Prepare (missing values, label, encoding) → Multiply
   → [Cross Validation: train model | Apply Model → Performance]  × 7 models
</code></pre>
<h2>2. Preparing the data</h2>
<table>
<thead>
<tr>
<th>Operator</th>
<th>What it does</th>
<th>How we used it</th>
</tr>
</thead>
<tbody><tr>
<td><strong>Retrieve</strong></td>
<td>Loads a dataset from the repository</td>
<td>The Cleveland heart disease data</td>
</tr>
<tr>
<td><strong>Declare Missing Value</strong></td>
<td>Marks a placeholder (such as "?") as missing</td>
<td>Missing values in <code>ca</code> and <code>thal</code></td>
</tr>
<tr>
<td><strong>Filter Examples</strong></td>
<td>Keeps only rows that meet a condition</td>
<td>Removed rows where <code>ca</code> or <code>thal</code> was missing (303 → 297 rows)</td>
</tr>
<tr>
<td><strong>Generate Attributes</strong></td>
<td>Creates a new column from an expression</td>
<td><code>disease = if(num &gt; 0, 1, 0)</code>: turned the 0–4 severity score into yes/no</td>
</tr>
<tr>
<td><strong>Select Attributes</strong></td>
<td>Keeps or drops columns</td>
<td>Dropped the original <code>num</code> column so the answer could not leak into the features</td>
</tr>
<tr>
<td><strong>Set Role</strong></td>
<td>Tells RapidMiner which column is the <strong>label</strong> (target)</td>
<td><code>disease</code> as label</td>
</tr>
<tr>
<td><strong>Numerical to Binominal</strong></td>
<td>Turns 0/1 numbers into a two-class label</td>
<td>Made <code>disease</code> a classification target</td>
</tr>
<tr>
<td><strong>Numerical to Polynominal</strong></td>
<td>Treats number codes as categories</td>
<td>Chest-pain type, slope, sex and other coded columns</td>
</tr>
<tr>
<td><strong>Remove Unused Values</strong></td>
<td>Drops category values no row uses any more</td>
<td>Removed the leftover "?" category from <code>ca</code> and <code>thal</code></td>
</tr>
<tr>
<td><strong>Nominal to Numerical</strong> (dummy coding)</td>
<td>One-hot encoding</td>
<td>The eight categorical columns became 0/1 columns</td>
</tr>
<tr>
<td><strong>Normalize</strong> (Z-transformation)</td>
<td>Scales each feature to mean 0, standard deviation 1</td>
<td>The five continuous columns (age, blood pressure, cholesterol, max heart rate, ST depression), for distance-based k-NN</td>
</tr>
</tbody></table>
<p><strong>Lesson:</strong> RapidMiner separates the <em>type</em> of a column (numerical, binominal, polynominal) from its <em>role</em> (regular attribute or label). A label needs both the right role and the right type (binominal for yes/no) before a classifier will accept it.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6b0f76a874eff5c1bf91b426/36f93d93-cc99-4839-99e5-adb1275e6b41.png" alt="" width="620" height="272" />

<h2>3. Training and evaluating</h2>
<ul>
<li><strong>Multiply</strong>: copies the prepared data so the same data can feed several models side by side.</li>
<li><strong>Cross Validation</strong> (10 folds, local random seed 1992): splits the data into 10 parts, trains on 9 and tests on 1, ten times. The fixed seed makes the folds the same for every model, so the comparison is fair and repeatable.</li>
<li><strong>Apply Model</strong>: uses a trained model (or a preprocessing model such as Normalize) on new data.</li>
<li><strong>Performance (Binominal Classification)</strong>: reports accuracy, precision, recall, F1 and the confusion matrix for a yes/no label.</li>
<li><strong>Split Data</strong>: an earlier version of our process used a simple 70/30 train–test split. We moved to cross-validation because, with under 300 patients, one split gives a noisy result.</li>
</ul>
<img src="https://cdn.hashnode.com/uploads/covers/6b0f76a874eff5c1bf91b426/54397e11-0743-4710-be8d-bdf28aebdb4c.png" alt="" width="624" height="729" />

<h2>4. Tuning: Optimize Parameters (Grid)</h2>
<p><strong>Optimize Parameters (Grid)</strong> wraps a process and tries every value in a grid. We searched k for k-NN from 1 to 21 in 10 steps, with the full cross-validation inside, so each k was judged on unseen folds.</p>
<p><strong>Normalize inside the folds.</strong> In our updated process, Normalize sits <em>inside</em> the training side of cross-validation. It learns the mean and standard deviation from the training folds only, and Apply Model reuses those values on the test fold. Normalising the whole dataset first would leak information from the test data into training.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6b0f76a874eff5c1bf91b426/d0decb9c-f13b-4db0-b1b7-0029a4399d2d.png" alt="" width="624" height="167" />

<h2>5. The models we compared</h2>
<table>
<thead>
<tr>
<th>Model</th>
<th>Settings we used</th>
</tr>
</thead>
<tbody><tr>
<td>k-NN</td>
<td>k from the grid search, weighted vote, Euclidean distance</td>
</tr>
<tr>
<td>Decision Tree</td>
<td>information gain, maximal depth 10</td>
</tr>
<tr>
<td>Logistic Regression (H2O)</td>
<td>no regularisation</td>
</tr>
<tr>
<td>Random Forest</td>
<td>20 trees, information gain, depth 15</td>
</tr>
<tr>
<td>Bagging</td>
<td>20 decision trees, each on a 70% sample</td>
</tr>
<tr>
<td>AdaBoost</td>
<td>21 boosting rounds of decision trees</td>
</tr>
<tr>
<td>Gradient Boosted Trees (H2O)</td>
<td>50 trees, depth 5, learning rate 0.01</td>
</tr>
</tbody></table>
<p><strong>What we found:</strong> Logistic Regression was the most reliable (accuracy 0.829, F1 0.811), k-NN was the weakest (0.644), and every ensemble beat a single decision tree by about 5–9 accuracy points.</p>
<p><strong>Decision-tree criteria.</strong> Information gain picks the split that reduces uncertainty the most. Gain ratio corrects it for attributes with many values, which information gain tends to favour.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6b0f76a874eff5c1bf91b426/7a42bd68-745e-4e26-9664-fbd62642e524.png" alt="" width="624" height="315" />

<h2>6. Neural networks in RapidMiner (lab)</h2>
<p>In a lab on the sonar dataset (60 readings per sample, labelled rock or mine), I built a <strong>Neural Net</strong> with 60 input neurons and 2 output classes. A <strong>Normalize</strong> operator came first, because neural networks train badly when features have very different ranges.</p>
<h2>7. RapidMiner vs Python: what I took from using both</h2>
<table>
<thead>
<tr>
<th></th>
<th>RapidMiner</th>
<th>Python (scikit-learn)</th>
</tr>
</thead>
<tbody><tr>
<td>Building</td>
<td>Drag and connect operators</td>
<td>Write code</td>
</tr>
<tr>
<td>Seeing the flow</td>
<td>The process is a picture</td>
<td>Must read the code</td>
</tr>
<tr>
<td>Avoiding leakage</td>
<td>Put Normalize inside Cross Validation</td>
<td>Put the scaler inside a Pipeline</td>
</tr>
<tr>
<td>Repeatability</td>
<td>Local random seed on each operator</td>
<td><code>random_state</code></td>
</tr>
<tr>
<td>Best for</td>
<td>Fast experiments and explaining a process to others</td>
<td>Full control, automation, production</td>
</tr>
</tbody></table>
<p>The same ideas carried over in both tools: prepare the data carefully, keep the test data unseen, fix the random seed, and compare models on the same folds. Both tools also gave the same conclusion in our project: Logistic Regression won.</p>
<hr />
<p><strong>Skills demonstrated:</strong> RapidMiner · visual ML pipelines · data preparation (missing values, label roles, dummy coding, Z-normalisation) · 10-fold cross-validation · grid search · k-NN · decision trees · logistic regression · random forest · bagging · AdaBoost · gradient boosted trees · neural networks · model evaluation (accuracy, precision, recall, F1, confusion matrix)</p>
<p><em>The Hybrid Mind: where symbolic AI meets neural networks.</em></p>
]]></content:encoded></item><item><title><![CDATA[From k-NN to Neural Networks: Six Ways Machines Learn from Data]]></title><description><![CDATA[k-NN, SVM, k-means, DBSCAN, neural networks and ensembles explained with small Python experiments that show when each method works and when it fails.]]></description><link>https://fkabir.hashnode.dev/from-k-nn-to-neural-networks-six-ways-machines-learn-from-data</link><guid isPermaLink="true">https://fkabir.hashnode.dev/from-k-nn-to-neural-networks-six-ways-machines-learn-from-data</guid><category><![CDATA[Machine Learning · Python · NumPy · scikit-learn · #k-means]]></category><category><![CDATA[Machine Learning]]></category><category><![CDATA[Python]]></category><category><![CDATA[numpy]]></category><category><![CDATA[scikit learn]]></category><category><![CDATA[KMeans]]></category><category><![CDATA[clustering]]></category><category><![CDATA[neural networks]]></category><category><![CDATA[Data Science]]></category><dc:creator><![CDATA[Farhana Kabir]]></dc:creator><pubDate>Wed, 02 Dec 2026 23:05:07 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6b0f76a874eff5c1bf91b426/c72a8217-88a1-40b2-a530-26bc5385ebe5.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><strong>Key takeaways</strong></p>
<ul>
<li>Machine learning splits into two questions: <em>with labels</em>, predict a class or a value (supervised learning); <em>without labels</em>, find the groups hidden in the data (clustering).</li>
<li>k-NN, SVM, k-means and DBSCAN all rely on <strong>distance</strong>, while neural networks <strong>learn weights</strong> by gradient descent. Knowing which idea a method uses tells you where it will work and where it will fail.</li>
<li>Every method has settings that change the result (k, C, K, Eps, network size), and every one of them can overfit. Checking on unseen data, and looking at the data itself, matters more than the name of the algorithm.</li>
</ul>
<hr />
<h2>Context: the map of machine learning</h2>
<p><em>Artificial Intelligence and Pattern Recognition</em> was one of the first courses in my master's in Applied AI. It started with a simple map that I still use:</p>
<table>
<thead>
<tr>
<th></th>
<th>Labels available?</th>
<th>Output</th>
<th>Examples</th>
</tr>
</thead>
<tbody><tr>
<td><strong>Classification</strong></td>
<td>yes</td>
<td>a discrete class</td>
<td>disease / no disease</td>
</tr>
<tr>
<td><strong>Regression</strong></td>
<td>yes</td>
<td>a continuous value</td>
<td>a price, a temperature</td>
</tr>
<tr>
<td><strong>Clustering</strong></td>
<td>no</td>
<td>groups of similar points</td>
<td>customer segments, anomalies</td>
</tr>
</tbody></table>
<p>Behind all of them is one goal: optimise an objective (a loss function). Supervised learning follows the same rhythm every time: prepare labelled data, train on part of it, then predict on test data the model has never seen.</p>
<p>The data itself also has a shape. Most examples in this post are independent points, but the course also stressed <strong>time-series data</strong>: ordered observations where the order carries meaning (sensor readings, prices), and where the values can be numbers or categories. Shuffling such data destroys exactly the information you want to learn from.</p>
<p>In this post I walk through six methods from the course: two classifiers (k-NN and SVM), two clustering methods (k-means and DBSCAN), neural networks and ensembles. For each one I ran a small experiment in Python with scikit-learn, and every output shown is real.</p>
<hr />
<h2>k-NN: learning by remembering</h2>
<p><strong>k-nearest neighbours</strong> is an <em>instance-based</em> (or <em>lazy</em>) learner (Cover &amp; Hart, 1967). It builds no model. It stores the training data, and when a new point arrives it:</p>
<ol>
<li>computes the distance to every stored point, usually the Euclidean distance <strong>d = √((x₁ − x₂)² + (y₁ − y₂)²)</strong>;</li>
<li>takes the k closest points;</li>
<li>predicts the majority class (for regression: the average of their values).</li>
</ol>
<p>The appeal is its simplicity, and new examples can be added without retraining. The cost comes at prediction time: every prediction compares the new point with all n stored points in d dimensions, so memory and time grow with the data.</p>
<p>"No training" does not mean "no choices". The value of k and the distance measure still have to be chosen, and features must be on the same scale, or the feature with the largest numbers dominates every distance. I chose k with cross-validation:</p>
<pre><code class="language-python">from sklearn.datasets import make_moons
from sklearn.model_selection import cross_val_score
from sklearn.neighbors import KNeighborsClassifier
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

X, y = make_moons(n_samples=400, noise=0.25, random_state=0)
for k in [1, 5, 15, 51, 151]:
    pipe = make_pipeline(StandardScaler(), KNeighborsClassifier(n_neighbors=k))
    print(f"k = {k:3d}: mean 5-fold accuracy {cross_val_score(pipe, X, y, cv=5).mean():.3f}")
</code></pre>
<pre><code class="language-text">k =   1: mean 5-fold accuracy 0.872
k =   5: mean 5-fold accuracy 0.895
k =  15: mean 5-fold accuracy 0.925
k =  51: mean 5-fold accuracy 0.922
k = 151: mean 5-fold accuracy 0.853
</code></pre>
<p>With k = 1 the model follows every noisy point (overfitting); with k = 151 it averages over almost half the data and blurs the boundary (underfitting). The best values sit in between.</p>
<hr />
<h2>SVM: learning a boundary with the widest margin</h2>
<p>A <strong>support vector machine</strong> works the opposite way (Cortes &amp; Vapnik, 1995). It is an <em>eager, model-based</em> classifier: training finds the boundary (a hyperplane) that separates two classes with the <strong>largest margin</strong> to the nearest points of each class. Only those nearest points, the <em>support vectors</em>, are kept. With n features, the hyperplane has n − 1 dimensions: a line in 2D, a plane in 3D.</p>
<p>Two ideas made SVMs click for me:</p>
<ul>
<li><strong>Hard vs soft margin.</strong> A hard margin demands that every point is on the correct side, so a single outlier can ruin the boundary. A soft margin allows some points inside the margin or on the wrong side, with a penalty set by the parameter C. It does not delete outliers; it just stops them from dictating the boundary.</li>
<li><strong>Kernels.</strong> When classes are not linearly separable, the data can be mapped to a higher dimension where they are. Computing those new features explicitly is expensive, so the <strong>kernel trick</strong> computes the dot product in the higher space directly.</li>
</ul>
<p>The polynomial kernel is <strong>K(a, b) = (a·b + r)ᵈ</strong>, where d is the degree. I checked the trick by hand with a = (1, 2), b = (3, 4), r = 1 and d = 2: the kernel gives (11 + 1)² = <strong>144</strong>, and the dot product of the six explicit degree-2 features of a and b also gives <strong>144</strong>. Same answer, without ever building the features.</p>
<p>The <strong>RBF kernel</strong>, <strong>K(a, b) = exp(−γ‖a − b‖²)</strong>, is 1 for identical points and close to 0 for distant ones. Its exponential expands into an infinite series, so it behaves like a polynomial kernel of unlimited degree.</p>
<h3>What I built: k-NN vs linear SVM vs RBF SVM</h3>
<p>To see the difference, I used a dataset no straight line can separate: one class forms a ring around the other.</p>
<pre><code class="language-python">from sklearn.datasets import make_circles
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC

X, y = make_circles(n_samples=400, factor=0.5, noise=0.1, random_state=0)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.3, random_state=0, stratify=y)
models = {"k-NN (k=5)": KNeighborsClassifier(n_neighbors=5),
          "SVM, linear": SVC(kernel="linear"),
          "SVM, RBF": SVC(kernel="rbf", gamma=1.0, C=1.0)}
for name, model in models.items():
    pipe = make_pipeline(StandardScaler(), model).fit(X_tr, y_tr)
    print(f"{name:12s} test accuracy: {pipe.score(X_te, y_te):.3f}")
print("support vectors kept:", pipe[-1].n_support_.sum(), "of", len(X_tr))  # last model = RBF SVM
</code></pre>
<pre><code class="language-text">k-NN (k=5)   test accuracy: 1.000
SVM, linear  test accuracy: 0.433
SVM, RBF     test accuracy: 1.000
support vectors kept: 50 of 280
</code></pre>
<p>The linear SVM is worse than a coin flip, because no straight line exists that works. The RBF kernel solves it perfectly, and so does k-NN, which never assumed a shape in the first place. The difference is what each keeps: k-NN needs all 280 training points at prediction time, while the SVM keeps only 50 support vectors.</p>
<hr />
<h2>Clustering: finding groups without labels</h2>
<p>Clustering groups unlabelled points so that points in a group are more similar to each other than to points in other groups. Methods are either <strong>partitional</strong> (every point goes into exactly one of K flat groups, like k-means) or <strong>hierarchical</strong> (a tree of clusters nested inside each other). Clusters themselves come in different types: well-separated, center-based, contiguous, density-based, conceptual, or defined by an objective function. The course covered two very different ideas of what a "group" is.</p>
<h3>k-means: groups around a centre</h3>
<p><strong>k-means</strong> follows five steps:</p>
<ol>
<li>choose K;</li>
<li>place K initial centroids;</li>
<li>assign every point to its nearest centroid;</li>
<li>move each centroid to the average position of the points assigned to it;</li>
<li>repeat steps 3–4 until the clusters stop changing.</li>
</ol>
<p>It is fast and simple, but it assumes round (globular) clusters of similar size and density, and the result depends on where the centroids start. The usual remedies are running it several times with smarter starting points (k-means++, the scikit-learn default; Arthur &amp; Vassilvitskii, 2007), bisecting k-means, choosing a higher K and merging clusters afterwards, or pre- and post-processing the data.</p>
<p>Without labels, there is no accuracy to tune K. I compared two common answers: the <strong>elbow method</strong> on WCSS (within-cluster sum of squares) and the <strong>silhouette score</strong>, <strong>s(i) = (b(i) − a(i)) / max(a(i), b(i))</strong>, where a(i) is the average distance to a point's own cluster and b(i) to the nearest other cluster (Rousseeuw, 1987).</p>
<pre><code class="language-python">from sklearn.datasets import make_blobs
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score

X, _ = make_blobs(n_samples=300, centers=4, cluster_std=0.8, random_state=1)
for k in range(1, 8):
    km = KMeans(n_clusters=k, n_init=10, random_state=0).fit(X)
    sil = f"{silhouette_score(X, km.labels_):.3f}" if k &gt; 1 else "  -  "
    print(f"K = {k}: WCSS {km.inertia_:7.1f} | silhouette {sil}")
</code></pre>
<pre><code class="language-text">K = 1: WCSS  9156.3 | silhouette   -
K = 2: WCSS  2003.1 | silhouette 0.724
K = 3: WCSS   909.8 | silhouette 0.630
K = 4: WCSS   378.0 | silhouette 0.697
K = 5: WCSS   340.1 | silhouette 0.623
K = 6: WCSS   304.0 | silhouette 0.532
K = 7: WCSS   268.7 | silhouette 0.473
</code></pre>
<p>WCSS always falls as K grows (it reaches 0 when every point is its own cluster), so you look for the bend, not the minimum. Here the bend is clearly at K = 4, the true number of groups. The silhouette score, however, slightly prefers K = 2, because one blob lies far away from the other three, which sit close together, so "far blob vs the rest" already looks like a clean split. That surprised me, and it is a useful lesson: the two metrics measure different things, so I now check both and look at the data before trusting a number.</p>
<h3>DBSCAN: groups as dense regions</h3>
<p><strong>DBSCAN</strong> (Ester et al., 1996) defines a cluster as a dense region. It needs two parameters: a radius Eps and a minimum number of points MinPts. A <strong>core point</strong> has at least MinPts neighbours within Eps; a <strong>border point</strong> has fewer but lies within Eps of a core point; everything else is <strong>noise</strong>. It still uses distances, but it has no centroids and needs no K.</p>
<p>I tested both methods on a ring around a dense core, plus one far-away outlier:</p>
<pre><code class="language-python">import numpy as np
from sklearn.datasets import make_circles
from sklearn.cluster import KMeans, DBSCAN

X, y = make_circles(n_samples=300, factor=0.3, noise=0.05, random_state=0)
X = np.vstack([X, [[2.5, 2.5]]])                  # one far-away outlier
km = KMeans(n_clusters=2, n_init=10, random_state=0).fit(X)
db = DBSCAN(eps=0.2, min_samples=5).fit(X)
# ... then print cluster sizes, noise count and each method's label for the outlier
</code></pre>
<pre><code class="language-text">k-means sizes: [140 161]
k-means outlier label: 0
DBSCAN clusters: 2 | noise points: 1
DBSCAN outlier label: -1
ring and core recovered: True
</code></pre>
<p>k-means cuts the ring and core into two halves, because it can only draw groups around centres, and it forces the outlier into a cluster. DBSCAN recovers the ring and the core exactly and labels the outlier as noise (−1). Its weaknesses are the mirror image: clusters with very different densities, and high-dimensional data, where distances become less meaningful and a single Eps no longer fits.</p>
<p><strong>Tuning DBSCAN.</strong> WCSS needs centroids, so the course suggested trying combinations of Eps and MinPts and comparing their silhouette scores. I ran that on the same ring-and-core data:</p>
<pre><code class="language-python">from sklearn.metrics import silhouette_score

X, _ = make_circles(n_samples=300, factor=0.3, noise=0.05, random_state=0)
for eps in [0.1, 0.2, 0.5]:
    for min_pts in [5, 15]:
        labels = DBSCAN(eps=eps, min_samples=min_pts).fit_predict(X)
        n_clusters, noise = len(set(labels) - {-1}), (labels == -1).sum()
        keep = labels != -1                         # silhouette without noise points
        sil = f"{silhouette_score(X[keep], labels[keep]):.3f}" if n_clusters &gt; 1 else "  -  "
        print(f"Eps {eps}, MinPts {min_pts:2d}: {n_clusters} clusters, {noise:3d} noise, silhouette {sil}")
</code></pre>
<pre><code class="language-text">Eps 0.1, MinPts  5: 15 clusters,  61 noise, silhouette 0.521
Eps 0.1, MinPts 15: 4 clusters, 216 noise, silhouette 0.711
Eps 0.2, MinPts  5: 2 clusters,   0 noise, silhouette 0.204
Eps 0.2, MinPts 15: 1 clusters, 150 noise, silhouette   -
Eps 0.5, MinPts  5: 1 clusters,   0 noise, silhouette   -
Eps 0.5, MinPts 15: 1 clusters,   0 noise, silhouette   -
</code></pre>
<p>The pattern matches the theory: a small Eps or a large MinPts creates more noise and splits clusters apart, while a large Eps merges everything into one cluster. But the result also taught me a limit. The correct answer (Eps 0.2, MinPts 5: ring and core, no noise) has the <em>lowest</em> silhouette score, while a setting that throws away 216 of 300 points as noise scores highest. The silhouette rewards compact, round clusters, and a ring is neither. So I now read the silhouette together with the number of clusters, the share of noise and a plot.</p>
<hr />
<h2>Neural networks: learning the weights</h2>
<p>The methods so far measure distances. A <strong>neural network</strong> does something different: it <em>learns</em> a set of weights by repeatedly correcting its own mistakes.</p>
<h3>Neurons and layers</h3>
<p>A single neuron multiplies each input by a weight, adds a bias and passes the sum through an <strong>activation function</strong>:</p>
<p><strong>z = w₁x₁ + w₂x₂ + … + b, output = f(z)</strong></p>
<p>Neurons are stacked in layers:</p>
<ul>
<li>an <strong>input layer</strong> with one neuron per feature;</li>
<li>one or more <strong>hidden layers</strong>, whose number and size are hyperparameters I choose;</li>
<li>an <strong>output layer</strong> shaped by the task: one neuron with a <strong>sigmoid</strong> for a yes/no answer (two neurons with softmax also works), or one neuron per class with <strong>softmax</strong> for several classes. A network that recognises car, truck, bicycle and pedestrian needs four output neurons.</li>
</ul>
<p>Activation functions add the non-linearity. Without them, any stack of layers collapses into one linear model. The input layer has none; hidden layers usually use <strong>ReLU</strong> (or Leaky ReLU); the output layer uses sigmoid or softmax.</p>
<h3>How a network learns</h3>
<p>Training repeats one loop:</p>
<ol>
<li>start with random weights;</li>
<li><strong>forward pass</strong>: compute the output from input through the hidden layers;</li>
<li>compute the <strong>loss</strong> (how wrong the output is);</li>
<li><strong>backpropagation</strong>: use the chain rule to find how much each weight contributed to the loss (Rumelhart et al., 1986);</li>
<li><strong>gradient descent</strong>: move each weight a small step against its gradient;</li>
<li>repeat.</li>
</ol>
<p>For one weight, the chain rule reads <strong>dL/dw₁ = dL/dy · dy/dz · dz/dw₁</strong>. With a sigmoid output, dy/dz = y(1 − y) and dz/dw₁ = x₁. I wrote this out for a single neuron to watch it learn:</p>
<pre><code class="language-python">import numpy as np

x, t = np.array([1.0, 2.0]), 1.0             # one input and its target
w, b, lr = np.array([0.1, -0.2]), 0.0, 0.5
for step in range(4):
    y = 1 / (1 + np.exp(-(w @ x + b)))       # forward pass
    loss = 0.5 * (y - t) ** 2
    dz = (y - t) * y * (1 - y)               # dL/dy * dy/dz
    w -= lr * dz * x                          # dz/dw = x
    b -= lr * dz
    print(f"step {step}: output {y:.3f}, loss {loss:.4f}")
</code></pre>
<pre><code class="language-text">step 0: output 0.426, loss 0.1650
step 1: output 0.530, loss 0.1103
step 2: output 0.616, loss 0.0738
step 3: output 0.678, loss 0.0518
</code></pre>
<p>Each step pulls the output towards the target and the loss down. In practice, training stops when the validation loss stops improving or after a set number of epochs, not when the training loss reaches zero, which usually means the network has memorised the data.</p>
<h3>Why the sigmoid is a problem in deep networks</h3>
<p>The sigmoid <strong>σ(z) = 1 / (1 + e⁻ᶻ)</strong> maps any number to the range 0–1, which is why it suits a probability at the output. Its gradient, <strong>σ(z)(1 − σ(z))</strong>, is the problem:</p>
<pre><code class="language-python">sigmoid = lambda z: 1 / (1 + np.exp(-z))
for z in [0, 2, 5, 10]:
    s = sigmoid(z)
    print(f"z = {z:2d}: sigmoid {s:.5f} | gradient {s * (1 - s):.5f}")
</code></pre>
<pre><code class="language-text">z =  0: sigmoid 0.50000 | gradient 0.25000
z =  2: sigmoid 0.88080 | gradient 0.10499
z =  5: sigmoid 0.99331 | gradient 0.00665
z = 10: sigmoid 0.99995 | gradient 0.00005
</code></pre>
<p>The gradient is never larger than 0.25. Backpropagation multiplies one such factor per layer, so even in the best case, five sigmoid layers shrink the signal to 0.25⁵ ≈ 0.001 (ignoring the weights). This is the <strong>vanishing gradient problem</strong>: the early layers barely learn. It is the reason hidden layers use ReLU, whose gradient is 1 for positive inputs.</p>
<h3>Overfitting, and how to fight it</h3>
<p>A network that is strong on training data but weak on new data is <strong>overfitting</strong>. I compared four networks on a small, noisy dataset with 150 training points:</p>
<pre><code class="language-python">from sklearn.neural_network import MLPClassifier

X, y = make_moons(n_samples=300, noise=0.35, random_state=2)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.5, random_state=0, stratify=y)
nets = {"large, no regularisation": MLPClassifier((200, 200), alpha=0.0, max_iter=5000, random_state=0),
        "small (8 neurons)":        MLPClassifier((8,), alpha=0.0, max_iter=5000, random_state=0),
        "large + L2 (alpha=1)":     MLPClassifier((200, 200), alpha=1.0, max_iter=5000, random_state=0),
        "large + early stopping":   MLPClassifier((200, 200), early_stopping=True, max_iter=5000, random_state=0)}
for name, net in nets.items():
    pipe = make_pipeline(StandardScaler(), net).fit(X_tr, y_tr)
    print(f"{name:25s} train {pipe.score(X_tr, y_tr):.3f} | test {pipe.score(X_te, y_te):.3f}")
</code></pre>
<pre><code class="language-text">large, no regularisation  train 1.000 | test 0.793
small (8 neurons)         train 0.833 | test 0.827
large + L2 (alpha=1)      train 0.907 | test 0.840
large + early stopping    train 0.867 | test 0.813
</code></pre>
<p>The large network scores 100% on training data and the worst on test data: a textbook case. Every remedy narrows the gap: a <strong>simpler</strong> network (fewer neurons, not more), <strong>L2 regularisation</strong>, and <strong>early stopping</strong>. More or augmented data and dropout are the other standard tools.</p>
<p>Accuracy alone hides <em>which</em> mistakes a model makes, so the course always paired it with the <strong>confusion matrix</strong>. For the small network on the 150 test points:</p>
<table>
<thead>
<tr>
<th></th>
<th>Predicted class 0</th>
<th>Predicted class 1</th>
</tr>
</thead>
<tbody><tr>
<td><strong>Actual class 0</strong></td>
<td>63 (TN)</td>
<td>12 (FP)</td>
</tr>
<tr>
<td><strong>Actual class 1</strong></td>
<td>14 (FN)</td>
<td>61 (TP)</td>
</tr>
</tbody></table>
<p>In a medical setting, those 14 false negatives would matter far more than the 12 false positives, which is why I looked at recall in our heart-disease project.</p>
<h3>In the lab: a neural network in RapidMiner</h3>
<p>We also built networks without code in RapidMiner, on the classic <strong>sonar</strong> dataset (Gorman &amp; Sejnowski, 1988), where each sample holds 60 sonar energy readings and is labelled rock or mine. The design followed directly from the data: 60 input neurons, one per feature, and two output neurons, one per class. The readings had different ranges, so a <strong>Normalize</strong> operator (the RapidMiner equivalent of a scaler) went in before the network, for the same reason I scale features for k-NN.</p>
<hr />
<h2>Ensembles: many models, one decision</h2>
<p>An ensemble combines several models instead of trusting one. The course covered three ways to do it:</p>
<ul>
<li><strong>Majority vote</strong>: different models predict in parallel and the most common answer wins.</li>
<li><strong>Bagging</strong> (bootstrap aggregating): train many copies of one model, each on a random sample of the data drawn with replacement, then vote or average (Breiman, 1996). A random forest is bagging with decision trees.</li>
<li><strong>Boosting</strong>: train models one after another, each focusing on the examples the previous ones got wrong. AdaBoost is the classic version (Freund &amp; Schapire, 1997).</li>
</ul>
<pre><code class="language-python">from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import BaggingClassifier, AdaBoostClassifier, VotingClassifier
from sklearn.linear_model import LogisticRegression

X, y = make_moons(n_samples=500, noise=0.35, random_state=3)
tree = DecisionTreeClassifier(random_state=0)
models = {"one decision tree": tree,
          "bagging (100 trees)": BaggingClassifier(tree, n_estimators=100, random_state=0),
          "AdaBoost (100 stumps)": AdaBoostClassifier(DecisionTreeClassifier(max_depth=1), n_estimators=100, random_state=0),
          "majority vote (k-NN, SVM, LR)": make_pipeline(StandardScaler(), VotingClassifier(
              [("knn", KNeighborsClassifier(15)), ("svm", SVC()), ("lr", LogisticRegression())], voting="hard"))}
for name, m in models.items():
    print(f"{name:30s} mean 5-fold accuracy {cross_val_score(m, X, y, cv=5).mean():.3f}")
</code></pre>
<pre><code class="language-text">one decision tree              mean 5-fold accuracy 0.822
bagging (100 trees)            mean 5-fold accuracy 0.864
AdaBoost (100 stumps)          mean 5-fold accuracy 0.864
majority vote (k-NN, SVM, LR)  mean 5-fold accuracy 0.868
</code></pre>
<p>A single deep tree overfits the noise; every ensemble beats it by about four points. The errors of different models partly cancel out when they vote. We saw the same pattern in our group project, where ensembles beat a single decision tree by 5–9 points.</p>
<hr />
<h2>Ethics: what the models cost</h2>
<p>The course did not end with accuracy. It asked what these systems cost outside the code:</p>
<ul>
<li><strong>Energy and water</strong>: training and running large models uses a lot of electricity, and data centres use water for cooling.</li>
<li><strong>Data privacy</strong>: models are trained on data about people, who may not know how it is used.</li>
<li><strong>Consent</strong>: people should agree to their data being used, especially for sensitive data such as health records.</li>
<li><strong>Labour</strong>: automation changes jobs, and much training data is labelled by low-paid workers.</li>
</ul>
<p>To me, this connects back to the methods: a small, well-regularised model that is good enough is often the more responsible choice than the largest one available.</p>
<hr />
<h2>What I learned</h2>
<ul>
<li><strong>Lazy and eager are a trade-off, not a ranking.</strong> k-NN is cheap to train and expensive to use; an SVM is the reverse. For large datasets with fast predictions, that difference matters more than a few points of accuracy.</li>
<li><strong>Start from the shape of the data.</strong> My most useful habit from this course is to plot the data first. Overlapping, curved classes point to a kernel SVM or k-NN; rings and outliers point to DBSCAN rather than k-means.</li>
<li><strong>Every method has hidden choices.</strong> k, C, γ, K, Eps, MinPts and the size of a network all change the result, and each one needs a principled way to choose it: cross-validation with labels, WCSS and silhouette without, and always a check on data the model has not seen.</li>
<li><strong>No metric is the whole truth.</strong> The elbow and the silhouette disagreed on K, the silhouette rewarded a bad DBSCAN setting, and accuracy hid which errors a network made. Reading several measures together, plus a plot, became my habit.</li>
<li><strong>Bigger is not better.</strong> The largest network overfit the most, and a single deep tree lost to simple ensembles.</li>
</ul>
<p><strong>What I would explore next:</strong> tuning C and γ together with a grid search, testing DBSCAN on real data with varying densities (and trying HDBSCAN, which handles that better), and comparing sigmoid and ReLU networks of increasing depth to see the vanishing gradient in training curves.</p>
<h2>Why this matters in industry</h2>
<p>These methods are far from outdated. k-NN-style similarity search is the core of recommendation systems and of the vector search behind retrieval-augmented generation. SVMs remain strong on small, high-dimensional datasets such as text classification. Clustering drives customer segmentation, and DBSCAN's notion of noise is a practical anomaly detector for fraud or sensor data. Neural networks power today's vision and language systems, and the backpropagation loop above is the same one that trains them, at a vastly larger scale. Ensembles such as random forests and gradient boosting are still the first choice for tabular business data. Knowing <em>why</em> each method behaves as it does is what lets an engineer choose quickly and explain the choice.</p>
<hr />
<p><strong>Skills demonstrated:</strong> Python · scikit-learn · NumPy · RapidMiner · k-nearest neighbours · support vector machines · kernel methods · k-means · DBSCAN · WCSS and the elbow method · silhouette analysis · neural networks · backpropagation and gradient descent · regularisation and early stopping · confusion matrices · bagging, boosting and voting ensembles · cross-validation · feature scaling · model selection · AI ethics</p>
<hr />
<p><em>References</em></p>
<p><em>Arthur, D., &amp; Vassilvitskii, S. (2007). k-means++: The advantages of careful seeding. In Proceedings of the Eighteenth Annual ACM-SIAM Symposium on Discrete Algorithms (pp. 1027–1035). SIAM.</em></p>
<p><em>Breiman, L. (1996). Bagging predictors. Machine Learning, 24(2), 123–140.</em> <a href="https://doi.org/10.1007/BF00058655"><em>https://doi.org/10.1007/BF00058655</em></a></p>
<p><em>Cortes, C., &amp; Vapnik, V. (1995). Support-vector networks. Machine Learning, 20(3), 273–297.</em> <a href="https://doi.org/10.1007/BF00994018"><em>https://doi.org/10.1007/BF00994018</em></a></p>
<p><em>Cover, T., &amp; Hart, P. (1967). Nearest neighbor pattern classification. IEEE Transactions on Information Theory, 13(1), 21–27.</em> <a href="https://doi.org/10.1109/TIT.1967.1053964"><em>https://doi.org/10.1109/TIT.1967.1053964</em></a></p>
<p><em>Ester, M., Kriegel, H.-P., Sander, J., &amp; Xu, X. (1996). A density-based algorithm for discovering clusters in large spatial databases with noise. In Proceedings of the Second International Conference on Knowledge Discovery and Data Mining (KDD-96) (pp. 226–231). AAAI Press.</em></p>
<p><em>Freund, Y., &amp; Schapire, R. E. (1997). A decision-theoretic generalization of on-line learning and an application to boosting. Journal of Computer and System Sciences, 55(1), 119–139.</em> <a href="https://doi.org/10.1006/jcss.1997.1504"><em>https://doi.org/10.1006/jcss.1997.1504</em></a></p>
<p><em>Gorman, R. P., &amp; Sejnowski, T. J. (1988). Analysis of hidden units in a layered network trained to classify sonar targets. Neural Networks, 1(1), 75–89.</em> <a href="https://doi.org/10.1016/0893-6080(88)90023-8"><em>https://doi.org/10.1016/0893-6080(88)90023-8</em></a></p>
<p><em>Pedregosa, F., Varoquaux, G., Gramfort, A., Michel, V., Thirion, B., Grisel, O., … Duchesnay, É. (2011). Scikit-learn: Machine learning in Python. Journal of Machine Learning Research, 12, 2825–2830.</em></p>
<p><em>Rumelhart, D. E., Hinton, G. E., &amp; Williams, R. J. (1986). Learning representations by back-propagating errors. Nature, 323(6088), 533–536.</em> <a href="https://doi.org/10.1038/323533a0"><em>https://doi.org/10.1038/323533a0</em></a></p>
<p><em>Rousseeuw, P. J. (1987). Silhouettes: A graphical aid to the interpretation and validation of cluster analysis. Journal of Computational and Applied Mathematics, 20, 53–65.</em> <a href="https://doi.org/10.1016/0377-0427(87)90125-7"><em>https://doi.org/10.1016/0377-0427(87)90125-7</em></a></p>
<hr />
<p><em>The Hybrid Mind: where symbolic AI meets neural networks.</em></p>
]]></content:encoded></item><item><title><![CDATA[Building ML Algorithms from Scratch in Python]]></title><description><![CDATA[Regression, k-means, silhouette and template matching written from scratch in Python, then checked against scikit-learn: what my ML labs taught me.]]></description><link>https://fkabir.hashnode.dev/building-ml-algorithms-from-scratch-in-python</link><guid isPermaLink="true">https://fkabir.hashnode.dev/building-ml-algorithms-from-scratch-in-python</guid><category><![CDATA[Machine Learning]]></category><category><![CDATA[Python]]></category><category><![CDATA[numpy]]></category><category><![CDATA[scikit learn]]></category><category><![CDATA[KMeans]]></category><category><![CDATA[clustering]]></category><dc:creator><![CDATA[Farhana Kabir]]></dc:creator><pubDate>Wed, 02 Dec 2026 23:04:36 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6b0f76a874eff5c1bf91b426/7f94b1cd-030f-48e1-8bd2-68013312a408.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><strong>Key takeaways</strong></p>
<ul>
<li>In <em>Programming for Machine Learning</em>, a course in my master's in Applied AI, I worked through labs on regression, clustering and image processing, writing core algorithms myself before using libraries.</li>
<li>The key lessons: understand the data before modelling it, keep test data separate when choosing a model, and scale features for distance-based methods.</li>
<li>Writing k-means, the silhouette score and template matching from scratch, then checking them against scikit-learn, is the habit I take with me: <strong>implement, then verify against a trusted reference.</strong></li>
</ul>
<h2>Context: why "programming for ML" is its own skill</h2>
<p>Most ML tutorials start with <code>model.fit(X, y)</code>. This course went the other way. It started with Python basics (program state, loops, recursion, string processing), then asked us to load and clean real data by hand, implement algorithms ourselves, and only then compare our results with scikit-learn.</p>
<p>That order matters in industry. Data rarely arrives clean, and you can only trust, explain or improve a model if you know what it computes.</p>
<p>The labs I write about here:</p>
<table>
<thead>
<tr>
<th>Topic</th>
<th>What I built</th>
</tr>
</thead>
<tbody><tr>
<td>Regression</td>
<td>Linear regression with the normal equation, then polynomial regression with scikit-learn</td>
</tr>
<tr>
<td>Clustering</td>
<td>A k-means class and the silhouette score, written from scratch</td>
</tr>
<tr>
<td>Image processing</td>
<td>Image loading, scaling and thresholding with scikit-image, plus my own template matching</td>
</tr>
</tbody></table>
<hr />
<h2>Regression: from the normal equation to overfitting</h2>
<h3>Linear regression by hand</h3>
<p>For income versus age, I solved linear regression with the <strong>normal equation</strong> instead of calling a library:</p>
<p><strong>θ = (XᵀX)⁻¹ Xᵀy</strong></p>
<p>where the first column of X is all ones, which gives the intercept. In NumPy, on a small synthetic example:</p>
<pre><code class="language-python">import numpy as np
rng = np.random.default_rng(0)
age = rng.uniform(20, 50, 40).reshape(-1, 1)
income = 240 + 3.9 * age.ravel() + rng.normal(0, 10, 40)

X = np.c_[np.ones(age.shape), age]                 # design matrix [1, x]
theta = np.linalg.inv(X.T @ X) @ X.T @ income      # normal equation
print("intercept, slope:", theta.round(2))
</code></pre>
<pre><code class="language-text">intercept, slope: [237.4    4.06]
</code></pre>
<p>The fitted values are close to the true 240 and 3.9 used to generate the data. One small but real lesson: you cannot "divide" by a matrix. You multiply by its inverse (and in production you would use <code>np.linalg.lstsq</code> or a library, which is numerically safer).</p>
<h3>Underfitting and overfitting, made visible</h3>
<p>Next came polynomial regression. Income rises with age and then falls, so a straight line underfits. Here is the same experiment on synthetic data with that shape:</p>
<pre><code class="language-python">from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import PolynomialFeatures, StandardScaler
from sklearn.linear_model import LinearRegression

for degree in [1, 2, 5, 12]:
    model = make_pipeline(StandardScaler(), PolynomialFeatures(degree), LinearRegression())
    model.fit(X_tr, y_tr)
    # ... compute train and test MSE
</code></pre>
<pre><code class="language-text">degree  1: train MSE   4798.7   test MSE   5936.1
degree  2: train MSE    344.3   test MSE    411.9
degree  5: train MSE    319.9   test MSE    415.0
degree 12: train MSE    225.1   test MSE    454.3
</code></pre>
<p>Degree 1 underfits. Degree 2 captures the curve. Degree 12 has the lowest training error but a higher test error: it starts fitting noise. Two practices I now follow:</p>
<ul>
<li><strong>Learn preprocessing settings from the training split only</strong>, then apply them unchanged to the test split. A pipeline makes this automatic.</li>
<li><strong>Choose hyperparameters on a validation set</strong>, and keep a separate test set for the final, honest estimate.</li>
</ul>
<hr />
<h2>Clustering: k-means and the silhouette score from scratch</h2>
<p>I implemented k-means as a class with the two alternating steps of Lloyd's algorithm (Lloyd, 1982): label every point with its closest centroid, recompute every centroid as the average of the points it owns, and repeat until the centroids settle. The core idea, in a compact vectorised form:</p>
<pre><code class="language-python">def kmeans_step(data, centroids):
    # assign: index of the nearest centroid for every point
    dists = np.linalg.norm(data[:, None, :] - centroids[None, :, :], axis=2)
    labels = dists.argmin(axis=1)
    # update: each centroid moves to the mean of its points (kept if empty)
    new = np.array([data[labels == j].mean(axis=0) if np.any(labels == j) else centroids[j]
                    for j in range(len(centroids))])
    return labels, new
</code></pre>
<p>On three synthetic blobs this converged after 3 iterations, with centroids close to the true centres (0, 0), (4, 4) and (0, 4).</p>
<p>To choose <em>k</em>, I implemented the <strong>silhouette score</strong> (Rousseeuw, 1987). For a point i, a(i) measures how far it sits, on average, from its cluster-mates, b(i) measures its average distance to the closest neighbouring cluster, and</p>
<p><strong>s(i) = (b(i) − a(i)) / max(a(i), b(i))</strong></p>
<p>The average over all points is between −1 and 1; higher means tighter, better-separated clusters.</p>
<h3>Checking against scikit-learn</h3>
<p>I compared my implementation with <code>sklearn.metrics.silhouette_score</code>, including a cluster with only one point, which by the standard definition contributes s(i) = 0:</p>
<pre><code class="language-python">data = np.array([[0, 0], [0, 1], [1, 0], [8, 8], [8, 9], [20, 0]], dtype=float)
labels = np.array([0, 0, 0, 1, 1, 2])             # [20, 0] is a one-point cluster
print("mine:", round(silhouette(data, labels), 4),
      " scikit-learn:", round(silhouette_score(data, labels), 4))
</code></pre>
<pre><code class="language-text">mine: 0.7527  scikit-learn: 0.7527
</code></pre>
<p>This is the habit I value most from the course: <strong>a from-scratch implementation is only finished when it agrees with a trusted reference</strong>, and testing edge cases is part of that.</p>
<p>Another lesson from this lab: features on very different scales (here, yearly income and annual rent per square metre) let the larger one dominate every Euclidean distance. Distance-based methods need <strong>feature scaling</strong> (for example <code>StandardScaler</code>) just as much as regression does.</p>
<hr />
<h2>Image processing: images are just arrays</h2>
<p>The image-processing lab used scikit-image's sample images. The useful mindset shift: an image is a NumPy array with a shape and a dtype, so most image operations are array operations.</p>
<ul>
<li>A colour image is <code>(rows, cols, 3)</code> of <code>uint8</code> (0–255); <code>rgb2gray</code> turns it into <code>(rows, cols)</code> floats in 0–1, which means any threshold also has to live on the 0–1 scale. scikit-image weights the channels 0.2125, 0.7154 and 0.0721 (red, green, blue), which I checked directly.</li>
<li><code>rescale</code> multiplies the size by a factor; <code>resize</code> targets a fixed output shape.</li>
<li><code>uint8</code> <strong>arithmetic wraps around:</strong> <code>np.uint8(200) + np.uint8(100)</code> gives <code>44</code>. Converting to float before doing sums is not optional.</li>
</ul>
<p>I wrote my own <strong>template matching</strong> with normalised cross-correlation (NCC): slide the template over the image, subtract the mean of the template and of each window (so brightness differences don't matter), and score the match between −1 and 1:</p>
<pre><code class="language-python">image = data.coins().astype(float)            # uint8 -&gt; float, avoids wrap-around
template = image[170:220, 75:130]             # one coin cut from the image
t = template - template.mean()
# for each window: wc = win - win.mean()
# score = (wc * t).sum() / np.sqrt((wc ** 2).sum() * (t ** 2).sum())
</code></pre>
<pre><code class="language-text">best match (x, y): (75, 170) NCC: 1.0
</code></pre>
<p>The highest score lands exactly where I cut the template from. A sum-of-squared-differences matcher works the other way round (lowest value wins), and it finds the same location. Writing the loop myself made it clear why library versions use FFT-based tricks: the naive version is slow.</p>
<hr />
<h2>What I learned</h2>
<ul>
<li><strong>Evaluation discipline.</strong> Separate training, validation and test data, fit preprocessing on training data only, and compare models on data they have not seen.</li>
<li><strong>Implement, then verify.</strong> Writing k-means, the silhouette score, the normal equation and NCC myself gave me a real understanding of what library calls do, and comparing with scikit-learn and scikit-image turned that understanding into tested code.</li>
<li><strong>Data comes before models.</strong> Cleaning text fields, handling file encodings (a hidden BOM character in a CSV header) and choosing feature scales mattered as much as the choice of algorithm.</li>
</ul>
<p><strong>What I would explore next:</strong> k-means++ initialisation with several random starts (keeping the lowest-inertia result), automated tests for each from-scratch function, and an FFT-based version of template matching for speed.</p>
<h2>Why this matters in industry</h2>
<p>The same skills show up in every production ML project: cleaning and validating data before training, choosing models on validation data rather than training data, scaling features for distance-based methods, and verifying numerical code before its results reach a dashboard or a decision. Computer-vision basics like template matching are still used in quality inspection and document processing, and knowing that an image is "just an array" makes deep-learning pipelines much less mysterious.</p>
<p>On <strong>The Hybrid Mind</strong>, this course is my foundation on the <em>neural and statistical</em> side: the learning-from-data half of hybrid AI.</p>
<hr />
<p><strong>Skills demonstrated:</strong> Python · NumPy · pandas · Matplotlib · scikit-learn · scikit-image · linear regression (normal equation) · polynomial regression · train/validation/test splits · overfitting and underfitting · feature scaling · k-means · silhouette analysis · template matching (NCC) · testing numerical code against reference implementations</p>
<hr />
<h2>References</h2>
<p>Lloyd, S. (1982). Least squares quantization in PCM. <em>IEEE Transactions on Information Theory, 28</em>(2), 129–137. <a href="https://doi.org/10.1109/TIT.1982.1056489">https://doi.org/10.1109/TIT.1982.1056489</a></p>
<p>Pedregosa, F., Varoquaux, G., Gramfort, A., Michel, V., Thirion, B., Grisel, O., … Duchesnay, É. (2011). Scikit-learn: Machine learning in Python. <em>Journal of Machine Learning Research, 12</em>, 2825–2830.</p>
<p>Rousseeuw, P. J. (1987). Silhouettes: A graphical aid to the interpretation and validation of cluster analysis. <em>Journal of Computational and Applied Mathematics, 20</em>, 53–65. <a href="https://doi.org/10.1016/0377-0427(87)90125-7">https://doi.org/10.1016/0377-0427(87)90125-7</a></p>
<p>van der Walt, S., Schönberger, J. L., Nunez-Iglesias, J., Boulogne, F., Warner, J. D., Yager, N., Gouillart, E., Yu, T., &amp; the scikit-image contributors. (2014). scikit-image: Image processing in Python. <em>PeerJ, 2</em>, e453. <a href="https://doi.org/10.7717/peerj.453">https://doi.org/10.7717/peerj.453</a></p>
<hr />
<p><em>The Hybrid Mind: where symbolic AI meets neural networks.</em></p>
]]></content:encoded></item></channel></rss>