如何用千层面计算F1-micro分数


import theano.tensor as T
import numpy as np
from nolearn.lasagne import NeuralNet
def multilabel_objective(predictions, targets):
    epsilon = np.float32(1.0e-6)
    one = np.float32(1.0)
    pred = T.clip(predictions, epsilon, one - epsilon)
    return -T.sum(targets * T.log(pred) + (one - targets) * T.log(one - pred), axis=1)
net = NeuralNet(
    # your other parameters here (layers, update, max_epochs...)
    # here are the one you're interested in:
    objective_loss_function=multilabel_objective,
    custom_score=("validation score", lambda x, y: np.mean(np.abs(x - y)))
)

我在网上找到了这个代码,想测试一下。它确实有效,结果包括训练损失、测试损失、验证分数和时间等。

但是我怎样才能得到F1-micro的分数呢?此外,如果我试图导入scikit-learn,添加以下代码后计算F1:

data = data.astype(np.float32) 
classes = classes.astype(np.float32)
net.fit(data, classes)
score = cross_validation.cross_val_score(net, data, classes, scoring='f1', cv=10)
print score

我得到这个错误:

ValueError:不能处理多标签指示符和continuous-multioutput

如何基于以上代码实现f1微计算?

假设你在测试集上的真标签是y_true(形状:(n_samples, n_classes),只由0和1组成),你的测试观察值是X_test(形状:(n_samples, n_features))。

然后通过y_test = net.predict(X_test)得到测试集上的净预测值。

如果你正在做多类分类:

由于在您的网络中您已将regression设置为False,因此它也应该仅由0和1组成。

你可以用:

计算微平均f1分数
from sklearn.metrics import f1_score
f1_score(y_true, y_pred, average='micro')

用来说明这一点的小代码示例(使用虚拟数据,使用实际的y_testy_true):

from sklearn.metrics import f1_score
import numpy as np

y_true = np.array([[0, 0, 1], [0, 1, 0], [0, 0, 1], [0, 0, 1], [0, 1, 0]])
y_pred = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1], [0, 0, 1], [0, 0, 1]])
t = f1_score(y_true, y_pred, average='micro')

如果你正在做多标签分类:

你输出的不是0和1的矩阵,而是概率矩阵。Y_pred [i, j]是观测值i属于j类的概率。

您需要定义一个阈值,在此阈值之上,您将说观察值属于给定的类。然后,您可以相应地赋予标签属性,并像前面的情况一样进行操作。

thresh = 0.8  # choose your own value 
y_test_binary = np.where(y_test > thresh, 1, 0) 
# creates an array with 1 where y_test>thresh, 0 elsewhere
f1_score(y_true, y_pred_binary, average='micro')

最新更新