KNeighborsClassifier

public class KNeighborsClassifier

K-neighbors classifier.

Classifier implementing the k-nearest neighbors vote.

  • p

    The order of the norm of the difference: ||a - b||_p.

    Declaration

    Swift

    var p: Int
  • Weight function used in prediction.

    Declaration

    Swift

    public var weights: String
  • Number of neighbors.

    Declaration

    Swift

    var neighborCount: Int
  • The training data.

    Declaration

    Swift

    var data: Tensor<Float>
  • The target class correspoing to training data.

    Declaration

    Swift

    var labels: Tensor<Int32>
  • Create a K neighbors classifier model.

    Declaration

    Swift

    public init(
        neighborCount: Int = 5,
        weights: String = "distance",
        p: Int = 2
    )

    Parameters

    neighborCount

    Number of neighbors to use, default to 5.

    weights

    Weight function used in prediction. Possible values uniform - uniform weighted, distance - weight point by inverse of their distance. Default set to distance.

    p

    The order of the norm of the difference: ||a - b||_p, default set to 2.

  • Fit a K-neighbors classifier model.

    Declaration

    Swift

    public func fit(data: Tensor<Float>, labels: Tensor<Int32>)

    Parameters

    data

    Training data with shape [sample count, feature count].

    labels

    Target value with shape [sample count].

  • Returns the weights of each neighbor.

    Declaration

    Swift

    internal func computeWeights(
        distances: Tensor<Float>,
        labels: Tensor<Float>
    ) -> Tensor<Float>

    Parameters

    distances

    Contains the distance between test data and top neighbors.

    labels

    Contains the classes of neighbors.

  • Returns the predicted classification.

    Declaration

    Swift

    internal func predictSingleSample(_ test: Tensor<Float>) -> Tensor<Int32>

    Parameters

    test

    Input data to be classified.

    Return Value

    Predicted classification.

  • Returns classification.

    Declaration

    Swift

    public func prediction(for data: Tensor<Float>) -> Tensor<Int32>

    Parameters

    data

    Prediction data with shape [sample count, feature count].

    Return Value

    Classification for test data.

  • Returns the mean accuracy.

    Declaration

    Swift

    public func score(data: Tensor<Float>, labels: Tensor<Int32>) -> Float

    Parameters

    data

    Sample data with shape [sample count, feature count].

    labels

    Target label with shape [sample count].

    Return Value

    Returns the mean accuracy on the given test data and labels.