Menu
CoddyTech

Measuring Similarity

Part of the Unsupervised Learning section of Coddy's Machine Learning journey. Lesson 2 of 51.

In k-NN, nearest meant the smallest distance. To find groups, you need it for every pair of rows: a distance table. Four friends rated two films, 1 to 10:

ratings = np.array([[9, 2], [8, 3], [2, 9], [3, 7]])  # Ana, Ben, Cy, Dee
n = len(ratings)
table = np.zeros((n, n))
for i in range(n):
    table[i] = np.sqrt(((ratings - ratings[i]) ** 2).sum(axis=1))

Row i holds friend i's distance to everyone. Here is table, drawn as a grid:

A 4 by 4 grid of distances between Ana, Ben, Cy and Dee. The diagonal holds 0.0. The two cells for Ana and Ben, 1.4, are highlighted as the smallest off the diagonal; Ana and Cy are farthest at 9.9

Skip the 0 diagonal, each friend against themself. The smallest number left is the most alike pair, the largest the most different. Small distance, similar rows.

challenge icon

Challenge

Easy

A juice bar adds the chef's new smoothie, read by the program, to its menu. Which two are so alike that one can go? Which two are most different, for a tasting flight?

  1. Build the distance table of menu.
  2. Find the most alike and the most different pair: each pair once, never a smoothie with itself.
  3. Print both, names in menu order, distances to 1 decimal.

For another menu:

Most alike: Lemon Zing and Lime Twist (14.1 g apart)
Most different: Choco Shake and Cucumber Cool (212.6 g apart)

Try it yourself

import numpy as np

names = ["Berry Blast", "Green Glow", "Mango Lassi", "Kale Kick", "Tropical Sun", "Banana Oat", "Minty Melon"]
# One row per smoothie, grams per cup: fruit, greens, yogurt
menu = np.array([[180, 0, 120],
                 [90, 110, 60],
                 [160, 0, 150],
                 [60, 150, 30],
                 [200, 20, 40],
                 [100, 0, 200],
                 [170, 40, 0]])

# The chef's new recipe joins the menu as the last row
names.append(input())
new = [int(input()), int(input()), int(input())]
menu = np.concatenate([menu, [new]])

# Write your code below
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Unsupervised Learning

Practice on your own: Online Python compiler