AttributeError: 'int' object has no attribute 'sqrt' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "F:\week1_220213459\HWdigits\class.py", line 51, in <module> predict_label = myKNN(train_data_set, train_labels, test_data_set[i], k=3) File "F:\week1_220213459\HWdigits\class.py", line 32, in myKNN distance = euclidean_distance(train_data_set[i], test_data) File "F:\week1_220213459\HWdigits\class.py", line 26, in euclidean_distance return np.sqrt(np.sum(np.square(x1 - x2))) TypeError: loop of ufunc does not support argument 0 of type int which has no callable sqrt method
时间: 2023-11-27 14:54:13 浏览: 113
Python3下错误AttributeError: ‘dict’ object has no attribute’iteritems‘的分析与解决
5星 · 资源好评率100%
这个错误的原因是你在使用 np.sqrt() 计算平方根时传入了一个整数,而整数类型没有 sqrt() 方法。你需要确保传入的参数是可以进行平方根计算的类型,例如浮点数。你可以将传入的整数转换为浮点数来解决此问题,如下所示:
```python
return np.sqrt(np.sum(np.square(x1 - x2)).astype(float))
```
这样可以将结果转换为浮点数类型,避免了整数类型没有 sqrt() 方法的问题。
阅读全文