inflearn logo
강의

Khóa học

Chia sẻ kiến thức

[Làm gì sau giờ làm] Chứng chỉ Phân tích Dữ liệu lớn - Kỳ thi thực hành (Dạng bài tập 1, 2, 3)

Đề thi mẫu lần 2 (Loại hình công việc 2)

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

Đã giải quyết

266

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

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

화이팅입니다.

제2유형 질문입니다.

0

11

1

C()

0

9

1

작업형 2에서 strafity 적용 유무

0

12

2

수강 기간 연장 가능 여부 문의드립니다.

0

13

1

ols

0

12

2

2유형 작성관련 질문(일반 심화)

0

17

2

2유형 작성관련 질문

0

16

2

2유형 object컬럼 개수 다르면

0

17

2

코딩팡질문이요ㅠㅠ

0

17

2

관찰값과 기대값의 개념이 헷갈립니다.

0

12

2

작업형2 ID 컬럼 삭제 질문

0

22

2

2유형 작성관련 질문

0

19

2

memoryerror 질문

0

15

2

작업형 유형2 이렇게 고정 템플릿으로 가져가도 될까요?

0

19

1

ID 삭제 필수 인가요?

0

19

3

7회 기출문제 작업형1번 df 변환 후 저장되는 방식 질문

0

15

2

3 유형 귀무가설, 대립가설

0

19

2

인코딩 관련 질문 있습니다

0

23

2

작업형3 이원분산분석 sm에서불러오기 / anova_lm 차이

0

26

2

2유형 원핫인코딩 오류

0

23

2

시험장에서 주석 단축키 안될 때 많나요?

0

28

2

라벨인코딩 방식

0

27

2

test 재학습 관련

0

16

2

target 빈도 확인

0

18

2