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


Python metrics.classification_report方法代碼示例

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


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

示例1: train_and_evaluate

# 需要導入模塊: from sklearn import metrics [as 別名]
# 或者: from sklearn.metrics import classification_report [as 別名]
def train_and_evaluate(clf, X_train, X_test, y_train, y_test):
    clf.fit(X_train, y_train)
    print ("Accuracy on training set:")
    print (clf.score(X_train, y_train))
    print ("Accuracy on testing set:")
    print (clf.score(X_test, y_test))
    y_pred = clf.predict(X_test)
    print ("Classification Report:")
    print (metrics.classification_report(y_test, y_pred))
    print ("Confusion Matrix:")
    print (metrics.confusion_matrix(y_test, y_pred))


# ===============================================================================
# from FaceDetectPredict.py
# =============================================================================== 
開發者ID:its-izhar,項目名稱:Emotion-Recognition-Using-SVMs,代碼行數:18,代碼來源:Train Classifier and Test Video Feed.py

示例2: eval_batch_col

# 需要導入模塊: from sklearn import metrics [as 別名]
# 或者: from sklearn.metrics import classification_report [as 別名]
def eval_batch_col(classifier, val_dataset, batch_size, device):

    val_batch_generator = datasets.generate_batches_col(val_dataset,
                                               batch_size=batch_size,
                                               shuffle=False,
                                               drop_last=True,
                                               device=device)

    y_pred, y_true = [], []
    for batch_idx, batch_dict in enumerate(val_batch_generator):
        y = batch_dict["label"]
        X = batch_dict["data"]

        # Pred
        pred = classifier(X)
        y_pred.extend(pred.cpu().numpy())
        y_true.extend(y.cpu().numpy())

    
    report = classification_report(y_true, np.argmax(y_pred, axis=1), output_dict=True)
    return report

# evaluate and return prediction & true labels of a table batch 
開發者ID:megagonlabs,項目名稱:sato,代碼行數:25,代碼來源:feature_importance.py

示例3: multi_class_classification

# 需要導入模塊: from sklearn import metrics [as 別名]
# 或者: from sklearn.metrics import classification_report [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

示例4: evaluation_analysis

# 需要導入模塊: from sklearn import metrics [as 別名]
# 或者: from sklearn.metrics import classification_report [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

示例5: score_binary_classification

# 需要導入模塊: from sklearn import metrics [as 別名]
# 或者: from sklearn.metrics import classification_report [as 別名]
def score_binary_classification(y, y_hat, report=True):
    """
    Create binary classification output
    :param y: true value
    :param y_hat: class 1 probabilities
    :param report:
    :return:
    """
    y_hat_class = [1 if x >= 0.5 else 0 for x in y_hat]  # convert probability to class for classification report

    report_string = "---Binary Classification Score--- \n"
    report_string += classification_report(y, y_hat_class)
    score = roc_auc_score(y, y_hat)
    report_string += "\nAUC = " + str(score)

    if report:
        print(report_string)

    return score, report_string 
開發者ID:mbernico,項目名稱:snape,代碼行數:21,代碼來源:score_dataset.py

示例6: score_multiclass_classification

# 需要導入模塊: from sklearn import metrics [as 別名]
# 或者: from sklearn.metrics import classification_report [as 別名]
def score_multiclass_classification(y, y_hat, report=True):
    """
    Create multiclass classification score
    :param y:
    :param y_hat:
    :return:
    """
    report_string = "---Multiclass Classification Score--- \n"
    report_string += classification_report(y, y_hat)
    score = accuracy_score(y, y_hat)
    report_string += "\nAccuracy = " + str(score)

    if report:
        print(report_string)

    return score, report_string 
開發者ID:mbernico,項目名稱:snape,代碼行數:18,代碼來源:score_dataset.py

示例7: print_evaluation

# 需要導入模塊: from sklearn import metrics [as 別名]
# 或者: from sklearn.metrics import classification_report [as 別名]
def print_evaluation(model,data,ls,log=None):
    features,actual = data
    predictions = predict(model, features, 500).data.numpy().reshape(-1).tolist()

    labels = [ls.idx[i] for i, _ in enumerate(ls.idx)]

    actual = [labels[i] for i in actual]
    predictions = [labels[i] for i in predictions]

    print(accuracy_score(actual, predictions))
    print(classification_report(actual, predictions))
    print(confusion_matrix(actual, predictions))

    data = zip(actual,predictions)
    if log is not None:
        f = open(log, "w+")
        for a,p in data:
            f.write(json.dumps({"actual": a, "predicted": p}) + "\n")
        f.close() 
