def fastmap(problem, true_population): """ Fastmap function that projects all the points on the principal component :param problem: Instance of the problem :param population: Set of points in the cluster population :return: """ def list_equality(lista, listb): for a, b in zip(lista, listb): if a != b: return False return True from random import choice from euclidean_distance import euclidean_distance decision_population = [pop.decisionValues for pop in true_population] one = choice(decision_population) west = furthest(one, decision_population) east = furthest(west, decision_population) c = euclidean_distance(east, west) tpopulation = [] for one in decision_population: a = euclidean_distance(one, west) b = euclidean_distance(one, east) tpopulation.append([one, projection(a, b, c)]) for tpop in tpopulation: for true_pop in true_population: if list_equality(tpop[0], true_pop.decisionValues): true_pop.x = tpop[-1] temp_list = sorted(true_population, key=lambda pop: pop.x) return true_population, temp_list[0], temp_list[-1]
def scores(individual, stars): cols = len(stars[0].east.fitness.fitness) temp = -1e32 selected = -1 individual.anyscore = -1e30 for count, star in enumerate(stars): try: a = euclidean_distance(individual.decisionValues, star.east.decisionValues) b = euclidean_distance(individual.decisionValues, star.west.decisionValues) c = euclidean_distance(star.east.decisionValues, star.west.decisionValues) x = (a**2 + c**2 - b**2) / (2*c) y = (a**2 - x**2)**0.5 r = len(stars) - 1 # Number of poles - midpoint diff = euclidean_distance(star.east.fitness.fitness, star.west.fitness.fitness) temp_score = ((a/b) * diff/(y**2)) except: temp_score = 1e32 if temp < temp_score: temp = temp_score selected = count assert(selected > -1), "Something's wrong" individual.anyscore = temp return selected, individual
def is_near_palindrome(word, lo, hi): d1 = euclidean_distance(word[0], word[4]) d2 = euclidean_distance(word[1], word[3]) if ((d1 + d2) > lo and (d1 + d2) <= hi): return True return False
def one_test(): dimension = random.randint(1, 100) first = [random.randint(-100, 100) for _ in xrange(dimension)] second = [random.randint(-100, 100) for _ in xrange(dimension)] from scipy.spatial import distance try: assert(round(euclidean_distance(first, second), 6) == round(distance.euclidean(first, second),6)), "Mistakes" \ " discovered" except: print "First: ", first print "Second: ", second print "My: ", euclidean_distance(first, second) print "Their: ", distance.euclidean(first, second) return False return True
def find_extreme(one, population): temp = [] for individual in population: temp_distance = euclidean_distance(one.decisionValues, individual.decisionValues), individual assert(temp_distance > 1), "Something's wrong" temp.append([temp_distance, individual]) return sorted(temp, key=lambda x: x[0], reverse=True)[0][1]
def furthest(individual, population): from euclidean_distance import euclidean_distance distances = sorted([[euclidean_distance(individual, pop), pop] for pop in population], key=lambda x: x[0], reverse=True) return distances[0][-1]
def create_distance_matrix(population): global distance_matrix weights = [pop.weight for pop in population] distance_matrix = [[[0, i] for i, _ in enumerate(xrange(len(weights)))] for _ in xrange(len(weights))] for i in xrange(len(weights)): for j in xrange(len(weights)): distance_matrix[i][j][0] = euclidean_distance(weights[i], weights[j])
def generate_directions(problem): def gen(point): r = sum([pp**2 for pp in point])**0.5 return [round(p/r,3) for p in point] coordinates = [gen([random.uniform(0, 1) for _ in xrange(len(problem.decisions))]) for _ in xrange(jmoo_properties.ANYWHERE_POLES * 2)] for co in coordinates: assert(int(round(euclidean_distance(co, [0 for _ in xrange(len(problem.decisions))]))) == 1), "Something's wrong" return coordinates
def IGD(approximation_points, original_points): summ = 0 for o in original_points: min_distance = 1e32 for a in approximation_points: min_distance = min(min_distance, euclidean_distance(o, a)) summ += min_distance return summ/len(original_points)
def fastmap(problem, population): """ Fastmap function that projects all the points on the principal component :param problem: Instance of the problem :param population: Set of points in the cluster population :return: """ from random import choice from euclidean_distance import euclidean_distance one = choice(population) west = furthest(one, population) east = furthest(west, population) c = euclidean_distance(east, west) tpopulation = [] for one in population: a = euclidean_distance(one, west) b = euclidean_distance(one, east) tpopulation.append([one, projection(a, b, c)]) population = [pop[0] for pop in sorted(tpopulation, key=lambda l: l[-1])] return population, east, west
def furthest(one, all_members): ret = None ret_distance = -1 * 1e10 for member in all_members: if equal_list(one, member) is True: continue else: temp = euclidean_distance(one, member) if temp > ret_distance: ret = member ret_distance = temp return ret
def get_neighbors(training_set, test_instance, k): distances = [] length = len(test_instance) - 1 for x in range(len(training_set)): dist = ed.euclidean_distance(test_instance, training_set[x], length) distances.append((training_set[x], dist)) distances.sort(key=operator.itemgetter(1)) neighbors = [] for x in range(k): neighbors.append(distances[x][0]) return neighbors
def closest_vertex(self, lat, long): """ Returns the id of the closest vertex to the specified lat and long >>> s = Server() >>> s.vertex_locations[29577354] = (5343099.6,-11349133.1) >>> s.vertex_locations[29770958] = (5357142.9,-11362729.9) >>> s.closest_vertex(5343099,-11349133) 29577354 """ coords = (lat, long) closest = min(self.vertex_locations.items(), key=lambda x: euclidean_distance(coords, x[1])) return closest[0]
def find_k_nearest_neighbors(test_point, train_data, k): """Function that finds the k nearest neighbors of a test point""" #make list of all euclidean distances distances = [euclidean_distance(test_point, x) for x in train_data] distances = np.array(distances) #get indices of k nearest neighbors distances = np.argsort(distances)[:k] #initialize k_nearest_neighbors and then fill it up k_nearest_neighbors = train_data[distances[0]] for i in range(1, len(distances)): k_nearest_neighbors = np.append(k_nearest_neighbors, \ train_data[distances[i]], 0) return k_nearest_neighbors
def scores2(individual, stars): cols = len(stars[0].east.fitness.fitness) temp = -1e32 selected = -1 individual.anyscore = -1e30 nearest_contours = [] for count, star in enumerate(stars): try: a = euclidean_distance(individual.decisionValues, star.east.decisionValues) b = euclidean_distance(individual.decisionValues, star.west.decisionValues) c = euclidean_distance(star.east.decisionValues, star.west.decisionValues) x = (a**2 + c**2 - b**2) / (2*c) y = (a**2 - x**2)**0.5 r = len(stars) - 1 # Number of poles - midpoint diff = euclidean_distance(star.east.fitness.fitness, star.west.fitness.fitness) temp_score = ((a/b) * diff/(y**2)) except: temp_score = 1e32 nearest_contours.append([count, temp_score]) return [x[0] for x in sorted(nearest_contours, key=lambda item:item[-1], reverse=True)[:6]], individual
def find_poles2(problem, population): def midpoint(population): def median(lst): import numpy return numpy.median(numpy.array(lst)) mdpnt = [] for dec in xrange(len(population[0].decisionValues)): mdpnt.append(median([pop.decisionValues[dec] for pop in population])) assert(len(mdpnt) == len(population[0].decisionValues)), "Something's wrong" # print mdpnt return jmoo_individual(problem, mdpnt, None) def generate_directions(problem): def gen(point): r = sum([pp**2 for pp in point])**0.5 return [round(p/r,3) for p in point] coordinates = [gen([random.uniform(0, 1) for _ in xrange(len(problem.decisions))]) for _ in xrange(jmoo_properties.ANYWHERE_POLES * 2)] for co in coordinates: assert(int(round(euclidean_distance(co, [0 for _ in xrange(len(problem.decisions))]))) == 1), "Something's wrong" return coordinates # find midpoint mid_point = midpoint(population) # find directions directions = generate_directions(problem) # draw a star poles =[] for direction in directions: mine = -1e32 temp_pole = None for pop in population: transformed_dec = [(p-m) for p, m in zip(pop.decisionValues, mid_point.decisionValues)] y = perpendicular_distance(direction, transformed_dec) c = euclidean_distance(transformed_dec, [0 for _ in xrange(len(problem.decisions))]) # print c, y if mine < (c-y): mine = c - y temp_pole = pop poles.append(temp_pole) stars = rearrange(problem, mid_point, poles) return stars
def cost_distance(self, e): """ cost_distance returns the straight-line distance between the two vertices at the endpoints of the edge e. >>> s = Server() >>> s.vertex_locations[29577354] = (400,-400) >>> s.vertex_locations[29770958] = (500,-500) >>> tcompare(100 * math.sqrt(2), s.cost_distance((29577354, 29770958))) True """ #print('cost_distance: e = {}'.format(e)) v1 = self.vertex_locations[e[0]] v2 = self.vertex_locations[e[1]] #print('cost_distance: v1 = {}; v2 = {}'.format(v1, v2)) return euclidean_distance(v1, v2)
def kNN_classification(test_point, in_features, targets, k): distances = euclidean_distance(test_point, in_features) (val, ind) = tf.nn.top_k(-distances, k) # find closest neighbours in training set candidates = tf.gather( tf.constant(targets), ind) # Find the classifications for these neighbours length = tf.shape(candidates)[0] class_list = [] count_list = [] # Count the frequency of nearest neighbours and put them into matrices # (reduced class list and count list) for i in range(0, length.eval()): (temp_class, __, temp_count) = tf.unique_with_counts(candidates[i]) padding = tf.concat( [tf.constant([0]), tf.constant([k]) - tf.shape(temp_class)], 0) class_list.append(tf.pad(temp_class, [padding])) count_list.append(tf.pad(temp_count, [padding])) red_class_list = tf.stack(class_list) red_count_list = tf.stack(count_list) # Create an iterator for each test_point iterator = tf.cast(tf.linspace(0., length.eval() - 1., length.eval()), tf.int64) iterator = tf.reshape(iterator, [length, 1]) # Combine the iterator with the indices of the highest counts in the # reduced count list (red_count_list) count_loc = tf.concat( [iterator, tf.reshape(tf.argmax(red_count_list, 1), [length, 1])], 1) outputs = tf.gather_nd(red_class_list, count_loc) return (outputs, ind)
def classify(self, features): """ classify a new set of features :param features: 1D numpy.ndarray of features :return: a tagging of the given features (1 or 0) """ # iterate through train data set and obtain the euclidean # distances between the sample we want to classify and every sample in the train data set. distances = np.asarray([ euclidean_distance(features, train_feature) for train_feature in self._train_features.tolist() ]) # partition the distances s.t k'th element in his final location if we were sorting the array # (all elements before it are smaller or equal) # idx contains the indexes of the re-ordered array idx = np.argpartition(distances, self._k) # get indexes of first k smallest distances (related to k nearest nearest neighbors) k_minimal_distances_idx = idx[:self._k] # get labels of k nearest neighbors k_minimal_distances_labels = self._train_labels[ k_minimal_distances_idx] # get the majority vote count_label_zero = 0 count_label_one = 0 for label in k_minimal_distances_labels: if label == 0: count_label_zero += 1 if label == 1: count_label_one += 1 if count_label_zero > count_label_one: return 0 else: return 1
from tag_list import critics from euclidean_distance import euclidean_distance from pearson_corretation import pearson_corretation from top_match import topMatch from film_recommendation import getRecommendation from film_relation import filmRelate, watchWith print euclidean_distance(critics, 'Lisa Rose', 'Gene Seymour') print pearson_corretation(critics, 'Lisa Rose', 'Gene Seymour') print topMatch(critics, 'Toby', pearson_corretation) print getRecommendation(critics, 'Toby', pearson_corretation) print filmRelate(critics, 'Superman Returns', pearson_corretation) print watchWith(critics, 'Just My Luck', pearson_corretation)
def fastmap(problem, true_population): """ Fastmap function that projects all the points on the principal component :param problem: Instance of the problem :param population: Set of points in the cluster population :return: """ def list_equality(lista, listb): for a, b in zip(lista, listb): if a != b: return False return True from random import choice from euclidean_distance import euclidean_distance decision_population = [pop.decisionValues for pop in true_population] one = choice(decision_population) west = furthest(one, decision_population) east = furthest(west, decision_population) west_indi = jmoo_individual(problem,west, None) east_indi = jmoo_individual(problem,east, None) west_indi.evaluate() east_indi.evaluate() # Score the poles n = len(problem.decisions) weights = [] for obj in problem.objectives: # w is negative when we are maximizing that objective if obj.lismore: weights.append(+1) else: weights.append(-1) weightedWest = [c * w for c, w in zip(west_indi.fitness.fitness, weights)] weightedEast = [c * w for c, w in zip(east_indi.fitness.fitness, weights)] westLoss = loss(weightedWest, weightedEast, mins=[obj.low for obj in problem.objectives], maxs=[obj.up for obj in problem.objectives]) eastLoss = loss(weightedEast, weightedWest, mins=[obj.low for obj in problem.objectives], maxs=[obj.up for obj in problem.objectives]) # Determine better Pole if eastLoss < westLoss: SouthPole, NorthPole = east_indi, west_indi else: SouthPole, NorthPole = west_indi, east_indi east = SouthPole.decisionValues west = NorthPole.decisionValues c = euclidean_distance(east, west) tpopulation = [] for one in decision_population: a = euclidean_distance(one, west) b = euclidean_distance(one, east) tpopulation.append([one, projection(a, b, c)]) for tpop in tpopulation: for true_pop in true_population: if list_equality(tpop[0], true_pop.decisionValues): true_pop.x = tpop[-1] temp_list = sorted(true_population, key=lambda pop: pop.x) ranklist = [t.id for t in temp_list] return true_population, ranklist, temp_list[0], temp_list[-1]
left_eye = [[(i.x, i.y) for i in eye] for eye in left_eye] left_eye = left_eye[0][0] left_eye_x = left_eye[0] left_eye_y = left_eye[1] if left_eye_y < right_eye_y: point_3rd = (right_eye_x, left_eye_y) direction = -1 #rotate same direction to clock print("rotate to clock direction") else: point_3rd = (left_eye_x, right_eye_y) direction = 1 #rotate inverse direction of clock print("rotate to inverse clock direction") print("rotate to inverse clock direction") #Thread 2,3,4 t2 = threading.Thread(target=lambda e, arg1, arg2: e.put( euclidean_distance.euclidean_distance(arg1, arg2)), args=(a, left_eye, point_3rd)) t3 = threading.Thread(target=lambda e, arg1, arg2: e.put( euclidean_distance.euclidean_distance(arg1, arg2)), args=(b, right_eye, left_eye)) t4 = threading.Thread(target=lambda e, arg1, arg2: e.put( euclidean_distance.euclidean_distance(arg1, arg2)), args=(c, right_eye, point_3rd)) t2.start() threads_list.append(t2) t3.start() threads_list.append(t3) t4.start() threads_list.append(t4) for t in threads_list: t.join()
good = SouthPole.decisionValues[attr] bad = NorthPole.decisionValues[attr] dec = problem.decisions[attr] # Find direction to mutate (Want to mutate towards good pole) if me > good: d = -1 if me < good: d = +1 if me == good: d = 0 row.decisionValues[attr] = min( dec.up, max(dec.low, (me + me * g * d) * Configurations["GALE"]["DELTA"])) # Project the Mutant a = euclidean_distance(NorthPole.decisionValues, row.decisionValues) b = euclidean_distance(SouthPole.decisionValues, row.decisionValues) c = euclidean_distance(SouthPole.decisionValues, NorthPole.decisionValues) x = (a**2 + c**2 - b**2) / (2 * c + 0.00001) # print abs(cx-x), (cx + (g * configuration["GALE"]["GAMMA"])) if abs(x - cx) > (g * Configurations["GALE"]["GAMMA"] ) or problem.evalConstraints( row.decisionValues): # reject it # print "reject it", i row = copy row.x = x else: # print "Changed Number: ", count, g * Configurations["GALE"]["GAMMA"]
# just some naming shortcuts me = row.decisionValues[attr] good = SouthPole.decisionValues[attr] bad = NorthPole.decisionValues[attr] dec = problem.decisions[attr] # Find direction to mutate (Want to mutate towards good pole) if me > good: d = -1 if me < good: d = +1 if me == good: d = 0 row.decisionValues[attr] = min(dec.up, max(dec.low, (me + me * g * d) * Configurations["GALE"]["DELTA"])) # Project the Mutant a = euclidean_distance(NorthPole.decisionValues, row.decisionValues) b = euclidean_distance(SouthPole.decisionValues, row.decisionValues) c = euclidean_distance(SouthPole.decisionValues, NorthPole.decisionValues) x = (a ** 2 + c ** 2 - b ** 2) / (2 * c + 0.00001) # print abs(cx-x), (cx + (g * configuration["GALE"]["GAMMA"])) if abs(x - cx) > (g * Configurations["GALE"]["GAMMA"]) or problem.evalConstraints(row.decisionValues): # reject it # print "reject it", i row = copy row.x = x else: # print "Changed Number: ", count, g * Configurations["GALE"]["GAMMA"] count = count + 1 # print "Before: ", copy.decisionValues # print "After : ", row.decisionValues # print "Difference: ", euclidean_distance(copy.decisionValues, row.decisionValues)
def fastmap(problem, true_population): """ Fastmap function that projects all the points on the principal component :param problem: Instance of the problem :param population: Set of points in the cluster population :return: """ def list_equality(lista, listb): for a, b in zip(lista, listb): if a != b: return False return True from random import choice from Techniques.euclidean_distance import euclidean_distance decision_population = [pop.decisionValues for pop in true_population] one = choice(decision_population) west = furthest(one, decision_population) east = furthest(west, decision_population) west_indi = jmoo_individual(problem, west, None) east_indi = jmoo_individual(problem, east, None) west_indi.evaluate() east_indi.evaluate() for true_pop in true_population: if list_equality(true_pop.decisionValues, west_indi.decisionValues): true_pop.fitness.fitness = west_indi.fitness.fitness if list_equality(true_pop.decisionValues, east_indi.decisionValues): true_pop.fitness.fitness = east_indi.fitness.fitness # Score the poles n = len(problem.decisions) weights = [] for obj in problem.objectives: # w is negative when we are maximizing that objective if obj.lismore: weights.append(+1) else: weights.append(-1) weightedWest = [c * w for c, w in zip(west_indi.fitness.fitness, weights)] weightedEast = [c * w for c, w in zip(east_indi.fitness.fitness, weights)] westLoss = loss(weightedWest, weightedEast, mins=[obj.low for obj in problem.objectives], maxs=[obj.up for obj in problem.objectives]) eastLoss = loss(weightedEast, weightedWest, mins=[obj.low for obj in problem.objectives], maxs=[obj.up for obj in problem.objectives]) # Determine better Pole if eastLoss < westLoss: SouthPole, NorthPole = east_indi, west_indi else: SouthPole, NorthPole = west_indi, east_indi east = SouthPole.decisionValues west = NorthPole.decisionValues c = euclidean_distance(east, west) tpopulation = [] for one in decision_population: a = euclidean_distance(one, west) b = euclidean_distance(one, east) tpopulation.append([one, projection(a, b, c)]) for tpop in tpopulation: for true_pop in true_population: if list_equality(tpop[0], true_pop.decisionValues): true_pop.x = tpop[-1] temp_list = sorted(true_population, key=lambda pop: pop.x) return temp_list