2회 기출유형(작업형2)
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.
답변 2
1
경고의 경우
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과 동일한 컬럼 수를 같게 되고 모델 학습이 되네요
수강연장요청 문의
0
54
1
아무래도 다음 시험 연장은 어렵겠죠?
0
70
2
빅분기 12회 결과 관련 문의
0
86
1
책이랑 강의랑 순서나 예제가 다른것 같네요
0
69
2
수강연장 문의
0
77
2
재검토 요청 방법 좀 알려주셔요...-.-;;
0
95
2
12회 실기 질문(작업형 2)
0
82
2
뒤로가기 버튼 같은 것이 있나요?
0
56
1
강의 연장 문의
0
84
2
출력값 질문
0
60
2
수업노트가 어디에 있나요?
0
51
1
실기시험 제출관련
0
215
3
6.20 작업형 2 과적합
0
213
3
코딩팡 장업형2 베이스 라인 인코딩 종류 질문
0
75
2
로지스틱회귀, 회귀
0
64
2
회귀 문제를 풀때 질문입니다.
0
73
1
불균형 처리 후 성능이 더 낮아졌다면,
0
82
2
실기 체험 제2유형 에러 문의
0
80
1
LIGHTGBM 으로 하면 pred값이 소수점 6자리까지 나오는게 맞나요
0
70
2
3번문제 등분산 가정
0
64
2
작업형3 target 형 변환 질문
0
52
2
[작업형1] 연습문제 섹션1 ~ 10 의 section4
0
67
3
원핫인코딩과 레이블 인코딩에서 concat
0
75
2
제2유형 질문입니다.
0
60
2





