• 카테고리

    질문 & 답변
  • 세부 분야

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

  • 해결 여부

    해결됨

기사 (2회): 기출유형-작업형2 풀이 오류 해석

23.06.03 17:18 작성 조회수 312

1

안녕하세요.

강의 잘 듣고 있습니다. 매번 질문에 답해주셔서 감사합니다.

아래와 같이 코드를 짰는데

데이터 프레임 만들기 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
는 데이터 길이가 다르다는 뜻이에요

  1. 1760을 한번 찾아봐 주시겠어요? 잘 살펴보면 val 길이가 1760인 것을 확인할 수 있어요

  2. 그렇다면 ID값은 2200개이고 예측값(val)이 1760이 아닌지 의심해 볼 여지가 있겠네요

  3. 예측값은 'Reached.on.Time_Y.N' : predict[:,1] 입니다. predict 변수를 따라 가볼까요?

  4. 따라 올라가보니 predict은 test를 예측한 것이 아니라 val을 예측한 결과네요

  5. test 예측한 것을 다시 찾아보면 result = model.predict_proba(X_test) -> result라는 변수를 썼네요

  6. 결과적으로 predict변수가 아니라 result변수를 사용해야 합니다.

항상 감사드립니다