기사 (2회): 기출유형-작업형2 풀이 오류 해석
안녕하세요.
강의 잘 듣고 있습니다. 매번 질문에 답해주셔서 감사합니다.
아래와 같이 코드를 짰는데
데이터 프레임 만들기 submit = 에서 오류가 발생해서요.
해당 오류가... 무슨 뜻인지 알려주세요.
앞에서 test_id삭제하고 .pop을 빼먹었는데... 이것 땜에 발생했을까요?
<오류내역>
ValueError Traceback (most recent call last)
<ipython-input-30-13b5884e1ac8> in <cell line: 63>()
61
62 # 데이터 내보내기
---> 63 submit = pd.DataFrame(
64 {
65 'ID': X_test['ID'],
/usr/local/lib/python3.10/dist-packages/pandas/core/internals/construction.py in extractindex(data)
678 f"length {len(index)}"
679 )
--> 680 raise ValueError(msg)
681 else:
682 index = default_index(lengths[0])
ValueError: array length 1760 does not match index length 2200
<코드>
# 라이브러리 및 데이터 불러오기
import pandas as pd
X_train = pd.read_csv("X_train.csv")
y_train = pd.read_csv("y_train.csv")
X_test = pd.read_csv("X_test.csv")
# EDA
print(X_train.head())
print(X_test.head())
print(y_train.head())
pd.set_option('display.max_columns', None)
print(X_train.shape, X_test.shape, y_train.shape) # (8799, 11) (2200, 11) (8799, 2)
print(X_train.info)
print(X_train.describe())
print(X_train.describe(include = 'object')) # Warehouse_block, Mode_of_Shipment, Product_importance, Gender
print(X_train.isnull().sum()) # 결측치 없음
print(y_train.value_counts('Reached.on.Time_Y.N')) #1 5236, 0 3563
# 데이터 전처리
# 피처엔지니어링
# 라벨 인코딩
from sklearn.preprocessing import LabelEncoder
cols = ['Warehouse_block', 'Mode_of_Shipment', 'Product_importance', 'Gender']
cols1 = X_train.select_dtypes(include = 'object').columns
for col in cols:
la = LabelEncoder()
X_train[col] = la.fit_transform(X_train[col])
X_test[col] = la.transform(X_test[col])
# 데이터 분할
from sklearn.model_selection import train_test_split
X_tr, X_val, y_tr, y_val = train_test_split(X_train, y_train['Reached.on.Time_Y.N'],test_size = 0.2, random_state = 2023)
print(X_tr.shape, X_val.shape, y_tr.shape, y_val.shape) #(7039, 11) (1760, 11) (7039,) (1760,)
# 모델링
#분류(랜덤포레스트)
from sklearn.ensemble import RandomForestClassifier
model = RandomForestClassifier(random_state = 2023)
model.fit(X_tr, y_tr)
predict = model.predict_proba(X_val)
print(predict)
print(predict[:,1])
# 평가(ROC_AUC_SCORE)
from sklearn.metrics import roc_auc_score
pred=roc_auc_score(y_val, predict[:,1])
print(pred) # 랜덤포레스트 분류: 0.7340529818205483
# 예측
result = model.predict_proba(X_test)
# 데이터 내보내기
submit = pd.DataFrame(
{
'ID': X_test['ID'],
'Reached.on.Time_Y.N' : predict[:,1]
}
)
submit.to_csv("1111.csv", index = False)
답변 1
1
안녕하세요
ValueError: array length 1760 does not match index length 2200
는 데이터 길이가 다르다는 뜻이에요
1760을 한번 찾아봐 주시겠어요? 잘 살펴보면 val 길이가 1760인 것을 확인할 수 있어요
그렇다면 ID값은 2200개이고 예측값(val)이 1760이 아닌지 의심해 볼 여지가 있겠네요
예측값은 'Reached.on.Time_Y.N' : predict[:,1] 입니다. predict 변수를 따라 가볼까요?
따라 올라가보니 predict은 test를 예측한 것이 아니라 val을 예측한 결과네요
test 예측한 것을 다시 찾아보면 result = model.predict_proba(X_test) -> result라는 변수를 썼네요
결과적으로 predict변수가 아니라 result변수를 사용해야 합니다.
뒤로가기 버튼 같은 것이 있나요?
0
31
1
강의 연장 문의
0
36
1
출력값 질문
0
33
2
수업노트가 어디에 있나요?
0
33
1
실기시험 제출관련
0
164
2
6.20 작업형 2 과적합
0
171
3
코딩팡 장업형2 베이스 라인 인코딩 종류 질문
0
56
2
로지스틱회귀, 회귀
0
53
2
회귀 문제를 풀때 질문입니다.
0
60
1
불균형 처리 후 성능이 더 낮아졌다면,
0
67
2
실기 체험 제2유형 에러 문의
0
67
1
LIGHTGBM 으로 하면 pred값이 소수점 6자리까지 나오는게 맞나요
0
53
2
3번문제 등분산 가정
0
51
2
작업형3 target 형 변환 질문
0
39
2
[작업형1] 연습문제 섹션1 ~ 10 의 section4
0
41
3
원핫인코딩과 레이블 인코딩에서 concat
0
63
2
제2유형 질문입니다.
0
50
2
C()
0
45
2
작업형 2에서 strafity 적용 유무
0
56
2
수강 기간 연장 가능 여부 문의드립니다.
0
64
1
ols
0
45
2
2유형 작성관련 질문(일반 심화)
0
42
2
2유형 작성관련 질문
0
43
2
2유형 object컬럼 개수 다르면
0
50
2





