I have a data set of discrete points over a 2D grid with dimensions of 4x4, each have a given x and y coordinate such as:
x_coord, y_coord
0.5 2.1
0.8 3.2
3.3 1.1
2.8 0.6
1.9 1.0
I want to step through each grid point to find the distance to the third nearest neighbor. So I want to know the distance to the third nearest neighbor for the following coordinates:
[0,0]
[0,1]
[0,2]
[0,3]
[1,0]
[1,1]
[1,2]
[1,3]
[2,0]
[2,1]
[2,2]
[2,3]
[3,0]
[3,1]
[3,2]
[3,3]
I think that my trouble is coming from how to step through a grid and do the calculation for the distance to the nearest neighbor. I am just learning python so my experience with nesting for loops is very limited, but my guess is that's what I need here.
So far I have
from sklearn.neighbors import NearestNeighbors
import numpy as np
x=[0.5,0.8,3.3,2.8,1.9]
y=[2.1,3.2,1.1,0.6,1.0]
myarray = np.array([x,y])
myarray_trans = np.transpose(myarray)
myarray_trans
nbrs = NearestNeighbors(n_neighbors=3, algorithm='ball_tree').fit(myarray_trans)
distances, indices = nbrs.kneighbors(myarray_trans)
Now using this as my training set I need to step through the full grid to find the distance to the third nearest neighbor from the discrete list. I have tried this:
for i in range(0,4):
for j in range(0,4):
distances2[i,j], indices[i,j] = nbrs.kneighbors([i,j])
I get an error that says "Expected 2D array, got 1D array instead: array=[0 0]
I will have to do this on a bigger data set with a grid of something more like the size of 500 x 500 so this is an example.