TypeError: Encoders require their input to be uniformly strings or numbers.

    에러 발생 내용

    Traceback (most recent call last): File "C:\ProgramData\Anaconda3\lib\site-packages\sklearn\preprocessing\_label.py", line 113, in _encode res = _encode_python(values, uniques, encode) File "C:\ProgramData\Anaconda3\lib\site-packages\sklearn\preprocessing\_label.py", line 61, in _encode_python uniques = sorted(set(values)) TypeError: '<' not supported between instances of 'float' and 'str' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "Y:/Project/gendlca/python-source/gendlca/train_job_classifier.py", line 25, in <module> df['job_encoded'] = label_encoder.fit_transform(df['job']) File "C:\ProgramData\Anaconda3\lib\site-packages\sklearn\preprocessing\_label.py", line 256, in fit_transform self.classes_, y = _encode(y, encode=True) File "C:\ProgramData\Anaconda3\lib\site-packages\sklearn\preprocessing\_label.py", line 117, in _encode raise TypeError("Encoders require their input to be uniformly " TypeError: Encoders require their input to be uniformly strings or numbers. Got ['float', 'str'] Process finished with exit code 1

     

    판다스(Pandas)로 데이터를 읽은 후, job에 있는 위치의 값을 LabelEncoder로 fit_transform 할 때 발생하였다. fit_transform은 scikit-learn 라이브러리의 preprocessing 모듈에 있는 클래스로 범주형 레이블을 정수로 변환하는데 사용된다. 즉, 문자열을 정수형으로 변환하다 에러가 발생한 것이다. 

     

    에러 발생 원인

    아래는 ChatGPT 4.0에게 물어본 내용이다.

     

    TypeError: Encoders require their input to be uniformly strings or numbers. 에러는 scikit-learn의 인코더(예: LabelEncoder, OneHotEncoder)가 입력 데이터가 일관되게 문자열이나 숫자로 구성되어 있지 않을 때 발생합니다. 인코더는 입력 데이터가 일관된 유형으로 제공되기를 요구하므로, 입력 데이터에 문자열과 숫자가 혼합되어 있는 경우 이와 같은 에러가 발생할 수 있습니다.

     

    해결 방법은 다음과 같습니다.

    1. 입력 데이터를 확인하여 문자열과 숫자가 혼합되어 있는지 확인합니다.
    2. 모든 항목을 문자열 또는 숫자로 변환하여 일관성을 유지합니다. 예를 들어, 숫자를 문자열로 변환하려면 다음과 같이 할 수 있습니다:

     

    에러 해결책 예시

    from sklearn.preprocessing import LabelEncoder
    
    # 혼합된 유형의 입력 데이터
    input_data = [1, 'cat', 3, 'dog']
    
    # 모든 항목을 문자열로 변환
    input_data = [str(item) for item in input_data]
    
    # LabelEncoder 객체 생성
    encoder = LabelEncoder()
    
    # 변환된 데이터를 인코더에 전달하여 레이블을 정수로 변환
    encoded_labels = encoder.fit_transform(input_data)
    
    # 변환된 레이블 출력
    print(encoded_labels)

     

    데이터를 일관되게 넣어야 하는데 숫자등의 값이 있을 경우 문제이므로, 이를 str으로 감싸서 해결을 한다.

     

     

     

     

    반응형

    댓글

    Designed by JB FACTORY