defpredict(self, kicks, kisses): for i inrange(len(self.train_set)): self.train_set[i][0] = np.sqrt((kicks - self.train_set[i][1]) ** 2 + (kisses - self.train_set[i][2]) ** 2) self.train_set.sort() votes = {} for i inrange(self.k): if self.train_set[i][3] in votes: votes[self.train_set[i][3]] += 1 else: votes[self.train_set[i][3]] = 1 max = 0 max_type = -1 for k in votes.keys(): if votes[k] > max: max = votes[k] max_type = k return max_type
if __name__ == "__main__": # k为3的kNN算法 predictor = kNN(3) # 从文件中读取训练集 withopen('F:\\Desktop\\test.txt', 'r') as file: content = file.read().splitlines() for i inrange(len(content)): info = content[i].split('\t') predictor.feed(int(info[1]), int(info[2]), int(info[3])) # 从控制台读取亟待预测的数据 kick = int(input("Please type count of kicks within this movie: ")) kiss = int(input("Please type count of kisses within this movie: ")) if predictor.predict(kick, kiss) == 1: print("The result of the predicted type of this movie is ", "Romance") else: print("The result of the predicted type of this movie is ", "Action")