Getting Error -The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()


pred = knn(x_train , x_train ,x_test[0])
print(int(pred))

I am getting this error :-

The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

While other numbers are being printed. except the zeroth one or maybe others too which I haven’t tried.

hey @aditrisriv ,
can you please one thing before this line.
just print vals , and share with me a screenshot of that output.

Thank You :slightly_smiling_face:.

code for KNN ->
def dis(x1,x2):
return np.sqrt(sum((x1-x2)**2))

def knn(X,Y,query,k=5):
val = []
m = X.shape[0]

for i in range(m):
    d = dis(query , X[i])
    val.append((d,Y[i]))
val = sorted(val)
val=val[:k]
val=np.array(val)
print(val)

new_val = np.unique(val[:,1],return_counts=True)
print(new_val)

max_freq_index = new_val[1].argmax()
pred = new_val[0][max_freq_index]

return pred

While others are working but 0th index is not.
@prashant_ml where should I print vals ? I have done it in KNN function.

You were getting the error in this only ,right ?

I am getting error for 0th index only…

Kindly share me your code.

hey @aditrisriv ,
There is just a small typo.
You are doing wrong
knn(x_train, x_train, x_test[0])
here are you providing targets also as x_train , instead it should be y_train , the way it is in other function calls.
just change it to
knn(x_train, y_train, x_test[0])

It will work fine.

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.

1 Like

Python Pandas follows the numpy convention of raising an error when you try to convert something to a bool. This happens in a if or when using the boolean operations, and, or, or not. It is not clear what the result of.

example

5 == pd.Series([12,2,5,10])

The result you get is a Series of booleans, equal in size to the pd.Series in the right hand side of the expression. So, you get an error. The problem here is that you are comparing a pd.Series with a value, so you’ll have multiple True and multiple False values, as in the case above. This of course is ambiguous, since the condition is neither True or False. You need to further aggregate the result so that a single boolean value results from the operation. For that you’ll have to use either any or all depending on whether you want at least one (any) or all values to satisfy the condition.

(5 == pd.Series([12,2,5,10])).all()
# False

or

(5 == pd.Series([12,2,5,10])).any()
# True