【发布时间】:2019-09-20 17:37:19
【问题描述】:
对于我的问题,我想预测客户评论分数从 1 到 5。 我认为将其实现为回归问题会很好,因为模型预测的 1 而 5 是真实值应该是比 4 更“差”的预测。 还希望该模型以某种方式对所有评分等级都同样出色。 因为我的数据集高度不平衡,我想创建一个能够捕获这一点的指标/损失(我认为就像 F1 进行分类一样)。 因此我创建了以下指标(现在只有 mse 是相关的):
def custom_metric(y_true, y_pred):
df = pd.DataFrame(np.column_stack([y_pred, y_true]), columns=["Predicted", "Truth"])
class_mse = 0
#class_mae = 0
print("MAE for Classes:")
for i in df.Truth.unique():
temp = df[df["Truth"]==i]
mse = mean_squared_error(temp.Truth, temp.Predicted)
#mae = mean_absolute_error(temp.Truth, temp.Predicted)
print("Class {}: {}".format(i, mse))
class_mse += mse
#class_mae += mae
print()
print("AVG MSE over Classes {}".format(class_mse/len(df.Truth.unique())))
#print("AVG MAE over Classes {}".format(class_mae/len(df.Truth.unique())))
现在是一个示例预测:
import numpy as np
import pandas as pd
from sklearn.metrics import mean_squared_error, mean_absolute_error
# sample predictions: "model" messed up at class 2 and 3
y_true = np.array((1,1,1,2,2,2,3,3,3,4,4,4,5,5,5))
y_pred = np.array((1,1,1,2,2,3,5,4,3,4,4,4,5,5,5))
custom_metric(y_true, y_pred)
现在我的问题是:它是否能够创建一个能够以类似行为起作用的自定义张量流损失函数?我还研究了这个实现,它还没有为 tensorflow 做好准备,但可能更相似:
def custom_metric(y_true, y_pred):
mse_class = 0
num_classes = len(np.unique(y_true))
stacked = np.vstack((y_true, y_pred))
for i in np.unique(stacked[0]):
y_true_temp = stacked[0][np.where(stacked[0]==i)]
y_pred_temp = stacked[1][np.where(stacked[0]==i)]
mse = np.mean(np.square(y_pred_temp - y_true_temp))
mse_class += mse
return mse_class/num_classes
但是,我仍然不确定如何解决类似 tensorflow 的定义的 for 循环。
提前感谢您的帮助!
【问题讨论】:
标签: python tensorflow keras metrics loss-function