语法错误:在实现 k 最近邻分类器时无法为运算符赋值

发布于 2025-01-17 21:27:45 字数 1028 浏览 2 评论 0原文

*编辑以包括全错误堆栈,

请原谅我,如果这是一个愚蠢的问题,我是一个菜鸟。

我正在使用numpy在Python中创建一个K-Neart的邻居分类器。但是,当我尝试在CIFAR-10图像上运行KNN_CLASSIFIER.PREDECT()(被重塑为1D数组)时,我会遇到此错误。

File "<ipython-input-9-9df7a1ae9044>", line 1
    y-pred = knn.predict(x_ts, k=5)
                                   ^
SyntaxError: can't assign to operator

当我没有在分类器的较早版本中包括“ k”(预测中的方法)时,这并没有发生,所以我假设它与“ k”有关,但是我无法弄清楚我'我做错了。

这就是我写的:


   class knn_classifier:
   
     def __init__(self):
   
       pass
   
     def train(self, x, y):
   
       self.xtr = x
       self.ytr = y
   
     def predict(self, x, k=1):
   
       num_images = x.shape[0]
       y_pred = np.zeros(num_images, dtype=self.ytr.dtype)
       for i in range(num_images):
         distance = np.sum(np.abs(self.xtr - x[i,:]), axis=1)
         lowest = np.argsort(distance)
         lowest = lowest[:k]
         lowest_k = list(self.ytr[lowest])
         y_pred[i] = np.argmax(np.bincount(lowest_k))
       return y_pred  




*Edited to include full error stack

Forgive me if this is a silly question, i am a total noob.

I'm creating a k-nearest neighbor classifier in python using numpy. But when i try to run knn_classifier.predict() on CIFAR-10 images (reshaped into 1-D arrays), i get this error.

File "<ipython-input-9-9df7a1ae9044>", line 1
    y-pred = knn.predict(x_ts, k=5)
                                   ^
SyntaxError: can't assign to operator

This didn't happen when i hadn't included 'k'(method varibale in predict) in an earlier version of the classifier, so i'm assuming its related to 'k', but i can't figure out what i'm doing wrong.

This is what I wrote:


   class knn_classifier:
   
     def __init__(self):
   
       pass
   
     def train(self, x, y):
   
       self.xtr = x
       self.ytr = y
   
     def predict(self, x, k=1):
   
       num_images = x.shape[0]
       y_pred = np.zeros(num_images, dtype=self.ytr.dtype)
       for i in range(num_images):
         distance = np.sum(np.abs(self.xtr - x[i,:]), axis=1)
         lowest = np.argsort(distance)
         lowest = lowest[:k]
         lowest_k = list(self.ytr[lowest])
         y_pred[i] = np.argmax(np.bincount(lowest_k))
       return y_pred  




如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

披肩女神 2025-01-24 21:27:45

这只是一个错字。您用破折号而不是下划线编写了“y-pred”,Python 将其解释为操作 y 减去 pred

This is just a typo. You wrote "y-pred" with a dash rather than an underscore, which Python interprets as the operation y minus pred.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文