Skip to main content
 首页 » 编程设计

python之如何在 Keras 中实现加权均方误差函数

2024年12月31日7lhb25

我在 Keras 中定义加权均方误差如下:

def weighted_mse(yTrue,yPred): 
    data_weights = [w0,w1,w2,w3] 
    data_weights_np = np.asarray(data_weights, np.float32) 
    weights = tf.convert_to_tensor(data_weights_np, np.float32) 
    return K.mean(weights*K.square(yTrue-yPred)) 

我有每个预测的权重列表。预测的形状例如:(25,4)。这是通过维度为 4 的最终致密层生成的。我希望在均方误差中对这些预测进行加权,因此我生成了一个张量并将其与误差平方和相乘。这是这样做的正确方法吗? 因为,当我打印张量的形状时,对 YTrue 和 YPred 使用 tf.shape 它显示: 张量("loss_19/dense_20_loss/Shape:0", shape=(3,), dtype=int32)

对于权重:

Tensor("loss_19/dense_20_loss/Shape_2:0", shape=(1,), dtype=int32) 

请您参考如下方法:

Keras API 已经提供了一种提供权重的机制,例如 model.fit 函数。来自documentation :

class_weight: Optional dictionary mapping class indices (integers) to a weight (float) value, used for weighting the loss function (during training only). This can be useful to tell the model to "pay more attention" to samples from an under-represented class.

sample_weight: Optional Numpy array of weights for the training samples, used for weighting the loss function (during training only). You can either pass a flat (1D) Numpy array with the same length as the input samples (1:1 mapping between weights and samples), or in the case of temporal data, you can pass a 2D array with shape (samples, sequence_length), to apply a different weight to every timestep of every sample. In this case you should make sure to specify sample_weight_mode="temporal" in compile().

如果每个样本都有一个权重,则可以将 NumPy 数组作为 sample_weight 传递,以达到相同的效果,而无需编写自己的损失函数。