【发布时间】:2021-01-03 16:57:47
【问题描述】:
我正在编写一个自定义损失函数,该函数需要计算每组预测值的比率。作为一个简化的示例,我的数据和模型代码如下所示:
def main():
df = pd.DataFrame(columns=["feature_1", "feature_2", "condition_1", "condition_2", "label"],
data=[[5, 10, "a", "1", 0],
[30, 20, "a", "1", 1],
[50, 40, "a", "1", 0],
[15, 20, "a", "2", 0],
[25, 30, "b", "2", 1],
[35, 40, "b", "1", 0],
[10, 80, "b", "1", 1]])
features = ["feature_1", "feature_2"]
conds_and_label = ["condition_1", "condition_2", "label"]
X = df[features]
Y = df[conds_and_label]
model = my_model(input_shape=len(features))
model.fit(X, Y, epochs=10, batch_size=128)
model.evaluate(X, Y)
def custom_loss(conditions, y_pred): # this is what I need help with
conds = ["condition_1", "condition_2"]
conditions["label_pred"] = y_pred
g = conditions.groupby(by=conds,
as_index=False).apply(lambda x: x["label_pred"].sum() /
len(x)).reset_index(name="pred_ratio")
# true_ratios will be a constant, external DataFrame. Simplified example here:
true_ratios = pd.DataFrame(columns=["condition_1", "condition_2", "true_ratio"],
data=[["a", "1", 0.1],
["a", "2", 0.2],
["b", "1", 0.8],
["b", "2", 0.9]])
merged = pd.merge(g, true_ratios, on=conds)
merged["diff"] = merged["pred_ratio"] - merged["true_ratio"]
return K.mean(K.abs(merged["diff"]))
def joint_loss(conds_and_label, y_pred):
y_true = conds_and_label[:, 2]
conditions = tf.gather(conds_and_label, [0, 1], axis=1)
loss_1 = standard_loss(y_true=y_true, y_pred=y_pred) # not shown
loss_2 = custom_loss(conditions=conditions, y_pred=y_pred)
return 0.5 * loss_1 + 0.5 * loss_2
def my_model(input_shape=None):
model = Sequential()
model.add(Dense(units=2, activation="relu"), input_shape=(input_shape,))
model.add(Dense(units=1, activation='sigmoid'))
model.add(Flatten())
model.compile(loss=joint_loss, optimizer="Adam",
metrics=[joint_loss, custom_loss, "accuracy"])
return model
我需要帮助的是custom_loss 函数。如您所见,它当前的编写方式好像输入是 Pandas DataFrames。但是,输入将是 Keras 张量(带有 tensorflow 后端),所以我试图弄清楚如何将custom_loss 中的当前代码转换为使用 Keras/TF 后端函数。例如,我在网上搜索并找不到在 Keras/TF 中进行 groupby 以获得我需要的比率的方法......
一些可能对您有帮助的上下文/解释:
- 我的主要损失函数是
joint_loss,它由standard_loss(未显示)和custom_loss组成。但我只需要帮助转换custom_loss。 -
custom_loss所做的是:- 在两个条件列上进行分组(这两列代表数据的组)。
- 获取预测的 1 与每组批次样本总数的比率。
- 将“pred_ratio”与一组“true_ratio”进行比较并得出差异。
- 根据差值计算平均绝对误差。
【问题讨论】:
-
您使用的是什么版本的 Keras(独立?tf.keras?)和 Tensorflow,您是否可以在 Eager 模式下实现它?
-
所有可能的条件值的数量是常数并且提前知道吗?
-
@runDOSrun 我混合使用了 keras.backend 和 tensorflow (2.2.0)。有趣的是,您提到了 Eager 模式,因为我最终提出的解决方案仅适用于 Eager 模式,我不知道为什么!我刚刚发布了它,请随意看看。
-
@MohamedEzz 是的,可能的条件值的数量是提前知道的并且是恒定的(至少在模型运行期间)。
标签: python tensorflow keras pandas-groupby loss-function