當前位置: 首頁>>代碼示例>>Python>>正文


Python metrics.matthews_corrcoef方法代碼示例

本文整理匯總了Python中sklearn.metrics.matthews_corrcoef方法的典型用法代碼示例。如果您正苦於以下問題:Python metrics.matthews_corrcoef方法的具體用法?Python metrics.matthews_corrcoef怎麽用?Python metrics.matthews_corrcoef使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在sklearn.metrics的用法示例。


在下文中一共展示了metrics.matthews_corrcoef方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: multi_class_classification

# 需要導入模塊: from sklearn import metrics [as 別名]
# 或者: from sklearn.metrics import matthews_corrcoef [as 別名]
def multi_class_classification(data_X,data_Y):
    '''
    calculate multi-class classification and return related evaluation metrics
    '''

    svc = svm.SVC(C=1, kernel='linear')
    # X_train, X_test, y_train, y_test = train_test_split( data_X, data_Y, test_size=0.4, random_state=0) 
    clf = svc.fit(data_X, data_Y) #svm
    # array = svc.coef_
    # print array
    predicted = cross_val_predict(clf, data_X, data_Y, cv=2)
    print "accuracy",metrics.accuracy_score(data_Y, predicted)
    print "f1 score macro",metrics.f1_score(data_Y, predicted, average='macro') 
    print "f1 score micro",metrics.f1_score(data_Y, predicted, average='micro') 
    print "precision score",metrics.precision_score(data_Y, predicted, average='macro') 
    print "recall score",metrics.recall_score(data_Y, predicted, average='macro') 
    print "hamming_loss",metrics.hamming_loss(data_Y, predicted)
    print "classification_report", metrics.classification_report(data_Y, predicted)
    print "jaccard_similarity_score", metrics.jaccard_similarity_score(data_Y, predicted)
    # print "log_loss", metrics.log_loss(data_Y, predicted)
    print "zero_one_loss", metrics.zero_one_loss(data_Y, predicted)
    # print "AUC&ROC",metrics.roc_auc_score(data_Y, predicted)
    # print "matthews_corrcoef", metrics.matthews_corrcoef(data_Y, predicted) 
開發者ID:RoyZhengGao,項目名稱:edge2vec,代碼行數:25,代碼來源:multi_class_classification.py

示例2: evaluation_analysis

# 需要導入模塊: from sklearn import metrics [as 別名]
# 或者: from sklearn.metrics import matthews_corrcoef [as 別名]
def evaluation_analysis(true_label,predicted): 
    '''
    return all metrics results
    '''
    print "accuracy",metrics.accuracy_score(true_label, predicted)
    print "f1 score macro",metrics.f1_score(true_label, predicted, average='macro')     
    print "f1 score micro",metrics.f1_score(true_label, predicted, average='micro') 
    print "precision score",metrics.precision_score(true_label, predicted, average='macro') 
    print "recall score",metrics.recall_score(true_label, predicted, average='macro') 
    print "hamming_loss",metrics.hamming_loss(true_label, predicted)
    print "classification_report", metrics.classification_report(true_label, predicted)
    print "jaccard_similarity_score", metrics.jaccard_similarity_score(true_label, predicted)
    print "log_loss", metrics.log_loss(true_label, predicted)
    print "zero_one_loss", metrics.zero_one_loss(true_label, predicted)
    print "AUC&ROC",metrics.roc_auc_score(true_label, predicted)
    print "matthews_corrcoef", metrics.matthews_corrcoef(true_label, predicted) 
開發者ID:RoyZhengGao,項目名稱:edge2vec,代碼行數:18,代碼來源:link_prediction.py

示例3: matthews_correlation_coefficient_scorer

