0

KNN model for recognizing handwritting below is the required code snippet.

def dist(x1,x2):
    return np.sqrt(sum((x1-x2)**2))
def KNN(X,Y,query,k=5):
    m=X.shape[0]
    vals=[]
    for i in range(m):
        #print(',,',end='' )
        vals.append((dist(query,X.iloc[i]),Y.iloc[i]))
    vals= sorted(vals)
    vals=vals[:k]
    new_vals,count=np.unique(np.array(vals),return_counts=True)
    index=count.argmax()
    pred=new_values[index]
    return pred

# input data is in the dataframe form , took input using pandas library
pred = []
for i in range(y_train.shape[0]):
    pred.append(KNN(x_train,x_label,y_train.iloc[i]))

ERROR:

ValueError                                Traceback (most recent call last)
<ipython-input-18-87f99a8bd125> in <module>
      1 pred = []
      2 for i in range(y_train.shape[0]):
----> 3     pred.append(KNN(x_train,x_label,y_train.iloc[i]))

<ipython-input-17-7d9c6763b87d> in KNN(X, Y, query, k)
      7         print(',,',end='' )
      8         vals.append((dist(query,X.iloc[i]),Y.iloc[i]))
----> 9     vals= sorted(vals)
     10     vals=vals[:k]
     11     new_vals,count=np.unique(np.array(vals),return_counts=True)

~\Anaconda3\lib\site-packages\pandas\core\generic.py in __nonzero__(self)
   1476         raise ValueError("The truth value of a {0} is ambiguous. "
   1477                          "Use a.empty, a.bool(), a.item(), a.any() or a.all()."
-> 1478                          .format(self.__class__.__name__))
   1479 
   1480     __bool__ = __nonzero__

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

  • Did you copy/paste that into a google search? This is a _really_ common issue and that's a basic debugging step – roganjosh Mar 16 '20 at 14:38
  • 1
    Does this answer your question? [Truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()](https://stackoverflow.com/questions/36921951/truth-value-of-a-series-is-ambiguous-use-a-empty-a-bool-a-item-a-any-o) – Brydenr Mar 16 '20 at 14:42
  • What kind of values are you expecting `vals` to contain, before you make the `sorted` call? What kind of values does it actually contain? – Karl Knechtel Mar 16 '20 at 15:02
  • @KarlKnechtel it is actually the list of tuples (int,int) and i want to sort it according to first integer. – robin singh Mar 16 '20 at 16:32
  • @roganjosh i have searched all the previous solutions but no solution solves my issue. – robin singh Mar 16 '20 at 16:34
  • @Brydenr i have searched all the previous solutions but no solution solves my issue. – robin singh Mar 16 '20 at 16:35
  • 1
    `... list of tuples (int,int)...` - The Error message implies `vals` is or contains Pandas Series' or numpy ndarray's - inspect `vals` in a try/except and make sure what it is. You may need to write a key function to sort your data. For a [mcve] you should include an example of the `vals` that needs to be sorted. – wwii Mar 16 '20 at 16:54

0 Answers0