I'm trying to build a custom loss function for my model, but whenever I try to convert Tensors into .numpy() arrays with run_eagerly = True, it gives "WARNING: Gradients do not exist for variables ...". So I debugged other custom loss functions implemented using TensorFlow. But in my case, I need to apply to mask and splitting index arrays and then use those arrays as indices to apply some sort of arithmetic functions using broadcasting. But I retrieved indices lists after masking, but I just have to access those indices and add specific functions. But I found no way in TensorFlow to implement that in a vectorized way.
error = y_true - y_false
print(y_true.shape, y_pred.shape)
print(error.shape)
print("Error values: ", error)
Output: (10, 1000), (10, 1000)
(10, 1000)
Error values: <tf.Tensor: shape=(10, 1000), dtype=float64, numpy= array([[-10, 0, 8, ..., 3, -1.5, -2.5], ..., [ 2.5, 8 , 6.5, ..., 5.5, 3.5, -0.5]])>
mask = tf.where(y_true > 5)
i = mask[0]
j = mask[1]
print(i[:5])
print(j[:5])
Results:
(<tf.Tensor: shape=(5,), dtype=int64, numpy=array([0, 0, 0, 0, 0], dtype=int64)>,
<tf.Tensor: shape=(5,), dtype=int64, numpy=array([19, 26, 28, 35, 39], dtype=int64)>)
In NumPy, I can access it using:
error[i, j] = error[i, j] * 5
What I want is to replace with new values of error in a specified position after executing the above code and get values like:
Error values: <tf.Tensor: shape=(10, 1000), dtype=float64, numpy= array([[-10, 0, 16*, ..., 3, -1.5, -2.5], ..., [ 2.5, 16* , 13*, ..., 11*, 3.5, -0.5]])>
But when I try to execute this as Tensors, it gives the following error:
TypeError Traceback (most recent call last)
Input In [193], in <cell line: 1>()
----> 1 error[i, j]
File ~\AppData\Local\Programs\Python\Python310\lib\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 ~\AppData\Local\Programs\Python\Python310\lib\site-packages\tensorflow\python\ops\array_ops.py:899, in _check_index(idx)
894 dtype = getattr(idx, "dtype", None)
895 if (dtype is None or dtypes.as_dtype(dtype) not in _SUPPORTED_SLICE_DTYPES or
896 idx.shape and len(idx.shape) == 1):
897 # TODO(slebedev): IndexError seems more appropriate here, but it
898 # will break `_slice_helper` contract.
--> 899 raise TypeError(_SLICE_TYPE_ERROR + ", got {!r}".format(idx))
TypeError: Only integers, slices (`:`), ellipsis (`...`), tf.newaxis (`None`) and scalar tf.int32/tf.int64 tensors are valid indices, got <tf.Tensor: shape=(4797,), dtype=int64, numpy=array([ 0, 0, 0, ..., 26, 26, 26], dtype=int64)>
I tried using other functions provided by TensorFlow too, but those did not work.