如果你愿意,你当然可以两者兼得,关键是如果这是你需要。根据kerasdocs:
class_weight: 可选字典将类索引(整数)映射到权重(浮点)值,用于加权损失函数(仅在训练期间)。这对于告诉模型“更加关注”来自代表性不足的类的样本很有用。
sample_weight: 训练样本的可选 Numpy 权重数组,用于加权损失函数(仅在训练期间)。您可以传递一个平面 (1D) Numpy 数组与输入样本的长度相同(权重和样本之间的 1:1 映射),或者在时间数据的情况下 [...]。
因此,鉴于您提到“与第二类相比,第一类的数量要多得多”,我认为您应该选择class_weight 参数。在那里,您可以指示您的数据集呈现的比率,以便您可以补偿不平衡的数据类。当您想为 每个 数据元素定义权重或重要性时,sample_weight 更多。
例如,如果你通过:
class_weight = {0 : 1. , 1: 50.}
您会说 1 类中的每个样本都将计为 0 类中的 50 个样本,因此对 1 类中的元素给予更多“重要性”(因为这些样本肯定更少) .您可以自定义它以满足您自己的需求。更多关于 this 的不平衡数据集的信息很好的问题。
注意:要进一步比较这两个参数,请记住将class_weight 传递为{0:1., 1:50.} 将等效于将sample_weight 传递为[1.,1.,1.,...,50.,50.,...],因为您有样本的类[0,0,0,...,1,1,...]。
正如我们所看到的,在这种情况下使用class_weight 更实用,而sample_weight 可以用于更具体的情况,您实际上希望单独为每个样本赋予“重要性”。如果情况需要,也可以同时使用两者,但必须牢记其累积效应。
编辑:根据您的新问题,挖掘 Keras source code 似乎确实 sample_weights 覆盖了 class_weights,这是一段代码在 _standarize_weigths 方法(第 499 行)上执行此操作:
if sample_weight is not None:
#...Does some error handling...
return sample_weight #simply returns the weights you passed
elif isinstance(class_weight, dict):
#...Some error handling and computations...
#Then creates an array repeating class weight to match your target classes
weights = np.asarray([class_weight[cls] for cls in y_classes
if cls in class_weight])
#...more error handling...
return weights
这意味着您只能使用其中一种,但不能同时使用。因此,您确实需要将您的sample_weights 乘以补偿不平衡所需的比率。
更新:截至本次编辑时(2020 年 3 月 27 日),查看 training_utils.standardize_weights() 的 source code 我们可以看到它现在支持两者 class_weights 和 sample_weights:
一切都归一化为单个样本(或时间步)
权重数组。 如果同时提供了sample_weights 和class_weights,
权重相乘。