我在YouTube上观看了Google开发者关于机器学习的教程视频后,编写了这段代码,并尝试在Jupyter Python3笔记本中运行。链接:https://www.youtube.com/watch?v=AoeEHqVSNOw
我无法得到结果,因为我遇到了这个错误 ‘<‘ not supported between instances of ‘function’ and ‘function’
from scipy.spatial import distancedef euc(a,b): return distance.euclideanclass KNN(): def fit(self,X_train,y_train): self.X_train=X_train self.y_train=y_train def predict(self,X_test): predictions=[] for row in X_test: label=self.closest(row) predictions.append(label) return predictions def closest(self,row): best_dist=euc(row, self.X_train[0]) best_index=0 for i in range(1,len(self.X_train)): dist=euc(row,self.X_train[i]) if (dist < best_dist): # <--error here best_dist=dist best_index=i return self.y_train[best_index]#KNeighbors Classifiermy_classifier=KNN()my_classifier.fit(X_train,y_train)predictions=my_classifier.predict(X_test)from sklearn.metrics import accuracy_scoreprint(accuracy_score(y_test,predictions))
回答:
def euc(a,b): return distance.euclidean
您的函数 euc
返回的是 函数 distance.euclidean
的引用。
您应该 调用 它:
def euc(a,b): return distance.euclidean(a, b)