In this lab you are asked to complete the provided code so that
the algorithm calculates "n" nearest neighbours of a given vector.
The point of this exercise it to provide you with an example of an
algorithm, get you to think about how to divide a complex task into
a number of smaller, more manageable steps and to show you an
example of how different data types might be used for different
purposes.
A vector in this context is a point in 3 dimensional
space (x,y,z). It could be used to represent a location coordinate
e.g. on a google map with altitude. You can imagine each vector
representing the location of an object and the algorithm is trying
to find a number, "n", nearest objects to the object of
interest.
Some definitions:
from math import sqrt
# Function: calculates the distance between two input vectors
def vec_distance(vector1, vector2):
distance = 0.0
for cntr in range(len(vector1)-1):
distance += (vector1[cntr] -
vector2[cntr])**2
return sqrt(distance)
# Helper function: returns distance, from position 1 of
distance_tuple
def get_distance( distance_tuple ):
return distance_tuple[1]
# Function: sorts list of distances
def sort_(distances):
distances.sort(key=get_distance)
return distances
# Return the required number of nearest neighbours
def get_neighbours(data, test_vector, num_neighbours):
#** Your code goes here
pass # remove this
if __name__ == '__main__':
dataset = [
[2.7810836,2.550537003,0.5],
[1.465489372,2.362125076,1.54],
[3.396561688,4.400293529,0.72],
[1.38807019,1.850220317,1.65],
[3.06407232,3.005305973,0.98],
[7.627531214,2.759262235,1.2],
[5.332441248,2.088626775,1.1],
[6.922596716,1.77106367,0.8],
[8.675418651,-0.242068655,1.7],
[7.673756466,3.508563011,0.76]]
number_of_neighbours = int(input())+1
index_of_vector = int(input())
neighbours = get_neighbours(dataset,
dataset[index_of_vector], number_of_neighbours)
if neighbours:
for neighbour in neighbours:
print(neighbour)
In this lab you are asked to complete the provided code so that the algorithm calculates "n" nearest neighbours of a giv
-
- Site Admin
- Posts: 899603
- Joined: Mon Aug 02, 2021 8:13 am