Как минимум одна указанная метка должна быть в y_true, целевой вектор числовой - PullRequest
0 голосов
/ 01 марта 2020

Я реализую проект SVM с этими данными

, вот как я извлекаю функции:

import itertools
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn import svm
from sklearn.metrics import classification_report, confusion_matrix

df = pd.read_csv('loan_train.csv')
df['due_date'] = pd.to_datetime(df['due_date'])
df['effective_date'] = pd.to_datetime(df['effective_date'])
df['dayofweek'] = df['effective_date'].dt.dayofweek
df['weekend'] = df['dayofweek'].apply(lambda x: 1 if (x>3)  else 0)
Feature = df[['Principal','terms','age','Gender','weekend']]
Feature = pd.concat([Feature,pd.get_dummies(df['education'])], axis=1)
Feature.drop(['Master or Above'], axis = 1,inplace=True)

X = Feature
y = df['loan_status'].replace(to_replace=['PAIDOFF','COLLECTION'], value=[0,1],inplace=False)

создание модели и прогноз:

clf = svm.SVC(kernel='rbf')
clf.fit(X_train_svm, y_train_svm)
yhat_svm = clf.predict(X_test_svm)

фаза оценки:

def plot_confusion_matrix(cm, classes,
                          normalize=False,
                          title='Confusion matrix',
                          cmap=plt.cm.Blues):
    """
    This function prints and plots the confusion matrix.
    Normalization can be applied by setting `normalize=True`.
    """
    if normalize:
        cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
        print("Normalized confusion matrix")
    else:
        print('Confusion matrix, without normalization')

    print(cm)

    plt.imshow(cm, interpolation='nearest', cmap=cmap)
    plt.title(title)
    plt.colorbar()
    tick_marks = np.arange(len(classes))
    plt.xticks(tick_marks, classes, rotation=45)
    plt.yticks(tick_marks, classes)

    fmt = '.2f' if normalize else 'd'
    thresh = cm.max() / 2.
    for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
        plt.text(j, i, format(cm[i, j], fmt),
                 horizontalalignment="center",
                 color="white" if cm[i, j] > thresh else "black")

    plt.tight_layout()
    plt.ylabel('True label')
    plt.xlabel('Predicted label')
    plt.show()


cnf_matrix = confusion_matrix(y_test_svm, yhat_svm, labels=[2,4])
np.set_printoptions(precision=2)

print (classification_report(y_test_svm, yhat_svm))

# Plot non-normalized confusion matrix
plt.figure()
plot_confusion_matrix(cnf_matrix, classes=['Benign(2)','Malignant(4)'],normalize= False,  title='Confusion matrix')

здесь есть ошибка:

Трассировка (последний последний вызов):

Файл "E: / python /ification_project /ification.py ", строка 229, в

cnf_matrix = confusion_matrix (y_test_svm, yhat_svm, метки = [2,4])

файл" C: \ Program Files (x86) \ Python38-32 \ lib \ site-packages \ sklearn \ metrics_classification.py ", строка 277, в confusion_matrix

повышение ValueError (" По крайней мере одна указанная метка должна быть в y_true ")

ValueError: Как минимум одна указанная метка должна быть в y_true

Я проверил этот вопрос , который был похож на мой, и я изменил y с categorical на numerical но ошибка все еще там!

1 Ответ

0 голосов
/ 01 марта 2020

значениями в y являются 0 и 1, но в confusion_matrix вызов:

cnf_matrix = confusion_matrix(y_test_svm, yhat_svm, labels=[2,4])

метки были 2 и 4.
метки в confusion_matrix должны быть равны токенам в y векторе, ie:

cnf_matrix = confusion_matrix(y_test_svm, yhat_svm, labels=[0,1])
...