# 需要導入模塊: from sklearn import metrics [as 別名]
# 或者: from sklearn.metrics import matthews_corrcoef [as 別名]
def matthews_correlation_coefficient_scorer(
    golds: ndarray,
    probs: Optional[ndarray],
    preds: ndarray,
    uids: Optional[List[str]] = None,
) -> Dict[str, float]:
    """Matthews correlation coefficient (MCC).

    Args:
      golds: Ground truth values.
      probs: Predicted probabilities.
      preds: Predicted values.
      uids: Unique ids, defaults to None.

    Returns:
      Matthews correlation coefficient score.
    """
    # Convert probabilistic label to hard label
    if len(golds.shape) == 2:
        golds = prob_to_pred(golds)

    return {"matthews_corrcoef": matthews_corrcoef(golds, preds)} 
開發者ID:SenWu,項目名稱:emmental,代碼行數:24,代碼來源:matthews_correlation.py

示例4: test_confusion_matrix_binary

# 需要導入模塊: from sklearn import metrics [as 別名]
# 或者: from sklearn.metrics import matthews_corrcoef [as 別名]
def test_confusion_matrix_binary():
    # Test confusion matrix - binary classification case
    y_true, y_pred, _ = make_prediction(binary=True)

    def test(y_true, y_pred):
        cm = confusion_matrix(y_true, y_pred)
        assert_array_equal(cm, [[22, 3], [8, 17]])

        tp, fp, fn, tn = cm.flatten()
        num = (tp * tn - fp * fn)
        den = np.sqrt((tp + fp) * (tp + fn) * (tn + fp) * (tn + fn))

        true_mcc = 0 if den == 0 else num / den
        mcc = matthews_corrcoef(y_true, y_pred)
        assert_array_almost_equal(mcc, true_mcc, decimal=2)
        assert_array_almost_equal(mcc, 0.57, decimal=2)

    test(y_true, y_pred)
    test([str(y) for y in y_true],
         [str(y) for y in y_pred]) 
開發者ID:PacktPublishing,項目名稱:Mastering-Elasticsearch-7.0,代碼行數:22,代碼來源:test_classification.py

示例5: compute_metrics

# 需要導入模塊: from sklearn import metrics [as 別名]
# 或者: from sklearn.metrics import matthews_corrcoef [as 別名]
def compute_metrics(task_name, preds, labels):
    assert len(preds) == len(labels)
    if task_name == "cola":
        return {"mcc": matthews_corrcoef(labels, preds)}
    elif task_name == "sst-2":
        return {"acc": simple_accuracy(preds, labels)}
    elif task_name == "mrpc":
        return acc_and_f1(preds, labels)
    elif task_name == "sts-b":
        return pearson_and_spearman(preds, labels)
    elif task_name == "qqp":
        return acc_and_f1(preds, labels)
    elif task_name == "mnli":
        return {"acc": simple_accuracy(preds, labels)}
    elif task_name == "mnli-mm":
        return {"acc": simple_accuracy(preds, labels)}
    elif task_name == "qnli":
        return {"acc": simple_accuracy(preds, labels)}
    elif task_name == "rte":
        return {"acc": simple_accuracy(preds, labels)}
    elif task_name == "wnli":
        return {"acc": simple_accuracy(preds, labels)}
    else:
        raise KeyError(task_name) 
開發者ID:martiansideofthemoon,項目名稱:squash-generation,代碼行數:26,代碼來源:run_classifier.py

示例6: compute_metrics

# 需要導入模塊: from sklearn import metrics [as 別名]
# 或者: from sklearn.metrics import matthews_corrcoef [as 別名]
def compute_metrics(task_name, pred_srs, label_srs):
    assert len(pred_srs) == len(label_srs)
    if task_name == "cola":
        return {"mcc": matthews_corrcoef(label_srs, pred_srs)}
    elif task_name == "sst":
        return {"acc": simple_accuracy(pred_srs, label_srs)}
    elif task_name == "mrpc":
        return acc_and_f1(pred_srs, label_srs)
    elif task_name == "stsb":
        return pearson_and_spearman(pred_srs, label_srs)
    elif task_name == "qqp":
        return acc_and_f1(pred_srs, label_srs)
    elif task_name == "mnli":
        return {"acc": simple_accuracy(pred_srs, label_srs)}
    elif task_name == "mnli-mm":
        return {"acc": simple_accuracy(pred_srs, label_srs)}
    elif task_name == "qnli":
        return {"acc": simple_accuracy(pred_srs, label_srs)}
    elif task_name == "rte":
        return {"acc": simple_accuracy(pred_srs, label_srs)}
    elif task_name == "wnli":
        return {"acc": simple_accuracy(pred_srs, label_srs)}
    else:
        raise KeyError(task_name) 
