问题:
在使用tf-idf特征和logistic regression模型作文本分类(二分类)时,出现了下面的情况:
试过相同特征下的其他模型如Naive Bayes,但是效果一样:
又分别试了下word count特征,而不使用tf-idf,效果还是不行:
所以,log loss 到底什么范围才合理?log loss 特别大的话该如何解决?
解决:
1.为什么使用 log loss?log loss 和其他模型评估指标有什么区别?
针对分类问题的模型评估,可能有多种指标选择,比如混淆矩阵中的 Recall, Precision, F-Score 或者 Accuracy。
还有一种选择是使用 loss 指标,比如 log loss。
Log loss 和他们的区别是:
log loss 不仅考虑模型最后的分类表现,它还考虑了模型的概率。更大的概率会使得log loss变小,直至接近0;
它是对“不确定性”/“或者说”熵,的一种度量。
Log Loss it useful to compare models not only on their output but on their probabilistic outcome.
2.log loss 到底什么范围才合理?
先直接给出答案: 0.693
Log Loss is hard to interpret. A Log Loss of 0.69 may be good in a multiclass problem, but very bad in a binary biased case.
探索过程:
对于任意一个指标,想要解释它你就必须找到一些参考值来进行对比。
A good metric is at least better that the “dumb”, by-chance guess, if you would have to guess with no information on the observations. In other words, a model should be at least better than the non-informative model.
一个指标最基本的要求是要使得模型比完全靠“猜”的方法要好。
而完全靠猜的方法依据于两个指标:
① 类别数量 ② 分类的平衡
我们以此来探索 log loss:
后续可参考:
https://medium.com/@fzammito/whats-considered-a-good-log-loss-in-machine-learning-a529d400632d
3.log loss 特别大的话该如何解决?
使用model.predict_proba() 而不是 model.predict()
两者区别:
predict() 返回的是预测的分类结果:0或者1(二分类)
predict_proba() 返回的是分类的概率在0和1之间!
之前一直以为model.predict_proba() 用于多分类
但是使用之后依旧出现呢问题:
operands could not be broadcast together with shapes (2000,) (2000,2) ,
原因:没有将模型预测的值,由actual改为probabilities
可以自定义log loss 函数来解决:
def multiclass_logloss(actual, predicted, eps=1e-15):
"""对数损失度量(Logarithmic Loss Metric)的多分类版本。
:param actual: 包含actual target classes的数组
:param predicted: 分类预测结果矩阵, 每个类别都有一个概率
"""
# Convert 'actual' to a binary array if it's not already:
if len(actual.shape) == 1:
actual2 = np.zeros((actual.shape[0], predicted.shape[1]))
for i, val in enumerate(actual):
actual2[i, val] = 1
actual = actual2
clip = np.clip(predicted, eps, 1 - eps)
rows = actual.shape[0]
vsota = np.sum(actual * np.log(clip))
return -1.0 / rows * vsota