해결된 질문
23.11.20 14:41 작성
·
168
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.
답변 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
2023. 11. 20. 18:40
감사합니다! 이해했어요. 좋은 결과 나올 수 있도록 연습 꾸준히 하겠습니다.
좋은 하루 보내세요.