Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
Knn (weights=distance)
Language:
Ada
Assembly
Bash
C#
C++ (gcc)
C++ (clang)
C++ (vc++)
C (gcc)
C (clang)
C (vc)
Client Side
Clojure
Common Lisp
D
Elixir
Erlang
F#
Fortran
Go
Haskell
Java
Javascript
Kotlin
Lua
MySql
Node.js
Ocaml
Octave
Objective-C
Oracle
Pascal
Perl
Php
PostgreSQL
Prolog
Python
Python 3
R
Rust
Ruby
Scala
Scheme
Sql Server
Swift
Tcl
Visual Basic
Layout:
Vertical
Horizontal
import numpy as np x = np.array([ [2, 17], [3,11], [4,23], [1,12], [2,6], [6,2], [11,4], [3,24], [14,2], [9,4], [24,23], [7,6], [23,4], [14,16], [12,3] ]) y = np.array([ '+', '-', '+', '+', '-', '+', '-', '-', '-', '+', '+', '+', '-', '-', '+' ]) def distances(array, node): for _node in array: yield np.linalg.norm(_node-node) def percentage_of_labels(distances, labels): result = {} sum_distances = np.sum(1/distances) for i in set(labels): result[i] = (1/np.sum(distances[labels==i])) / sum_distances return result def knn(k, X, y, node): dist = np.array(list(distances(X, node))) index = dist.argsort()[:k] return percentage_of_labels(dist[index], y[index]) if __name__ == "__main__": print(knn(5,x, y, np.array([3,9])))
[
+
]
Show input
Absolute running time: 0.47 sec, cpu time: 0.71 sec, memory peak: 21 Mb, absolute service time: 0,48 sec
edit mode
|
history
|
discussion
{'+': 0.043264739247419574, '-': 0.13594994609086367}