2
respostas

ValueError em algoritmo de KFold cros validation

Estou a alguns dias tentando descobrir o que está errado no código:

https://ufile.io/v40hn

O erro recebido é :

ValueError                                Traceback (most recent call last)
<ipython-input-146-7b43b4b0f9d0> in <module>()
      6     y_train, y_test = classe[train_index], classe[test_index]
      7 
----> 8     logmodel.fit(X_train, y_train)
      9     print (confusion_matrix(y_test, logmodel.predict(X_test)))
     10 

/usr/local/lib/python3.6/dist-packages/sklearn/linear_model/logistic.py in fit(self, X, y, sample_weight)
   1249             raise ValueError("This solver needs samples of at least 2 classes"
   1250                              " in the data, but the data contains only one"
-> 1251                              " class: %r" % classes_[0])
   1252 
   1253         if len(self.classes_) == 2:

ValueError: This solver needs samples of at least 2 classes in the data, but the data contains only one class: 0

O trecho onde ocorre o erro é:

kf = KFold(n_splits=6, random_state=None, shuffle=False)
kf.get_n_splits(previsores)
for train_index, test_index in kf.split(previsores):

    X_train, X_test = previsores[train_index], previsores[test_index]
    y_train, y_test = classe[train_index], classe[test_index]

    logmodel.fit(X_train, y_train)
    print (confusion_matrix(y_test, logmodel.predict(X_test)))


    lista_matrizes.append(confusion_matrix(y_test, logmodel.predict(X_test)))
print(f" Matriz de Confusão Média \n{np.mean(lista_matrizes, axis=0)}")

O que fazer? O mais estranho é que algumas vezes o erro não ocorre e o programa executa normalmente!

2 respostas

Olá Edson, eu não testei mas dei uma pesquisada rápida aqui e parece ser um bug do sparkit-learn : https://github.com/lensacom/sparkit-learn/issues/49

Também tem outras discussões no stackoverflow propondo possíveis soluções: https://stackoverflow.com/questions/38138067/valueerror-this-solver-needs-samples-of-at-least-2-classes-in-the-data-but-the

Encontrei outra solução possível neste site: https://blog.minhazav.xyz/2016/06/23/1_notmnist-this-solver-needs-samples-of-at-least-2-classes-in-the-data-but-the-data-contains-only-one-class/

@Thais Thomazini Andre: Obrigado!