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

276

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

7

1

강의 연장 문의

0

14

1

수강 신청 연장 문의드립니다.

0

28

1

작업형 1번문제... 환경관련

0

24

2

12회 기출은 언제 업데이트 될까요??

0

35

2

8/6 작성한 연장문의 질문글에 대한 재요청

0

38

2

수강기간 연장 문의

0

35

2

수강기간 연장문의

0

36

2

수강기간 연장 요청 문의드립니다

0

37

2

수강 기간 연장 문의

0

46

2

수강연장 가능 문의 (기간 약 한달반)

0

58

2

수강기간 연장 가능할까요 선생님

0

74

2

Section15. 수업에 사용하는 데이터 주소가 다 보이지 않아서 실습을 위한 데이터를 다운 받지 못하고 있습니다.

0

53

3

수강연장요청 문의

0

88

2

아무래도 다음 시험 연장은 어렵겠죠?

0

106

2

빅분기 12회 결과 관련 문의

0

112

1

책이랑 강의랑 순서나 예제가 다른것 같네요

0

80

2

수강연장 문의

0

104

2

재검토 요청 방법 좀 알려주셔요...-.-;;

0

105

2

12회 실기 질문(작업형 2)

0

91

2

뒤로가기 버튼 같은 것이 있나요?

0

66

1

강의 연장 문의

0

99

2

출력값 질문

0

71

2

수업노트가 어디에 있나요?

0

63

1