我想为正样本的部分设置相同的权重。但是,在我看来,tf.nn.weighted_cross_entropy_with_logits
只能设置所有阳性样本的权重。
例如,在ctr预测中,我想为订单样本设置10个权重,点击样本和非单击样本的权重仍为1.
这是我未加权的代码
def my_model(features, labels, mode, params):
net = tf.feature_column.input_layer(features, params['feature_columns'])
for units in params['hidden_units']:
net = tf.layers.dense(net, units=units, activation=params["activation"])
logits = tf.layers.dense(net, params['n_classes'], activation=None)
predicted_classes = tf.argmax(logits, 1)
if mode == tf.estimator.ModeKeys.PREDICT:
predictions = {
'class_ids': predicted_classes, #predicted_classes[:, tf.newaxis],
'probabilities': tf.nn.softmax(logits),
'logits': logits,
}
return tf.estimator.EstimatorSpec(mode, predictions=predictions)
loss = tf.losses.sparse_softmax_cross_entropy(labels=labels, logits=logits)
metrics = {'auc': tf.metrics.auc(labels=labels, predictions=tf.nn.softmax(logits)[:,1])}
if mode == tf.estimator.ModeKeys.EVAL:
return tf.estimator.EstimatorSpec(mode, loss=loss, eval_metric_ops=metrics)
assert mode == tf.estimator.ModeKeys.TRAIN
optimizer = tf.train.AdagradOptimizer(learning_rate=0.1)
train_op = optimizer.minimize(loss, global_step=tf.train.get_global_step())
return tf.estimator.EstimatorSpec(mode, loss=loss, train_op=train_op)
train_input_fn = tf.estimator.inputs.pandas_input_fn(x=data_train, y=data_train_click, batch_size = 1024, num_epochs=1, shuffle=False)
classifier.train(input_fn=train_input_fn)
此处data_train_click
是一个系列,点击样本为1,未点击的样本为0.我有一个名为data_train_order
的系列,其中订单样本为1,其他为0 < / p>
答案 0 :(得分:1)
答案 1 :(得分:0)
您可以通过将权重参数传递给损失函数来对每个样本进行不同的权衡,该函数是包含每个样本的相应权重的形状张量[batch_size]。
loss = tf.losses.sparse_softmax_cross_entropy(labels=labels, logits=logits, weights=weights)