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 11:54:13 浏览: 42
这个错误的原因是你在使用 np.sqrt() 计算平方根时传入了一个整数,而整数类型没有 sqrt() 方法。你需要确保传入的参数是可以进行平方根计算的类型,例如浮点数。你可以将传入的整数转换为浮点数来解决此问题,如下所示:
```python
return np.sqrt(np.sum(np.square(x1 - x2)).astype(float))
```
这样可以将结果转换为浮点数类型,避免了整数类型没有 sqrt() 方法的问题。
相关问题
AttributeError: 'int' object has no attribute 'sqrt' The above exception was the direct cause of the following exception: Traceback (most recent call last):
这个错误通常意味着你尝试对一个整数对象使用sqrt函数,但是sqrt函数只能用于浮点数。你需要将整数对象转换为浮点数对象,例如:
```python
import math
x = 25
y = math.sqrt(float(x))
print(y)
```
这将输出 `5.0`,其中我们使用float函数将x转换为浮点数对象。
AttributeError: int object has no attribute int
抱歉,根据提供的引用内容,无法回答“AttributeError: int object has no attribute int”的问题。但是,根据错误信息“AttributeError: 'int' object has no attribute 'encode'”和“AttributeError: 'int' object has no attribute 'endswith'”,可以得出结论:在代码中,将整数类型的变量当作字符串类型来使用了,而整数类型没有“encode”或“endswith”等字符串类型的属性,因此会出现“AttributeError”错误。
解决这个问题的方法是,检查代码中是否有将整数类型的变量当作字符串类型来使用的情况,如果有,需要将其转换为字符串类型后再进行操作。可以使用str()函数将整数类型的变量转换为字符串类型,例如:
```python
num = 123
str_num = str(num)
```