원핫인코더 돌리니깐 데이터 길이가 줄어들었습니다.
조회수 4595회
import pandas as pd
from sklearn.model_selection import train_test_split
mushroom = pd.read_csv("../data/mushroom.csv", header = None)
mushroom[0] = mushroom[0].replace("p", float(1))
mushroom[0] = mushroom[0].replace("e", float(0))
from sklearn.preprocessing import OneHotEncoder
from sklearn.compose import ColumnTransformer
ct = ColumnTransformer(
[('one_hot_encoder', OneHotEncoder(categories='auto'), [0])],
remainder='passthrough'
)
feat = mushroom.iloc[1:]
mush = ct.fit_transform(feat)
y = mushroom[0] == 1
X_train, X_test, y_train, y_test = train_test_split(mush, y, random_state = 0)
버섯이 식용가능한지 독버섯인지 예측 하는 문제입니다. 데이터가 str형태로 되어있어서 식용이냐 아니냐만 float(1, 0)로 변경하고 나머지 특성은 원핫인코더를 써서 처리하여고 하였습니다. 훈련셋과 테스트셋을 나누려고 하면 에러가 발생합니다.
ValueError: Found input variables with inconsistent numbers of samples: [8123, 8124]
데이터와 레이블의 길이가 안맞아 에러가 나는 거 같아서 shape를 확인하였습니다.
mush.shape
(8123, 24)
y.shape
(8124,)
원핫인코더를 돌린 데이터의 길이가 줄어있는 것을 확인하였습니다.
- 길이가 줄어드는 원인을 모르겠습니다.
- 데이터와 레이블의 길이를 맞춰주려면 어떻게 처리해야 할지 여쭙고 싶습니다.
1 답변
-
>>> import pandas as pd >>> df = pd.DataFrame({"A":[1,2,1,1,1,1], "B":[33,24,52,66,22,111]}) >>> df A B 0 1 33 1 2 24 2 1 52 3 1 66 4 1 22 5 1 111 >>> df.shape (6, 2) >>> f = df.iloc[1:] >>> f A B 1 2 24 2 1 52 3 1 66 4 1 22 5 1 111 >>> y = df['A'] == 1 >>> y 0 True 1 False 2 True 3 True 4 True 5 True Name: A, dtype: bool >>> f.shape (5, 2) >>> y.shape (6,)
당연한 결과입니다.
위에 아주 간단한 데이터프레임을 가지고, 예시를 들었습니다.
- 원래 데이터프레임 df의 모양은 (6, 2) 이죠.
- 이 df 에 대해서,
df.iloc[1:]
은 제일 첫번째 row 를 뺀 나머지이기 때문에, shape 이 (5, 2) 가 됩니다. df['A'] == 1
은 "A"컬럼의 값이 1인지를 나타내는 시리즈가 되죠. 그래서 원래 길이인 (6,) 이 그 shape 이됩니다.
보면, OneHot 을 하는 과정에서 길이가 하나 줄어든 게 아니에요. 아마도 mushroom.iloc[:, 1:] 이 질문자가 원하던 게 아닌가 싶어요.
>>> f1 = df.iloc[:,1:] >>> f1 B 0 33 1 24 2 52 3 66 4 22 5 111 >>> f1.shape (6, 1)
댓글 입력