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.absshould beK.abs(since you're importing Keras backend asK). Also, the parentheses aroundK.meanwere 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
相关产品推荐
相关产品推荐