開發者ID:zphang,項目名稱:bert_on_stilts,代碼行數:26,代碼來源:evaluate.py

示例7: score_eval_func

# 需要導入模塊: from sklearn import metrics [as 別名]
# 或者: from sklearn.metrics import matthews_corrcoef [as 別名]
def score_eval_func(self, y_true, y_pred, mode='accuracy'):
        prob_pred = two_class_encoding(y_pred)
        label_pred = np.argmax(prob_pred, axis=1)
        if mode == 'accuracy':
            score_pred = accuracy_score(y_true=y_true, y_pred=label_pred)
        elif mode == 'precision':
            score_pred = precision_score(y_true=y_true, y_pred=label_pred)
        elif mode == 'recall':
            score_pred = recall_score(y_true=y_true, y_pred=label_pred)
        elif mode == 'f1':
            score_pred = f1_score(y_true=y_true, y_pred=label_pred)
        elif mode == 'MCC':
            score_pred = matthews_corrcoef(y_true=y_true, y_pred=label_pred)
        else:
            raise ValueError('Score function mode unrecognized! Must from one in the list '
                             '[\'accuracy\', \'precision\',\'recall\',\'f1\',\'MCC\']')

        return score_pred 
開發者ID:jhwjhw0123,項目名稱:Imbalance-XGBoost,代碼行數:20,代碼來源:imbalance_xgb.py

示例8: validation_step

# 需要導入模塊: from sklearn import metrics [as 別名]
# 或者: from sklearn.metrics import matthews_corrcoef [as 別名]
def validation_step(self, inputs, model: tf.keras.Model, metrics=None):
    if self.metric_type == 'accuracy':
      return super(SentencePredictionTask,
                   self).validation_step(inputs, model, metrics)
    features, labels = inputs
    outputs = self.inference_step(features, model)
    loss = self.build_losses(
        labels=labels, model_outputs=outputs, aux_losses=model.losses)
    logs = {self.loss: loss}
    if self.metric_type == 'matthews_corrcoef':
      logs.update({
          'sentence_prediction':
              tf.expand_dims(
                  tf.math.argmax(outputs['sentence_prediction'], axis=1),
                  axis=0),
          'labels':
              labels,
      })
    if self.metric_type == 'pearson_spearman_corr':
      logs.update({
          'sentence_prediction': outputs['sentence_prediction'],
          'labels': labels,
      })
    return logs 
開發者ID:tensorflow,項目名稱:models,代碼行數:26,代碼來源:sentence_prediction.py

示例9: get_metric_fn

# 需要導入模塊: from sklearn import metrics [as 別名]
# 或者: from sklearn.metrics import matthews_corrcoef [as 別名]
def get_metric_fn(task_name):
    if task_name == "cola":
        return lambda p, l: {"mcc": matthews_corrcoef(p, l)}
    if task_name == "sst-2":
        return lambda p, l: {"acc": simple_accuracy(p, l)}
    if task_name == "mrpc":
        return acc_and_f1
    if task_name == "sts-b":
        return pearson_and_spearman
    if task_name == "qqp":
        return acc_and_f1
    if task_name == "mnli":
        return lambda p, l: {"acc": simple_accuracy(p, l)}
    if task_name == "mnli-mm":
        return lambda p, l: {"acc": simple_accuracy(p, l)}
    if task_name == "qnli":
        return lambda p, l: {"acc": simple_accuracy(p, l)}
    if task_name == "rte":
        return lambda p, l: {"acc": simple_accuracy(p, l)}
    if task_name == "wnli":
        return lambda p, l: {"acc": simple_accuracy(p, l)}
    raise KeyError(task_name) 
