def predict(self, x): """Predict x array :param x: data with coordinates to be predicted :type: list, tuple, np.array :example: [[1, 2], [2, 3], [3, 4], [4, 5]] :return: x predicts :type: list :example: [[1], [0], [0], [1]] """ predicts = [] for coordinates in x: predict_point = Point(coordinates) # euclidean distance from predict_point to all in self._fit_data distances = [] for data_point, data_label in self._fit_data: distances.append((predict_point.distance(data_point), data_label)) # k points with less distances distances = sorted(distances, key=itemgetter(0))[:self.k] # label of k points with less distances predicts.append(list(max(distances, key=itemgetter(1))[1])) return predicts
def pairwise_distances(points, centroids): """Create pairwise distance between points and the centroids :param points: :type: list, tuple, np.array :example: [[1, 2], [2, 3], [3, 4], [4, 5]] :param centroids: :type: list, tuple, np.array :example: [[0, 0], [3, 3]] :return: distance :type: list :example: [[14.866068747318506, 1.0, 0.0], [14.212670403551895, 1.4142135623730951, 1.0], [14.142135623730951, 0.0, 1.0], ... ] """ distances = list() for index, point in enumerate(points): distances.append([]) point = Point(point) for centroid in centroids: centroid = Point(centroid) distance = centroid.distance(point) distances[index].append(distance) return distances