语法错误:在实现 k 最近邻分类器时无法为运算符赋值
*编辑以包括全错误堆栈,
请原谅我,如果这是一个愚蠢的问题,我是一个菜鸟。
我正在使用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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这只是一个错字。您用破折号而不是下划线编写了“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
minuspred
.