inflearn logo
강의

Khóa học

Chia sẻ kiến thức

[Việc riêng sau giờ tan làm] Kỳ thi thực hành chứng chỉ phân tích dữ liệu lớn (Dạng bài 1, 2, 3)

Dạng đề thi lần 2 (Dạng bài thực hành 2)

2회 기출유형(작업형2)

Đã giải quyết

303

chyg0000

5 câu hỏi đã được viết

0

import pandas as pd

import numpy as np

from sklearn.model_selection import train_test_split


def exam_data_load(df, target, id_name="", null_name=""):

    if id_name == "":

        df = df.reset_index().rename(columns={"index": "id"})

        id_name = 'id'

    else:

        id_name = id_name


    if null_name != "":

        df[df == null_name] = np.nan


    X_train, X_test = train_test_split(df, test_size=0.2, random_state=2022)

    y_train = X_train[[id_name, target]]

    X_train = X_train.drop(columns=[target])


    y_test = X_test[[id_name, target]]

    X_test = X_test.drop(columns=[target])

    return X_train, X_test, y_train, y_test


df = pd.read_csv("Train.csv") # 파일명이 다를 경우 파일명을 수정해주세요

X_train, X_test, y_train, y_test = exam_data_load(df, target='Reached.on.Time_Y.N', id_name='ID')

X_train.to_csv("X_train.csv", index=False)

y_train.to_csv("y_train.csv", index=False)

X_test.to_csv("X_test.csv", index=False)

 

import pandas as pd
X_test = pd.read_csv("X_test.csv")
X_train = pd.read_csv("X_train.csv")
y_train = pd.read_csv("y_train.csv")

# X_train.shape, y_train.shape, X_test.shape
#print(X_train.info())
print(X_test.info())
#print(y_train.info())

y_train = y_train.drop(columns = ['ID'])

#print(X_train.shape, X_test.shape)
X_train = X_train.drop(columns = ['ID'])
X_train = X_train.drop(columns = ['Warehouse_block'])
X_train = X_train.drop(columns = ['Mode_of_Shipment'])
X_train = X_train.drop(columns = ['Product_importance'])
X_train = X_train.drop(columns = ['Gender'])

X_test = X_test.pop('ID')
X_test = X_test.drop(columns = ['Warehouse_block'])
X_test = X_test.drop(columns = ['Mode_of_Shipment'])
X_test = X_test.drop(columns = ['Product_importance'])
X_test = X_test.drop(columns = ['Gender'])
#print(X_train.shape, X_test.shape)

from sklearn.ensemble import RandomForestClassifier
model = RandomForestClassifier()
model.fit(X_train,y_train)
model_pred = model.predict_proba(X_test)

 

강사님 안녕하세요. 위와 같이 인코딩을 하지 않고 object 컬럼을 지우는 방향으로 해서 모델학습을 진행하였어요. 그런데 이런 애러가 났어요. 어떻게 해야 할까요?

 

None
<ipython-input-36-25befb274901>:30: DataConversionWarning: A column-vector y was passed when a 1d array was expected. Please change the shape of y to (n_samples,), for example using ravel().
  model.fit(X_train,y_train)
/usr/local/lib/python3.10/dist-packages/sklearn/base.py:439: UserWarning: X does not have valid feature names, but RandomForestClassifier was fitted with feature names
  warnings.warn(
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-36-25befb274901> in <cell line: 31>()
     29 model = RandomForestClassifier()
     30 model.fit(X_train,y_train)
---> 31 model_pred = model.predict_proba(X_test)
     32 


3 frames


/usr/local/lib/python3.10/dist-packages/sklearn/utils/validation.py in check_array(array, accept_sparse, accept_large_sparse, dtype, order, copy, force_all_finite, ensure_2d, allow_nd, ensure_min_samples, ensure_min_features, estimator, input_name)
    900             # If input is 1D raise error
    901             if array.ndim == 1:
--> 902                 raise ValueError(
    903                     "Expected 2D array, got 1D array instead:\narray={}.\n"
    904                     "Reshape your data either using array.reshape(-1, 1) if "

ValueError: Expected 2D array, got 1D array instead:
array=[ 8285. 10192.  8675. ...  7390.  9977.  5696.].
Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample.

python 머신러닝 빅데이터 pandas 빅데이터분석기사

Câu trả lời 2

1

Jason

경고의 경우

y_train = y_train.drop(columns = ['ID']) 가 아닌

y_train = y_train['타겟컬럼']으로 하면 없어지고,

 

오류의 경우

처음 X_test 전처리하실 때 pop 함수를 통해 다른변수가 아닌 X_test로 저장해버려서

X_test 데이터는 ID값만 남는 형태로 보입니다.

(후에 columns를 drop 시킨것은 이미 X_test에는 데이터가 없기때문에 의미 없음)

따라서 X_test_id = X_test.pop('ID')로 하시거나

X_test.pop('ID')를 X_test.drop 다하고 밑에 하니깐 X_test.shape이 X_train.shape과 동일한 컬럼 수를 같게 되고 모델 학습이 되네요

1

chyg0000

감사합니다! 이해했어요. 좋은 결과 나올 수 있도록 연습 꾸준히 하겠습니다.

좋은 하루 보내세요.

0

roadmap

답변 달아주셔서 감사합니다. 😊

화이팅입니다.

수강 연장 문의드립니다

0

68

2

작업형2에서 clip(0) 언제 써야하는지 알려주세요 !

0

67

1

작업형2에서 clip(0) 언제 써야하는지 알려주세요 !

0

42

1

60. 예시문제 작업형2(ver. 2025) 문의

0

55

2

코딩팡, 시험실제환경 질문

0

58

1

섹션4 질문입니다

0

52

2

[작업형2] 레이블인코딩

0

52

2

[작업형2] train,test 범주 종류, 레이블인코딩 기준

0

50

1

2유형 train 전체 데이터 재학습

0

52

2

책 내용 질문

0

45

2

기출11 작업형3

0

35

2

최종 학습 계획

0

59

2

올려주신 기출 & 출제방식 질문입니다!

0

45

2

작업형 2 최종 제출, 시험 풀이 순서

0

47

1

10회 기출유형 (작업형3) 질문있습니다

0

42

2

빅이시 작업형2 추천1번문제.

0

38

2

굳이 원핫인코딩을 해야되나요?

0

47

2

작업형3 tukey와 Bonferroni

0

40

2

1,3유형 답 소수점 자리수

0

40

1

라이브러리 호출 관련 질문

0

44

1

불균형데이터 처리 관련 문의

0

51

2

작업형2 test데이터 관련 질문입니다.

0

45

2

마지막 단계 생성한 csv 파일 확인

0

50

2

시계열 공부 고민 질문입니다

0

46

1