geocrystal / kd_tree Goto Github PK
View Code? Open in Web Editor NEWCrystal implementation of "K-Dimensional Tree" and "N-Nearest Neighbors"
License: MIT License
Crystal implementation of "K-Dimensional Tree" and "N-Nearest Neighbors"
License: MIT License
Hi,
I think i found a bug in the function nearest!, it does not return the correct answer, i generated the following test
describe "#nearest" do
it "should equal naive implementation" do
ndim = 2
k = 3
distance = ->(m : Array(Float64),n : Array(Float64)) do
m.each_with_index.reduce(0) do |sum, (coord, index)|
sum += (coord - n[index]) ** 2
sum
end
end
10.times do
points = Array.new(10) do Array.new(ndim) do rand(-10.0 .. 10.0) end end
kd_tree = Kd::Tree(Float64).new(points)
target = Array.new(ndim) do rand(-11.0 .. 11.0) end
res = kd_tree.nearest(target,k)
sorted = points.sort_by do |p| distance.call(p,target) end.reverse!
(res - sorted[-k..]).should eq [] of Float64
end
end
end
I belive the bug is when the current node point is replaced, it should be the farthest point and currently
it is the first point.
The simplest solution is to sort the points
def nearest!(...)
# ...
if nearest.size < n
nearest << curr.pivot
else
nearest.sort_by! do |b| distance(b, query) end
dist_curr_query = distance(curr.pivot, query)
ix = nearest.rindex { |b| dist_curr_query < distance(b, query) }
nearest[ix] = curr.pivot if ix
end
# ...
end
But for larger values of n
the sorting and finding may have and impact on performance, an implementation with
a priority queue could have a positive impact on performance.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.