開發者ID:sheffieldnlp,項目名稱:fever-naacl-2018,代碼行數:21,代碼來源:run.py

示例8: evaluate

# 需要導入模塊: from sklearn import metrics [as 別名]
# 或者: from sklearn.metrics import classification_report [as 別名]
def evaluate(config, model, data_iter, test=False):
    model.eval()
    loss_total = 0
    predict_all = np.array([], dtype=int)
    labels_all = np.array([], dtype=int)
    with torch.no_grad():
        for texts, labels in data_iter:
            outputs = model(texts)
            loss = F.cross_entropy(outputs, labels)
            loss_total += loss
            labels = labels.data.cpu().numpy()
            predic = torch.max(outputs.data, 1)[1].cpu().numpy()
            labels_all = np.append(labels_all, labels)
            predict_all = np.append(predict_all, predic)

    acc = metrics.accuracy_score(labels_all, predict_all)
    if test:
        report = metrics.classification_report(labels_all, predict_all, target_names=config.class_list, digits=4)
        confusion = metrics.confusion_matrix(labels_all, predict_all)
        return acc, loss_total / len(data_iter), report, confusion
    return acc, loss_total / len(data_iter) 
開發者ID:649453932,項目名稱:Bert-Chinese-Text-Classification-Pytorch,代碼行數:23,代碼來源:train_eval.py

示例9: calc_test_result

# 需要導入模塊: from sklearn import metrics [as 別名]
# 或者: from sklearn.metrics import classification_report [as 別名]
def calc_test_result(result, test_label, test_mask):

  true_label=[]
  predicted_label=[]

  for i in range(result.shape[0]):
    for j in range(result.shape[1]):
      if test_mask[i,j]==1:
        true_label.append(np.argmax(test_label[i,j] ))
        predicted_label.append(np.argmax(result[i,j] ))
    
  print("Confusion Matrix :")
  print(confusion_matrix(true_label, predicted_label))
  print("Classification Report :")
  print(classification_report(true_label, predicted_label,digits=4))
  print("Accuracy ", accuracy_score(true_label, predicted_label))
  print("Macro Classification Report :")
  print(precision_recall_fscore_support(true_label, predicted_label,average='macro'))
  print("Weighted Classification Report :")
  print(precision_recall_fscore_support(true_label, predicted_label,average='weighted'))
  #print "Normal Classification Report :"
  #print precision_recall_fscore_support(true_label, predicted_label) 
開發者ID:SenticNet,項目名稱:hfusion,代碼行數:24,代碼來源:hfusion.py

示例10: main

# 需要導入模塊: from sklearn import metrics [as 別名]
# 或者: from sklearn.metrics import classification_report [as 別名]
def main():
    args = parse_args()

    features_extractor = FaceFeaturesExtractor()
    embeddings, labels, class_to_idx = load_data(args, features_extractor)
    clf = train(args, embeddings, labels)

    idx_to_class = {v: k for k, v in class_to_idx.items()}

    target_names = map(lambda i: i[1], sorted(idx_to_class.items(), key=lambda i: i[0]))
    print(metrics.classification_report(labels, clf.predict(embeddings), target_names=list(target_names)))

    if not os.path.isdir(MODEL_DIR_PATH):
        os.mkdir(MODEL_DIR_PATH)
    model_path = os.path.join('model', 'face_recogniser.pkl')
    joblib.dump(FaceRecogniser(features_extractor, clf, idx_to_class), model_path) 
開發者ID:arsfutura,項目名稱:face-recognition,代碼行數:18,代碼來源:train.py

示例11: learn_structure

# 需要導入模塊: from sklearn import metrics [as 別名]
# 或者: from sklearn.metrics import classification_report [as 別名]
def learn_structure(self, samples):
        X_train, X_train_label, X_test, X_test_label = \
            self._generate_train_test_sets(samples, 0.75)
        logger.info('Training with ' + str(len(X_train)) +
                    'samples; testing with ' + str(len(X_test)) + ' samples.')

        svc_detector = self._get_best_detector(X_train, X_train_label)
        Y_test = svc_detector.predict(X_test)

        num_anomalies = Y_test[Y_test == ANOMALY].size
        logger.info('Found ' + str(num_anomalies) +
                    ' anomalies in testing set')

        logger.info('Confusion Matrix: \n{}'.
                    format(classification_report(
                        X_test_label,
                        Y_test,
                        target_names=['no', 'yes'])))
        return svc_detector 
