def angleForPoint(center, point): radians = math.asin( euclidean_distance(point, (point[0], center[1])) / (euclidean_distance( center, point) if euclidean_distance(center, point) > 0 else 1)) angle = (180 * radians) / math.pi if point[0] < center[0]: if point[1] < center[1]: angle = 180 - angle else: angle += 180 else: if point[1] > center[1]: angle = 360 - angle return angle
def kNearestNeighbors(self, x_train, y_train, test, k): ''' parameters: x_train, y_train, test: single instance of x_test k: num of nearest neighbors retuns: a collections.Counter for k-nearest neighbors of of x_test array: Counter({1: n1, 0: n0}): n0+n1 = num_test points ''' # For uniform weights case distances, targets = list(), list() for i in range(len(x_train)): if self.distance_f == 'euclidean': dist = euclidean_distance(test, x_train[i, :]) if self.distance_f == 'manhattan': dist = manhattan_distance(test, x_train[i, :]) distances.append([dist, i]) distances = sorted(distances) for i in range(k): dist, index = distances[i][0], distances[i][1] targets.append([dist, y_train[index]]) # targets: contains k-nn each of the form [distance, neighbor class] return targets
def _calculate_distance(self, a, b, distance=None): if distance is None: distance = self.distance if distance == 'manhattan': return manhattan_distance(a, b) if distance == 'cosine': return cosine_distance(a, b) if distance == 'jaccard': return generalized_jaccard_distance(a, b) return euclidean_distance(a, b)
def hexagon_grid(center, radius, size, orientation=HEXAGON_HORIZONTAL): centers = [center] next_level = [center] while len(next_level) > 0: curr = next_level[0] next_level.remove(curr) start = 0 if orientation == HEXAGON_VERTICAL: start = 30 new_centers = _get_hexagon_layer(curr, radius, start) for nc in new_centers: flag = True for c in centers: if euclidean_distance(c, nc) < radius: flag = False break if flag and euclidean_distance(center, nc) < size: centers.append(nc) next_level.append(nc) return centers
def find_kneighbors(self, X, return_distance=False): if self.metric == 'euclidean': pairwise_matr = distances.euclidean_distance(X, self.data) else: pairwise_matr = distances.cosine_distance(X, self.data) if return_distance: return np.sort(pairwise_matr, axis=1)[:, :self.k], np.argsort(pairwise_matr, axis=1)[:, :self.k] else: return np.argsort(pairwise_matr, axis=1)[:, :self.k]
def computeNearestNeighbor(username, users, distance_algorithm='euclidean'): """ creates a sorted list of users based on their distance to username """ distances = [] for user in users: if user != username: if distance_algorithm == 'manhatten': distance = manhattan_distance(users[user], users[username]) elif distance_algorithm == 'euclidean': distance = euclidean_distance(users[user], users[username]) elif distance_algorithm == 'minkowski': distance = minkowski_distance(users[user], users[username], 5) distances.append((distance, user)) # sort based on distance -- closest first! distances.sort() return distances
def find_kneighbors(self, X, return_distance): """ params: * X - objects sample * return_distance - bool variable return values: * If return_distance == True: * tuple with two numpy array with size (X.shape[0], k), where: [i, j] elem of first array must be the distance between i-th object and his j-th nearest neighbour [i, j] elem of second array must be the index of j-th nearest neighbour to i-th object * If return_distance == False: * only second array """ if self.strategy != 'my_own': self.distances, \ self.neigh_idxs = self.model.kneighbors(X, n_neighbors=self.k) else: if self.metric == 'euclidean': self.distances = euclidean_distance(X, self.X_train) elif self.metric == 'cosine': self.distances = cosine_distance(X, self.X_train) elif self.metric == 'manhattan': dist = DistanceMetric.get_metric(self.metric) self.distances = dist.pairwise(X, self.X_train) elif self.metric == 'chebyshev': dist = DistanceMetric.get_metric(self.metric) self.distances = dist.pairwise(X, self.X_train) elif self.metric == 'minkowski': dist = DistanceMetric.get_metric(self.metric) self.distances = dist.pairwise(X, self.X_train) self.neigh_idxs = np.argsort(self.distances, axis=1)[:, :self.k] if return_distance: self.distances = self.distances[np.arange(self.distances.shape[0])[:, None], self.neigh_idxs] if return_distance: return self.distances, self.neigh_idxs return self.neigh_idxs
def find_kneighbors(self, X, return_distance): iter_num = np.size(X, 0) // self.test_block_size if (np.size(X, 0) % self.test_block_size): iter_num += 1 ind_list = list() if (return_distance): dist_list = list() for i in range(iter_num): ind_beg = self.test_block_size * i ind_end = self.test_block_size * (i + 1) if (self.strategy == 'my_own'): if (self.metric == 'euclidean'): distance_matrix = euclidean_distance( X[ind_beg:ind_end], self.X) elif (self.metric == 'cosine'): distance_matrix = cosine_distance(X[ind_beg:ind_end], self.X) k_ind_matrix = np.argsort(distance_matrix, axis=1)[:, :self.k] ind_list.append(k_ind_matrix) if (return_distance): dist_list.append(distance_matrix[ np.arange(np.size(k_ind_matrix, 0))[:, np.newaxis], k_ind_matrix]) else: if (return_distance): dist, ind = self.sklearn_knn.kneighbors( X[ind_beg:ind_end], n_neighbors=self.k, return_distance=return_distance) dist_list.append(dist) ind_list.append(ind) else: ind_list.append( self.sklearn_knn.kneighbors( X[ind_beg:ind_end], n_neighbors=self.k, return_distance=return_distance)) if (return_distance): return np.concatenate(dist_list), np.concatenate(ind_list) else: return np.concatenate(ind_list)
def find_kneighbors(self, X_test, return_distance): if self.strategy == "brute" or self.strategy == "ball_tree" or self.strategy == "kd_tree": distances, indeces = self.nbrs.kneighbors(X_test) else: if self.metric == 'euclidean': distances = euclidean_distance(X_test, self.X_train) elif self.metric == 'cosine': distances = cosine_distance(X_test, self.X_train) else: print("Wrong metric!") return indeces = np.argpartition(distances, self.k, axis=1) distances = np.take_along_axis(distances, indeces, axis=1) distances = np.delete(distances, np.s_[self.k:], axis=1) dist_index = np.delete(indeces, np.s_[self.k:], axis=1) ind = np.argsort(distances, axis=1) self.distances = np.take_along_axis(distances, ind, axis=1) self.indeces = np.take_along_axis(indeces, ind, axis=1) return self.distances, self.indeces if (return_distance): return distances, indeces else: return indeces