【问题标题】:Conditional Replace for Custom Loss Function Constraint? TypeError: 'Tensor' object does not support item assignment自定义损失函数约束的条件替换? TypeError:“张量”对象不支持项目分配
【发布时间】:2020-10-06 09:50:12
【问题描述】:

我有一个模型,它在批次中为每个样本返回两个值,其中第一个值必须 >=0,第二个值必须

def maxMinDiffLossConstrained(y_true, y_pred, sample_weight=None):
 
    y_pred_shape = list(y_pred.shape) # y_pred returns a tuple, we want a list so we can construct another tensor 
    #y_pred_data = y_pred.numpy() # get the tensor data as a numpy array 
        
    y_pred[y_pred[:,0] < 0, 0] = -10            
    y_pred[y_pred[:,1] > 0, 1] = 10            
        
    y_mod = tf.reshape(y_pred, y_pred_shape)   
   
    mse = MeanSquaredError()
    loss = mse(y_true, y_mod)

    return loss

哪里出错了

TypeError: 'Tensor' object does not support item assignment

如您所见,我尝试使用 y_pred.numpy(),但 type(y_pred) 之外的对象是 &lt;class 'tensorflow.python.framework.ops.Tensor'&gt; 并返回错误:

AttributeError: 'Tensor' object has no attribute 'numpy'

我检查了许多其他帖子。这个建议拆垛和重新堆叠

TypeError: 'Tensor' object does not support item assignment in TensorFlow

下一篇较长的文章很有帮助,它建议根据条件进行分解,然后重新制作张量。我仍在努力寻找这种方法的解决方案:

https://towardsdatascience.com/how-to-replace-values-by-index-in-a-tensor-with-tensorflow-2-0-510994fe6c5f

不幸的是,由于我的张量的尺寸是(batch_size, 2),我仍然没有找到可行的解决方案。我的困难是,在我使用以下代码获得 dim1 (>=0) 和 dim2 (

maxes_to_remove = y_pred[:,0] < 0 
mins_to_remove = y_pred[:,1] > 0

idx_maxes = tf.where(maxes_to_remove == True)
idx_mins = tf.where(mins_to_remove == True)

我不知道如何只替换需要替换的第一个维度中的值以及需要替换的第二个维度中的值。

顺便说一句,我也遇到了this issue,但能够解决它。

【问题讨论】:

    标签: python tensorflow keras neural-network loss-function


    【解决方案1】:

    我相信 tf 中的张量是不可变的,因此您不能将值分配给数组中的索引。两种解决方法:

    1. 定义一个使用原始张量和一些附加操作创建的新张量。我建议使用tf.keras.backend.switch(),它允许您根据布尔值的张量(对您来说这可能是 idx_maxes?)

    2. 转换为 numpy 数组,根据需要进行更改,然后转换回张量。 请注意,这仅在您处于渴望执行模式时才有效。 如果您处于图形模式,直观地转换为 numpy 是不行的,因为 numpy 数组不支持图形计算,所以操作链会在转换过程中丢失。

    【讨论】:

    • 转换为 numpy 数组是我的第一次尝试,但我失败了。我见过急切的张量突然出现,但我还没有弄清楚它们是如何工作的。有什么区别以及如何切换模式?
    猜你喜欢
    • 1970-01-01
    • 2016-10-08
    • 2013-08-16
    • 1970-01-01
    • 2016-07-31
    • 2014-02-18
    • 2017-03-26
    • 2021-08-05
    • 1970-01-01
    相关资源
    最近更新 更多