🤍 전 강의 25% 할인 중 🤍

2024년 상반기를 돌아보고 하반기에도 함께 성장해요!
인프런이 준비한 25% 할인 받으러 가기 >>

캐글 T2-4 집값 예측 라벨인코딩 하려는데,,

23.11.24 15:52 작성 23.11.24 15:53 수정 조회수 124

0

풀이에서는

 <이건 풀이코드 중 일부 발췌>

Preprocessing

In [10]:

X_train = X_train.select_dtypes(exclude=['object'])

X_test = X_test.select_dtypes(exclude=['object'])

target = y_train['SalePrice']

 

In [11]:

X_train.head(3)

In [12]:

from sklearn.impute import SimpleImputer

 

이렇게 범주형 제외시키고 수치형으로 전처리 끝낸 다음에 SimpleImputer로 핏, 예측했는데

 

 

<이건 제가 해보려 한 라벨인코딩>

제가 범주형데이터 잡고 라벨인코딩으로 전처리를 하려고 해봤는데

 

cols = X_train.select_dtypes(include='object').columns
from sklearn.preprocessing import LabelEncoder
le = LabelEncoder()
for col in cols:
    X_train[col] = le.fit_transform(X_train[col])
    X_test[col] = le.transform(X_test[col])
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/opt/conda/lib/python3.7/site-packages/sklearn/preprocessing/_label.py in _encode(values, uniques, encode, check_unknown)
    112         try:
--> 113             res = _encode_python(values, uniques, encode)
    114         except TypeError:

/opt/conda/lib/python3.7/site-packages/sklearn/preprocessing/_label.py in _encode_python(values, uniques, encode)
     60     if uniques is None:
---> 61         uniques = sorted(set(values))
     62         uniques = np.array(uniques, dtype=values.dtype)

TypeError: '<' not supported between instances of 'str' and 'float'

During handling of the above exception, another exception occurred:

TypeError                                 Traceback (most recent call last)
/tmp/ipykernel_20/2364802253.py in <module>
      3 le = LabelEncoder()
      4 for col in cols:
----> 5     X_train[col] = le.fit_transform(X_train[col])
      6     X_test[col] = le.transform(X_test[col])

/opt/conda/lib/python3.7/site-packages/sklearn/preprocessing/_label.py in fit_transform(self, y)
    254         """
    255         y = column_or_1d(y, warn=True)
--> 256         self.classes_, y = _encode(y, encode=True)
    257         return y
    258 

/opt/conda/lib/python3.7/site-packages/sklearn/preprocessing/_label.py in _encode(values, uniques, encode, check_unknown)
    115             types = sorted(t.__qualname__
    116                            for t in set(type(v) for v in values))
--> 117             raise TypeError("Encoders require their input to be uniformly "
    118                             f"strings or numbers. Got {types}")
    119         return res

TypeError: Encoders require their input to be uniformly strings or numbers. Got ['float', 'str']

 

이러한 에러가 뜨더라구요,, 범주형 데이터 잡고 라벨인코딩으로 하면 안되는 문제인건가요??

 

답변 1

답변을 작성해보세요.

0

인프런 AI 인턴님의 프로필

인프런 AI 인턴

2023.11.24

안녕하세요, 인프런 AI 인턴입니다.

chandnd37님, 라벨 인코딩 과정에서 발생한 문제를 살펴보겠습니다. 에러 메시지에 따르면 “Encoders require their input to be uniformly strings or numbers” 즉, 인코더는 입력값이 일관된 문자열이나 숫자여야 한다는 메시지가 나타나고 있습니다. 보통 이런 에러는 데이터에 NaN 값이나 다른 타입의 불일치가 있을 때 발생합니다.

라벨 인코딩을 적용하기 전에 모든 범주형 데이터가 결측값을 포함하지 않도록 처리하셔야 합니다. 결측값을 처리하는 하나의 방법으로 특정한 값으로 채우거나 제거하는 방법이 있습니다. 예를 들어, pandas의 fillna 함수를 사용하여 결측값을 적절한 값으로 채우거나, dropna 함수로 제거할 수 있습니다.

처리를 위해 다음 코드를 참고해보시길 권장합니다.

for col in cols:
    X_train[col] = X_train[col].fillna('NotAvailable')
    X_test[col] = X_test[col].fillna('NotAvailable')
    le.fit(X_train[col])
    X_train[col] = le.transform(X_train[col])
    X_test[col] = le.transform(X_test[col])

코드에서 ‘NotAvailable’은 결측값을 대체하기 위한 가상의 범주입니다. 실제 데이터와 맥락에 맞는 값을 사용하는 것이 중요합니다. 대체 값을 선정할 때는 데이터의 특성을 잘 고려하여 결측값이 있는 범주형 데이터의 처리를 선택해야 합니다.

이렇게 결측치를 처리한 후 라벨 인코딩을 진행하시면 에러 없이 진행하실 수 있을 것입니다.

chandnd37님의 프로필

chandnd37

2023.11.24

add Codeadd Markdown

[337]:

cols = X_train.select_dtypes(include='object').columns
from sklearn.preprocessing import LabelEncoder
le = LabelEncoder()
for col in cols:
    X_train[col] = X_train[col].fillna('NotAvailable')
    X_test[col] = X_test[col].fillna('NotAvailable')
    le.fit(X_train[col])
    X_train[col] = le.fit_transform(X_train[col])
    X_test[col] = le.transform(X_test[col])
X_train.head()

 

똑같이 따라했으며 런타임 이전실행 하고 실행했더니 이런 에러가 뜹니다

 

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
/opt/conda/lib/python3.7/site-packages/sklearn/preprocessing/_label.py in _encode_python(values, uniques, encode)
     65         try:
---> 66             encoded = np.array([table[v] for v in values])
     67         except KeyError as e:

/opt/conda/lib/python3.7/site-packages/sklearn/preprocessing/_label.py in <listcomp>(.0)
     65         try:
---> 66             encoded = np.array([table[v] for v in values])
     67         except KeyError as e:

KeyError: 'Membran'

During handling of the above exception, another exception occurred:

ValueError                                Traceback (most recent call last)
/tmp/ipykernel_20/1209145931.py in <module>
      7     le.fit(X_train[col])
      8     X_train[col] = le.fit_transform(X_train[col])
----> 9     X_test[col] = le.transform(X_test[col])
     10 X_train.head()

/opt/conda/lib/python3.7/site-packages/sklearn/preprocessing/_label.py in transform(self, y)
    275             return np.array([])
    276 
--> 277         _, y = _encode(y, uniques=self.classes_, encode=True)
    278         return y
    279 

/opt/conda/lib/python3.7/site-packages/sklearn/preprocessing/_label.py in _encode(values, uniques, encode, check_unknown)
    111     if values.dtype == object:
    112         try:
--> 113             res = _encode_python(values, uniques, encode)
    114         except TypeError:
    115             types = sorted(t.__qualname__

/opt/conda/lib/python3.7/site-packages/sklearn/preprocessing/_label.py in _encode_python(values, uniques, encode)
     67         except KeyError as e:
     68             raise ValueError("y contains previously unseen labels: %s"
---> 69                              % str(e))
     70         return uniques, encoded
     71     else:

ValueError: y contains previously unseen labels: 'Membran'
채널톡 아이콘