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:
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
EasyA 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?
- Build the distance table of
menu. - Find the most alike and the most different pair: each pair once, never a smoothie with itself.
- 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
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Unsupervised Learning
1Finding Groups
Learning Without LabelsMeasuring SimilarityK-Means by HandK-Means in scikit-learnRecap: Gym Members7PCA in Practice
Seeing 64 DimensionsComponents as PatternsCompress and RebuildPCA Before a ModelRecap: Face Scanner10Project: Digit Explorer
Look at the DigitsShrink with PCACluster the DigitsName the ClustersFind the Odd OnesPractice on your own: Online Python compiler