Menu
CoddyTech

Recap: Wine Neighbors

Part of the Supervised Learning section of Coddy's Machine Learning journey. Lesson 10 of 58.

challenge icon

Challenge

Easy

Draw a map like this chapter's first, for wine. The starter splits 178 wines (two features, cultivars 0 to 2), lists ks and labels the chart.

  1. Scale both sets, fit on training wines.
  2. Print the k with the best test accuracy (for now: chapter 7 has a fairer judge).
  3. With that k, fill the map: grid xx, yy, 100 by 100, -3 to 3 both ways, answers in zz.
  4. Scatter the scaled training wines on top, labelled from names; add a legend.

From alcohol and flavanoids:

Best k: 13 (test accuracy 0.956)

A wine map from alcohol and flavanoids, both scaled: an orange region on the left, a blue region at the upper right and a green region below, with the training wines of each class on top and a legend

Coddy describes your map.

Try it yourself

import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import load_wine
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.preprocessing import StandardScaler

# 178 wines from three cultivars, classes 0, 1, 2
wine = load_wine()
# columns 6 and 12: flavanoids and proline
X = wine.data[:, [6, 12]]
y = wine.target
names = ["cultivar A", "cultivar B", "cultivar C"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=0)
ks = range(1, 32, 2)  # k = 1, 3, 5, ..., 31

fig, ax = plt.subplots()
ax.set_title("Wine Neighbors")
ax.set_xlabel("flavanoids (scaled)")
ax.set_ylabel("proline (scaled)")

# Write your code below

All lessons in Supervised Learning

Practice on your own: Online Python compiler