<p>如果你想的话,你当然可以同时做这两件事,关键是你是否需要。根据keras <a href="https://keras.io/models/model/" rel="noreferrer">docs</a>:</p>
<blockquote>
<ul>
<li><p><strong>class_weight:</strong> 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 <strong>tell the model to "pay more attention" to samples from an under-represented class</strong>.</p></li>
<li><p><strong>sample_weight:</strong> 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 <strong>with the same length as the input samples (1:1 mapping between weights and samples)</strong>, or in the case of temporal data [...].</p></li>
</ul>
</blockquote>
<p>因此,鉴于您提到您的<em>“比第二个”</em>“拥有更多的第一个类,我认为您应该使用<code>class_weight</code>参数。在这里,您可以指示数据集所呈现的比率,以便可以补偿不平衡的数据类。当您想为每个<em>数据元素定义权重或重要性时,<code>sample_weight</code>会更多。在</p>
<p>例如,如果您通过:</p>
<pre><code>class_weight = {0 : 1. , 1: 50.}
</code></pre>
<p>您将说来自类<code>1</code>的每个样本都将被计为来自类<code>0</code>的50个样本,因此给来自类<code>1</code>的元素更多的“重要性”(因为这些样本肯定更少)。你可以根据自己的需要定制这个。更多关于<a href="https://datascience.stackexchange.com/questions/13490/how-to-set-class-weights-for-imbalanced-classes-in-keras">this</a>的不平衡数据集的信息。在</p>
<p><strong>注意:</strong>要进一步比较这两个参数,请记住将<code>class_weight</code>作为<code>{0:1., 1:50.}</code>传递将等效于将<code>sample_weight</code>作为{<cd9>}传递,前提是您有一个示例,其类<code>[0,0,0,...,1,1,...]</code>。在</p>
<p>正如我们所看到的,在这种情况下使用<code>class_weight</code>更实际,<code>sample_weight</code>可以用于更具体的情况,在这种情况下,您实际上想单独给每个样本一个“重要性”。如果情况需要,也可以同时使用这两种方法,但必须记住其累积效应。在</p>
<p><strong>编辑:</strong>根据您的新问题,在Keras上挖掘<a href="https://github.com/keras-team/keras/blob/master/keras/engine/training.py#L499" rel="noreferrer">source code</a>似乎<strong><code>sample_weights</code>确实覆盖了<code>class_weights</code></strong>,下面是对<code>_standarize_weigths</code>方法(第499行)执行此操作的代码片段:</p>
^{pr2}$
<p>这意味着您只能使用其中一个,但不能同时使用这两个。因此,您确实需要将您的<code>sample_weights</code>乘以您需要补偿不平衡的比率。在</p>