• 카테고리

    질문 & 답변
  • 세부 분야

    자격증 (데이터 사이언스)

  • 해결 여부

    해결됨

예시문제 작업형2(구 버전)

23.11.26 20:58 작성 조회수 200

0

ValueError: array length 2482 does not match index length 3500

제가 안보고 풀어봤는데 이런 에러가 뜨는건 무슨 이유일까요..

밑에는 제가 작성한 코드입니다. # 5. 평가까지 잘 돌아가다가 # 6. 제출 부분 작성하니깐 갑자기 저런 오류가 뜨네요 ㅠㅠ.. 제 코드 중에 어느 부분이 잘못된 걸까요..

 

# 2. 전처리
# 2-1. 결측치 처리
# print(X_train.isnull().sum())
X_train['환불금액'] = X_train['환불금액'].fillna(0)
X_test['환불금액'] = X_test['환불금액'].fillna(0)

# 2-2. object 컬럼 라벨인코딩
from sklearn.preprocessing import LabelEncoder
cols = ['주구매상품', '주구매지점']
le = LabelEncoder()
for col in cols :
        X_train[col] = le.fit_transform(X_train[col])
        X_test[col] = le.transform(X_test[col])

# 2-3. 불필요한 컬럼 삭제
X_train = X_train.drop(columns = 'cust_id')
X_test = X_test.drop(columns = 'cust_id')
test_id = y_train.pop('cust_id')

# 3. 분리
from sklearn.model_selection import train_test_split
X_tr, X_val, y_tr, y_val = train_test_split(X_train, y_train['gender'], test_size = 0.2, random_state = 2022)

# 4. 학습
from sklearn.ensemble import RandomForestClassifier
model = RandomForestClassifier(random_state = 2022)
model.fit(X_tr, y_tr)
pred = model.predict_proba(X_val)

# 5. 평가
from sklearn.metrics import roc_auc_score
# print(roc_auc_score(y_val , pred[:, 1]))

# 6. 제출
pred = model.predict_proba(X_test)
pd.DataFrame({'custid' : test_id, 'gender' : pred[:,1]}).to_csv('00000.csv', index = False)
# print(pd.read_csv('00000.csv'))

답변 2

·

답변을 작성해보세요.

0

시험에서 0점 맞기 쉬운 부분입니다.

컬럼의 수가 다름을 이전에는 id와 예측 결과가 달라서 이렇게 에러로 발견할 수 있었지만

지금은 예측컬럼만 제출하기 때문에 이렇게 발견하기 어렵습니다.

제출하기 전에 예측 컬럼의 수가 맞는지 반드시 확인해주세요!!

김민정님의 프로필

김민정

질문자

2023.11.28

컬럼 수 확인하는 습관이 잘 안돼서 ㅠㅠ 연습 많이 하겠습니다!

0

Jason님의 프로필

Jason

2023.11.26

pd.DataFrame 만드실 때,

test_id를 y_train에 있는 cust_id 값으로 만드신 거 같은데요

y_train shape이 아마 3500 이었을거 같고,

결과값으로 저장하시려는 gender의 예측값은 2482개라서 에러발생한거 같습니다.

 

분리과정에서 y_train['gender']에 대한 시리즈 값을 명시하셨으니,

drop 과정에서 y_train은 column drop이라던지 pop 없이

test_id = X_test.pop('cust_id')로 pop 하시면 될거같습니다.

김민정님의 프로필

김민정

질문자

2023.11.26

# 2-3. 불필요한 컬럼 삭제

X_train = X_train.drop(columns = 'cust_id')

test_id = X_test.pop('cust_id')

y_train = y_train.drop(columns = 'cust_id')

혹시 이렇게 수정하면 되는걸까요?

 

만약 분리과정이 없었더라면 아래와 같이 그대로 사용하면 되는걸까요?

# 2-3. 불필요한 컬럼 삭제

X_train = X_train.drop(columns = 'cust_id')

X_test = X_test.drop(columns = 'cust_id')

test_id = y_train.pop('cust_id')

 

 

 

Jason님의 프로필

Jason

2023.11.26

네 아래 코드로 하시면 test_id가 X_test 'cust_id'를 받기때문에 DataFrame 생성시 pred하고 같은 행수를 가질거 같습니다.

저라면 분리과정에서 y_train['Gender']라고 명시하셨기때문에 drop 처리는 하지 않을거같습니다.

 

X_train = X_train.drop(columns = 'cust_id')

test_id = X_test.pop('cust_id')

근데 만약 분리과정에서 y_train['Gender']가 아닌 y_train으로 하셨으면

앞서 컬럼 삭제시 y_train에 'cust_id' 컬럼을 삭제해야 'Gender'만 남는 시리즈 형태가 되기 때문에 아래와 같이 작성할거같습니다.

X_train = X_train.drop(columns = 'cust_id')

y_train = y_train.drop(columns = 'cust_id')

test_id = X_test.pop('cust_id')

김민정님의 프로필

김민정

질문자

2023.11.28

덕분에 이해가 잘 가네요.. 상세한 답변 감사합니다!!