pythontensorflowclassificationtensorkaggle

InvalidArgumentError: `predictions` contains negative values


I was trying to run the Tensorflow Audio classification code following the article of tensorflow. When I ran the following python code after finishing all above cells orderly:

Code:

confusion_mtx = tf.math.confusion_matrix(y_true, y_pred)
plt.figure(figsize=(10, 8))
sns.heatmap(confusion_mtx,
            xticklabels=label_names,
            yticklabels=label_names,
            annot=True, fmt='g')
plt.xlabel('Prediction')
plt.ylabel('Label')
plt.show()

I am getting the following error in both my Kaggle and Jupyter Notebook. How can I solve it and what is the real cause for prediction values to be negative?

Error:

---------------------------------------------------------------------------
InvalidArgumentError                      Traceback (most recent call last)
Cell In[32], line 1
----> 1 confusion_mtx = tf.math.confusion_matrix(y_true, y_pred)
      2 plt.figure(figsize=(10, 8))
      3 sns.heatmap(confusion_mtx,
      4             xticklabels=label_names,
      5             yticklabels=label_names,
      6             annot=True, fmt='g')

File /opt/conda/lib/python3.10/site-packages/tensorflow/python/util/traceback_utils.py:153, in filter_traceback.<locals>.error_handler(*args, **kwargs)
    151 except Exception as e:
    152   filtered_tb = _process_traceback_frames(e.__traceback__)
--> 153   raise e.with_traceback(filtered_tb) from None
    154 finally:
    155   del filtered_tb

File /opt/conda/lib/python3.10/site-packages/tensorflow/python/ops/check_ops.py:487, in _binary_assert(sym, opname, op_func, static_func, x, y, data, summarize, message, name)
    484   if message is not None:
    485     data = [message] + list(data)
--> 487   raise errors.InvalidArgumentError(
    488       node_def=None,
    489       op=None,
    490       message=('\n'.join(_pretty_print(d, summarize) for d in data)))
    492 else:  # not context.executing_eagerly()
    493   if data is None:

InvalidArgumentError: `predictions` contains negative values.  
Condition x >= 0 did not hold element-wise:
x (shape=(832, 8) dtype=int64) = 
['-10', '-4', '-1', '...']

Solution

  • I forgot to execute following cell in the code,

    y_pred = tf.argmax(y_pred, axis=1)
    y_true = tf.concat(list(test_spectrogram_ds.map(lambda s,lab: lab)), axis=0)
    

    Before running the code:

    confusion_mtx = tf.math.confusion_matrix(y_true, y_pred)
    plt.figure(figsize=(10, 8))
    sns.heatmap(confusion_mtx,
                xticklabels=label_names,
                yticklabels=label_names,
                annot=True, fmt='g')
    plt.xlabel('Prediction')
    plt.ylabel('Label')
    plt.show()
    

    So adding the cell solved the issue.