L oop экземпляры добавляют строку бесконечно - PullRequest
0 голосов
/ 30 января 2020

Я попытался закодировать в OOP таблицу, которая будет возвращать некоторые статистические метрики для алгоритмов, и отобразить в pandas DataFrame в Python.

У меня возникла проблема, где для каждого Например, имя столбца добавляет дополнительную строку «прогнозируемый» к создаваемому фрейму данных (пример в конце).

мой код:

from sklearn.metrics import roc_auc_score, accuracy_score, cohen_kappa_score, recall_score, accuracy_score, precision_score, f1_score
from sklearn import metrics

#----------------------------------------------------------------#        
####################### ROC metrics table ########################
#----------------------------------------------------------------# 


class roc_table:
    def __init__(self, data):
        self.data = data


    def viewer():


        #count columns in dataframe
        count_algo = len(data.columns)

        for i in data.iloc[:,1:]:
            data['predicted_{}'.format(i)] = (data[i] >= threshold).astype('int')

        rock_table = {
            "AUC":[round(roc_auc_score(data.actual_label, data[i]),2) for i in data.iloc[:,count_algo:]],
            "Accuracy":[round(accuracy_score(data.actual_label, data[i]),2) for i in data.iloc[:,count_algo:]],
            "Kappa":[round(cohen_kappa_score(data.actual_label, data[i]),2)for i in data.iloc[:,count_algo:]],
            "Sensitivity (Recall)": [round(recall_score(data.actual_label, data[i]),2) for i in data.iloc[:,count_algo:]],
            "Specificity": [round(accuracy_score(data.actual_label, data[i]),2) for i in data.iloc[:,count_algo:]],
            "Precision": [round(precision_score(data.actual_label, data[i]),2) for i in data.iloc[:,count_algo:]],
            "F1": [round(f1_score(data.actual_label, data[i]),2) for i in data.iloc[:,count_algo:]]
        }   

        rock_table = pd.DataFrame.from_dict(rock_table, orient = 'index').reset_index()
        col = ['metrics']
        col.extend([x for x in data.iloc[:,count_algo:]])
        rock_table.columns = col    

        return rock_table

эта строка доставляет мне проблемы:

for i in data.iloc[:,1:]:
            data['predicted_{}'.format(i)] = (data[i] >= threshold).astype('int')

пример выводов, которые я получаю при запуске: enter image description here

1 Ответ

1 голос
/ 30 января 2020

Проблема с вашей OOP реализацией. Вы изменяете исходные данные, передаваемые в класс " roc_table ".

Пожалуйста, попробуйте следующее:

class roc_table:
def __init__(self, data):
    self.org_data = data


def viewer(self, threshold):

    #make a copy of initial data
    data = self.org_data.copy()

    #count columns in dataframe
    count_algo = len(data.columns)

    for i in data.iloc[:,1:]:
        data['predicted_{}'.format(i)] = (data[i] >= threshold).astype('int')

    rock_table = {
        "AUC":[round(roc_auc_score(data.actual_label, data[i]),2) for i in data.iloc[:,count_algo:]],
        "Accuracy":[round(accuracy_score(data.actual_label, data[i]),2) for i in data.iloc[:,count_algo:]],
        "Kappa":[round(cohen_kappa_score(data.actual_label, data[i]),2)for i in data.iloc[:,count_algo:]],
        "Sensitivity (Recall)": [round(recall_score(data.actual_label, data[i]),2) for i in data.iloc[:,count_algo:]],
        "Specificity": [round(accuracy_score(data.actual_label, data[i]),2) for i in data.iloc[:,count_algo:]],
        "Precision": [round(precision_score(data.actual_label, data[i]),2) for i in data.iloc[:,count_algo:]],
        "F1": [round(f1_score(data.actual_label, data[i]),2) for i in data.iloc[:,count_algo:]]
    }   

    rock_table = pd.DataFrame.from_dict(rock_table, orient = 'index').reset_index()
    col = ['metrics']
    col.extend([x for x in data.iloc[:,count_algo:]])
    rock_table.columns = col    

    return rock_table

, а затем создайте экземпляр класса следующим образом и используйте:

rt = roc_table(data)
threshold=0.5
rt.viewer(threshold)
threshold=0.75
rt.viewer(threshold)

Таким образом, исходные данные не видоизменяются.

Надеюсь, это поможет.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...