Cadmium::Classifier::Tabular::KNN
K-Nearest Neighbors classifier for multi-feature tabular data.
This classifier stores all training data and makes predictions by finding the k most similar training examples and taking a majority vote.
Features
- Handles numerical features of any dimension
- Supports multiple distance metrics (Euclidean, Manhattan, Cosine, etc.)
- No training phase - just data storage
- Suitable for small to medium datasets
Example
classifier = Cadmium::Classifier::Tabular::KNN.new(k: 3)
features = [
[1.0, 2.0, 3.0],
[1.1, 2.1, 3.1],
[5.0, 6.0, 7.0],
]
labels = ["class_a", "class_a", "class_b"]
classifier.train(features, labels)
# Predict new sample
result = classifier.classify([1.05, 2.05, 3.05])
# => "class_a"
# Get detailed results with vote counts
details = classifier.classify_details([1.05, 2.05, 3.05])
# => {"class_a" => 3, "class_b" => 0}
Constructors
Instance methods
Classify a new sample and return the predicted label.
classifier.classify([1.0, 2.0, 3.0]) # => "class_a"
Classify multiple samples at once.
results = classifier.classify_batch([[1.0, 2.0], [3.0, 4.0]])
# => ["class_a", "class_b"]
Classify a new sample and return detailed vote counts.
details = classifier.classify_details([1.0, 2.0, 3.0])
# => {"class_a" => 3, "class_b" => 2}
Save the trained model to a file.
classifier.save_model("knn_model.msgpack")
Train the classifier by storing feature vectors and labels.
features = [[1.0, 2.0], [3.0, 4.0]]
labels = ["a", "b"]
classifier.train(features, labels)