def knn_visual(k, locationid, model, database, this_vector=None): nearest = {} if not this_vector: this_vector = Vectorizer.visual_vector(locationid, database, model) others = database.get_location_ids() others.remove(locationid) # Get distance to each other vecctor and add to nearest if it is less than the # distance to an existing vector. for other in others: other_vector = Vectorizer.visual_vector(other, database, model) distance = Distance.l_p_distance(3, this_vector, other_vector, positional=True) if len(nearest) < k: largest_key, largest_best = None, inf else: largest_key, largest_best = max(nearest.items(), key=itemgetter(1)) if distance < largest_best: if largest_key: nearest.pop(largest_key) nearest[other] = distance return nearest
def visual_sim_contribution(this_vector, ids, database, model, k=3): other_vectors = [ Vectorizer.visual_vector(locid, database, model) for locid in ids ] return Neighbor.similarity_contribution(this_vector, other_vectors, k, positional=True)
def nearest_visual(self, *args): """ arg[0] = locationid arg[1] = model (CM, CM3x3, CN, CN3x3, CSD, GLRLM, GLRLM3x3, HOG, LBP, LBP3x3, ALL) arg[2] = k """ if not self.database: print("[ERROR] The database must be loaded for this action.") return if not len(args) == 3: print("[ERROR] Expected three arguments but got " + str(len(args)) + ".") print("\targ = " + str(args)) # Get the first argument try: k = int(args[2]) except: print("[ERROR] K Value provided is invalid.") print("\tk = " + str(args[2])) return # Get the model to use. We do this before the item as it is easier # to differentiate valid from invalid model = args[1] if not model in self.valid_vis_models: print("[ERROR] Model Type value provided was invalid.") print("\tModel Type = " + str(args[1])) return try: locationid = int(args[0]) except: print("[ERROR] The ID specified was not valid") print("\tID = " + str(locationid) + "; Model = " + model) return start = time() if model == 'ALL': this_vector = Vectorizer.visual_vector_multimodel(locationid, self.database, self.valid_vis_models) nearest = Neighbor.knn_visual_all(k, locationid, self.valid_vis_models, self.database, this_vector = this_vector) else: # get vector representing item associated w/ id this_vector = Vectorizer.visual_vector(locationid, self.database, model) nearest = Neighbor.knn_visual(k, locationid, model, self.database, this_vector=this_vector) contribs = Neighbor.visual_sim_contribution(this_vector, nearest.keys(), self.database, model, k=3) print("The Visual Descriptor Nearest Neighbor took " + str(time() - start)) print(str(k) + " Nearest Neighbors:") for i, (an_id, distance) in enumerate(nearest.items()): print('\t' + str(i) + ". " + str(an_id) + "; Distance = " + str(distance)) print('Top 3 Image Pairs:') for i, item in enumerate(contribs): print('\t' + str(i) + '. ' + str(item))