開發者ID:NervanaSystems,項目名稱:nlp-architect,代碼行數:24,代碼來源:glue_tasks.py

示例10: test_matthews_corrcoef_nan

# 需要導入模塊: from sklearn import metrics [as 別名]
# 或者: from sklearn.metrics import matthews_corrcoef [as 別名]
def test_matthews_corrcoef_nan():
    assert_equal(matthews_corrcoef([0], [1]), 0.0)
    assert_equal(matthews_corrcoef([0, 0], [0, 1]), 0.0) 
開發者ID:PacktPublishing,項目名稱:Mastering-Elasticsearch-7.0,代碼行數:5,代碼來源:test_classification.py

示例11: test_matthews_corrcoef_against_numpy_corrcoef

# 需要導入模塊: from sklearn import metrics [as 別名]
# 或者: from sklearn.metrics import matthews_corrcoef [as 別名]
def test_matthews_corrcoef_against_numpy_corrcoef():
    rng = np.random.RandomState(0)
    y_true = rng.randint(0, 2, size=20)
    y_pred = rng.randint(0, 2, size=20)

    assert_almost_equal(matthews_corrcoef(y_true, y_pred),
                        np.corrcoef(y_true, y_pred)[0, 1], 10) 
開發者ID:PacktPublishing,項目名稱:Mastering-Elasticsearch-7.0,代碼行數:9,代碼來源:test_classification.py

示例12: test_matthews_corrcoef_against_jurman

# 需要導入模塊: from sklearn import metrics [as 別名]
# 或者: from sklearn.metrics import matthews_corrcoef [as 別名]
def test_matthews_corrcoef_against_jurman():
    # Check that the multiclass matthews_corrcoef agrees with the definition
    # presented in Jurman, Riccadonna, Furlanello, (2012). A Comparison of MCC
    # and CEN Error Measures in MultiClass Prediction
    rng = np.random.RandomState(0)
    y_true = rng.randint(0, 2, size=20)
    y_pred = rng.randint(0, 2, size=20)
    sample_weight = rng.rand(20)

    C = confusion_matrix(y_true, y_pred, sample_weight=sample_weight)
    N = len(C)
    cov_ytyp = sum([
        C[k, k] * C[m, l] - C[l, k] * C[k, m]
        for k in range(N) for m in range(N) for l in range(N)
    ])
    cov_ytyt = sum([
        C[:, k].sum() *
        np.sum([C[g, f] for f in range(N) for g in range(N) if f != k])
        for k in range(N)
    ])
    cov_ypyp = np.sum([
        C[k, :].sum() *
        np.sum([C[f, g] for f in range(N) for g in range(N) if f != k])
        for k in range(N)
    ])
    mcc_jurman = cov_ytyp / np.sqrt(cov_ytyt * cov_ypyp)
    mcc_ours = matthews_corrcoef(y_true, y_pred, sample_weight)

    assert_almost_equal(mcc_ours, mcc_jurman, 10) 
開發者ID:PacktPublishing,項目名稱:Mastering-Elasticsearch-7.0,代碼行數:31,代碼來源:test_classification.py

示例13: test_matthews_corrcoef