開發者ID:openstack,項目名稱:monasca-analytics,代碼行數:21,代碼來源:svc.py

示例12: learn_structure

# 需要導入模塊: from sklearn import metrics [as 別名]
# 或者: from sklearn.metrics import classification_report [as 別名]
def learn_structure(self, samples):
        X_train, X_train_label, X_test, X_test_label = \
            self._generate_train_test_sets(samples, 0.75)
        logger.info('Training with ' + str(len(X_train)) +
                    'samples; testing with ' + str(len(X_test)) + ' samples.')

        dt_detector = self._get_best_detector(X_train, X_train_label)
        Y_test = dt_detector.predict(X_test)

        num_anomalies = Y_test[Y_test == ANOMALY].size
        logger.info('Found ' + str(num_anomalies) +
                    ' anomalies in testing set')

        logger.info('Confusion Matrix: \n{}'.
                    format(classification_report(
                        X_test_label,
                        Y_test,
                        target_names=['no', 'yes'])))
        return dt_detector 
開發者ID:openstack,項目名稱:monasca-analytics,代碼行數:21,代碼來源:decision_tree.py

示例13: learn_structure

# 需要導入模塊: from sklearn import metrics [as 別名]
# 或者: from sklearn.metrics import classification_report [as 別名]
def learn_structure(self, samples):
        X_train, X_train_label, X_test, X_test_label = \
            self._generate_train_test_sets(samples, 0.75)
        logger.info('Training with ' + str(len(X_train)) +
                    'samples; testing with ' + str(len(X_test)) + ' samples.')

        lr_detector = self._get_best_detector(X_train, X_train_label)
        Y_test = lr_detector.predict(X_test)

        num_anomalies = Y_test[Y_test == ANOMALY].size
        logger.info('Found ' + str(num_anomalies) +
                    ' anomalies in testing set')

        logger.info('Confusion Matrix: \n{}'.
                    format(classification_report(
                        X_test_label,
                        Y_test,
                        target_names=['no', 'yes'])))
        return lr_detector 
開發者ID:openstack,項目名稱:monasca-analytics,代碼行數:21,代碼來源:logistic_regression.py

示例14: learn_structure

# 需要導入模塊: from sklearn import metrics [as 別名]
# 或者: from sklearn.metrics import classification_report [as 別名]
def learn_structure(self, samples):
        X_train, X_train_label, X_test, X_test_label = \
            self._generate_train_test_sets(samples, 0.75)
        logger.info('Training with ' + str(len(X_train)) +
                    'samples; testing with ' + str(len(X_test)) + ' samples.')

        rf_detector = self._get_best_detector(X_train, X_train_label)
        Y_test = rf_detector.predict(X_test)

        num_anomalies = Y_test[Y_test == ANOMALY].size
        logger.info('Found ' + str(num_anomalies) +
                    ' anomalies in testing set')

        logger.info('Confusion Matrix: \n{}'.
                    format(classification_report(
                        X_test_label,
                        Y_test,
                        target_names=['no', 'yes'])))
        return rf_detector 
開發者ID:openstack,項目名稱:monasca-analytics,代碼行數:21,代碼來源:random_forest_classifier.py

示例15: test_classification_report_multiclass

# 需要導入模塊: from sklearn import metrics [as 別名]
# 或者: from sklearn.metrics import classification_report [as 別名]
def test_classification_report_multiclass():
    # Test performance report
    iris = datasets.load_iris()
    y_true, y_pred, _ = make_prediction(dataset=iris, binary=False)

    # print classification report with class names
    expected_report = """\
              precision    recall  f1-score   support

      setosa       0.83      0.79      0.81        24
  versicolor       0.33      0.10      0.15        31
   virginica       0.42      0.90      0.57        20

    accuracy                           0.53        75
   macro avg       0.53      0.60      0.51        75
weighted avg       0.51      0.53      0.47        75
"""
    report = classification_report(
        y_true, y_pred, labels=np.arange(len(iris.target_names)),
        target_names=iris.target_names)
    assert_equal(report, expected_report) 
開發者ID:PacktPublishing,項目名稱:Mastering-Elasticsearch-7.0,代碼行數:23,代碼來源:test_classification.py


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