You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Keras自定义损失函数时张量赋值报错:TypeError: 'Tensor'对象不支持元素赋值

Fixing the "Tensor object does not support item assignment" Error in Keras Loss Function

Got it, let's sort this out! That error pops up because Keras/TensorFlow tensors are immutable—you can't assign values to them with square brackets like you would with a NumPy array or regular Python list. Your goal is to scale positive predictions by 1.1 before comparing to true values, and we can do that using Keras backend's conditional functions instead of direct assignment.

Here's the corrected version of your loss function:

import keras.backend as K

def rmseApprox(y_true, y_pred):
    # Create a coefficient tensor: 1.1 where y_pred >=0, 1.0 otherwise
    coeff = K.where(K.greater_equal(y_pred, 0), K.constant(1.1), K.constant(1.0))
    # Adjust predictions using the coefficient tensor
    adjusted_pred = coeff * y_pred
    # Calculate mean absolute difference (fixed your K.abs/K.mean syntax too)
    return K.abs(K.mean(y_true - adjusted_pred, axis=-1))

Key Notes:

  • We use K.where() to handle the conditional logic: it picks values from the second argument where the condition is true, and from the third where it's false. This builds the coefficient tensor without any forbidden assignment operations.
  • I fixed a small typo in your original code: k.abs should be K.abs (since you're importing Keras backend as K). Also, the parentheses around K.mean were misplaced—we need to compute the mean first, then take the absolute value.
  • All tensor operations in Keras/TensorFlow are symbolic, meaning you have to use backend functions to build the computation graph instead of Python's in-place assignment.

内容的提问来源于stack exchange,提问作者Reza Sabzi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 03:24:13