# 需要導入模塊: from sklearn import metrics [as 別名]
# 或者: from sklearn.metrics import matthews_corrcoef [as 別名]
def test_matthews_corrcoef():
    rng = np.random.RandomState(0)
    y_true = ["a" if i == 0 else "b" for i in rng.randint(0, 2, size=20)]

    # corrcoef of same vectors must be 1
    assert_almost_equal(matthews_corrcoef(y_true, y_true), 1.0)

    # corrcoef, when the two vectors are opposites of each other, should be -1
    y_true_inv = ["b" if i == "a" else "a" for i in y_true]
    assert_almost_equal(matthews_corrcoef(y_true, y_true_inv), -1)

    y_true_inv2 = label_binarize(y_true, ["a", "b"])
    y_true_inv2 = np.where(y_true_inv2, 'a', 'b')
    assert_almost_equal(matthews_corrcoef(y_true, y_true_inv2), -1)

    # For the zero vector case, the corrcoef cannot be calculated and should
    # result in a RuntimeWarning
    mcc = assert_warns_div0(matthews_corrcoef, [0, 0, 0, 0], [0, 0, 0, 0])

    # But will output 0
    assert_almost_equal(mcc, 0.)

    # And also for any other vector with 0 variance
    mcc = assert_warns_div0(matthews_corrcoef, y_true, ['a'] * len(y_true))

    # But will output 0
    assert_almost_equal(mcc, 0.)

    # These two vectors have 0 correlation and hence mcc should be 0
    y_1 = [1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1]
    y_2 = [1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1]
    assert_almost_equal(matthews_corrcoef(y_1, y_2), 0.)

    # Check that sample weight is able to selectively exclude
    mask = [1] * 10 + [0] * 10
    # Now the first half of the vector elements are alone given a weight of 1
    # and hence the mcc will not be a perfect 0 as in the previous case
    assert_raises(AssertionError, assert_almost_equal,
                  matthews_corrcoef(y_1, y_2, sample_weight=mask), 0.) 
開發者ID:PacktPublishing,項目名稱:Mastering-Elasticsearch-7.0,代碼行數:41,代碼來源:test_classification.py

示例14: test_matthews_corrcoef_overflow

# 需要導入模塊: from sklearn import metrics [as 別名]
# 或者: from sklearn.metrics import matthews_corrcoef [as 別名]
def test_matthews_corrcoef_overflow(n_points):
    # https://github.com/scikit-learn/scikit-learn/issues/9622
    rng = np.random.RandomState(20170906)

    def mcc_safe(y_true, y_pred):
        conf_matrix = confusion_matrix(y_true, y_pred)
        true_pos = conf_matrix[1, 1]
        false_pos = conf_matrix[1, 0]
        false_neg = conf_matrix[0, 1]
        n_points = len(y_true)
        pos_rate = (true_pos + false_neg) / n_points
        activity = (true_pos + false_pos) / n_points
        mcc_numerator = true_pos / n_points - pos_rate * activity
        mcc_denominator = activity * pos_rate * (1 - activity) * (1 - pos_rate)
        return mcc_numerator / np.sqrt(mcc_denominator)

    def random_ys(n_points):    # binary
        x_true = rng.random_sample(n_points)
        x_pred = x_true + 0.2 * (rng.random_sample(n_points) - 0.5)
        y_true = (x_true > 0.5)
        y_pred = (x_pred > 0.5)
        return y_true, y_pred

    arr = np.repeat([0., 1.], n_points)  # binary
    assert_almost_equal(matthews_corrcoef(arr, arr), 1.0)
    arr = np.repeat([0., 1., 2.], n_points)  # multiclass
    assert_almost_equal(matthews_corrcoef(arr, arr), 1.0)

    y_true, y_pred = random_ys(n_points)
    assert_almost_equal(matthews_corrcoef(y_true, y_true), 1.0)
    assert_almost_equal(matthews_corrcoef(y_true, y_pred),
                        mcc_safe(y_true, y_pred)) 
開發者ID:PacktPublishing,項目名稱:Mastering-Elasticsearch-7.0,代碼行數:34,代碼來源:test_classification.py

示例15: compute_mcc

# 需要導入模塊: from sklearn import metrics [as 別名]
# 或者: from sklearn.metrics import matthews_corrcoef [as 別名]
def compute_mcc(predicts, labels):
    return 100.0 * matthews_corrcoef(labels, predicts) 
開發者ID:RTIInternational,項目名稱:gobbli,代碼行數:4,代碼來源:metrics.py


注:本文中的sklearn.metrics.matthews_corrcoef方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。