How Alike Are Two Applicants?

Classic MLMedium+20 XP+20

How Alike Are Two Applicants?

A bank's loan data has an awkward shape. Plotted by two scaled features, the approved applicants sit in a ring, with denied applicants both inside it and all around it. No straight line can separate a ring from what surrounds it, so a plain linear SVM is out.

A kernel SVM gets a curved boundary by asking a different question. It doesn't ask "which side of a line is this point on?" It asks "how similar is this point to each training point?" For that it needs similarity as a number, and the most common choice is the RBF (Gaussian) kernel:

K(a,b)=exp⁡(−∥a−b∥22σ2)K(a, b) = \exp\left(-\frac{\lVert a - b \rVert^2}{2\sigma^2}\right)K(a,b)=exp(−2σ2∥a−b∥2​)
  • ∥a−b∥2\lVert a - b \rVert^2∥a−b∥2 is the squared straight-line distance between the two points: square the difference in every feature, then add those up.
  • σ\sigmaσ (sigma) is the kernel's width, in the same units as the features. It sets how quickly similarity fades as points move apart.
  • Identical points score exactly 111. The score falls toward 000 as the points get further apart, and it is never negative.

Task: write rbf_similarity(points_a, points_b, sigma) that returns the kernel matrix. This is a list with one row per point in points_a, where entry [i][j] is KKK(points_a[i], points_b[j]), rounded to 4 decimal places.

  • Every point is a list of numbers, and all points have the same number of features (one, two, three or more).
  • points_a and points_b can have different lengths, so the matrix need not be square. They can also be the same list.
  • sigma is greater than 0.

Each row of this matrix shows how one new applicant looks to the model: a list of "how close am I to each stored applicant?" A kernel SVM decides from those closeness scores instead of from a line, and that is how its boundary can bend into a circle.

Examples

points_a = [[0, 0], [1, 1]]
points_b = [[0, 0], [1, 1]]
sigma = 1.0
returns [[1.0, 0.3679], [0.3679, 1.0]]
points_a = [[1], [4]]
points_b = [[1], [2], [6]]
sigma = 2.0
returns [[1.0, 0.8825, 0.0439], [0.3247, 0.6065, 0.6065]]

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run