concept

Neighbors, margins and probabilistic classifiers

Brute-force binary KNN uses squared Euclidean distance, input index for equal distances, and class 0 for tied votes. Naive Bayes and SVM use different assumptions.

Formal Syntax & Structure

artificial-intelligence syntaxartificial-intelligence
knn(rows, query, k)

Working Example

Example Snippetartificial-intelligence
def knn(rows, query, k):    if not 1 <= k <= len(rows):        raise ValueError("k outside training set size")    if not query or any(len(x) != len(query) or y not in (0, 1)                        for x, y in rows):        raise ValueError("Invalid feature shape or label")    distances = [(sum((a - b)**2 for a, b in zip(x, query)), i, y)                 for i, (x, y) in enumerate(rows)]    nearest = sorted(distances)[:k]    return int(2 * sum(y for _, _, y in nearest) > k)
rows = [([2], 0), ([5], 1), ([6], 1)]print(knn(rows, [3], 1))print(knn(rows, [3], 3))