通过特定索引错误的价值分配在TensorFlow中
我正在尝试为我的模型构建自定义损失函数,但是每当我尝试将张量转换为带有run_eagerly = true的numpy()数组时,它会发出“警告:变量不存在渐变……”。因此,我调试了使用TensorFlow实施的其他自定义损失功能。但是就我而言,我需要申请掩码和拆分索引阵列,然后使用这些数组作为索引来使用广播应用某种算术功能。但是我在掩盖后检索了索引列表,但是我只需要访问这些索引并添加特定功能即可。但是我在Tensorflow中找不到以矢量化的方式实施的方法。
error = y_true - y_false
print(y_true.shape, y_pred.shape)
print(error.shape)
print("Error values: ", error)
输出:(10,1000),(10,1000)
(10,1000)
错误值:< tf.tensor:shape =(10,1000),dtype = float64,numpy = 阵列([[ - 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])
结果:
(< tf.tensor:shape =(5,),dtype = int64,numpy = array([[0,0,0,0,0,0],dtype = int64)>,
>
< tf.tensor:shape =(5,),dtype = int64,numpy = array([[19,26,28,35,39],dtype = int64)>)
>
在numpy中,我可以使用:
error[i, j] = error[i, j] * 5
< Strong>我想要的是在执行上述代码后指定位置中以新的错误值替换并获得以下值:
错误值:&lt; tf.tensor:shape =(10,1000),dtype = float64,numpy = array([[ - 10,0,0,16*,... -1.5,-2.5], ...,, [2.5,16*,13*,...,11*, 3.5,-0.5]])&gt;
但是,当我尝试以张量为张者时,它会产生以下错误:
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)>
我也尝试使用TensorFlow提供的其他功能,但这些功能不起作用。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果我正确理解您的评论,则应适合以下代码。它乘以alpha(= 2。在此)所有误差值大于5,
该值给出:
输入错误
蒙版
增益
输出错误
If I understand your comment correctly, the following code should be appropriate. It multiplies by alpha (=2. here) all error values greater than 5
which gives:
input error
mask
gain
output error
您不能在TensorFlow中使用索引分配,但是可以使用 /a> and tf.scatter_nd_nd 。
这是一个带虚拟输入数据
输出的示例
y_true:
y_mask:
y_mask*4+y_true:
另一个解决方案是直接使用掩码并将其施放为int32或float32(或其他):
y_mask v2:y_mask v2:
You can't use indices assignement in tensorflow, but this can be overcome using tf.gather_nd and tf.scatter_nd.
Here is an example with dummy input data
outputs
y_true:
y_mask:
y_mask*4+y_true:
Another solution is to use directly the mask and cast it to int32 or float32 (or other):
y_mask v2: