Python: ValueError: The number of classes has to be greater than one; got 1

本秂侑毒 提交于 2019-12-13 09:35:40

问题


Following Tonechas suggestion from this post, the code to compute the red channel histogram of a set of images and then classify them to the correct type, is this:

import cv2
import os
import glob
import numpy as np
from skimage import io


root = "C:/Users/joasa/data/train"
folders = ["Type_1", "Type_2", "Type_3"]
extension = "*.jpg"


# skip errors caused by corrupted files

def file_is_valid(filename):
    try:
        io.imread(filename)
        return True
    except:
        return False

def compute_red_histogram(root, folders, extension):
    X = []
    y = []
    for n, imtype in enumerate(folders):
        filenames = glob.glob(os.path.join(root, imtype, extension))
        for fn in filter(file_is_valid, filenames):
            print(fn)
            image = io.imread(fn)
            img = cv2.resize(image, None, fx=0.1, fy=0.1, interpolation=cv2.INTER_AREA)
            red = img[:, :, 0]
            h, _ = np.histogram(red, bins=np.arange(257), normed=True)
            X.append(h)
            y.append(n)
     return np.vstack(X), np.array(y)

X, y = compute_red_histogram(root, folders, extension)

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.5, random_state = 0)

from sklearn.svm import SVC
clf = SVC()
clf.fit(X_train, y_train)

y_test
clf.predict(X_test)
y_test == clf.predict(X_test)
score = clf.score(X_test, y_test)

prediction = pd.DataFrame(y_test, score, columns=['prediction', 'score']).to_csv('prediction.csv')

I get this error:

ValueError: The number of classes has to be greater than one; got 1

Can someone help with this? Thanks


回答1:


Look at you function:

def compute_red_histogram(root, folders, extension):
    X = []
    y = []
    for n, imtype in enumerate(folders):
        filenames = glob.glob(os.path.join(root, imtype, extension))
        for fn in filter(file_is_valid, filenames):
            print(fn)
            image = io.imread(fn)
            img = cv2.resize(image, None, fx=0.1, fy=0.1, interpolation=cv2.INTER_AREA)
            red = img[:, :, 0]
            h, _ = np.histogram(red, bins=np.arange(257), normed=True)
            X.append(h)
            y.append(n)
        return np.vstack(X), np.array(y) ## <--- this line is not properly indented.

You return at the end of the first iteration of the for loop over folders. you need to un-indent this line.




回答2:


I just have the same problem and I figured out some times the label or the target is String when ur data is downloaded try y=y.astype(np.uint8)



来源:https://stackoverflow.com/questions/44239189/python-valueerror-the-number-of-classes-has-to-be-greater-than-one-got-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!