인프런 커뮤니티 질문&답변

눈누난나님의 프로필 이미지

작성한 질문수

[퇴근후딴짓] 빅데이터 분석기사 실기 (작업형1,2,3)

작업형2 모의문제2

작업형2 모의문제2 lightGBM 적용 질문

해결된 질문

23.06.19 23:13 작성

·

596

0

import pandas as pd

train = pd.read_csv('train.csv')
test = pd.read_csv('test.csv')

pd.set_option('display.max_columns', None)
# print(train.shape, test.shape)
# print(train.head())
# print(test.head())
# print(train.info())
# print(test.info())

cols = train.select_dtypes(include='object')
for col in cols : 
  train[col] = train[col].astype('category')
  test[col] = test[col].astype('category') # 이걸 안 하면 lgb.predict(test) 구문에서 에러남

from sklearn.model_selection import train_test_split
X_tr, X_val, y_tr, y_val = train_test_split(train.drop('price', axis=1), train['price'], test_size = 0.2, random_state=2023)

import lightgbm
lgb = lightgbm.LGBMRegressor(random_state = 2023)
lgb.fit(X_tr, y_tr)
pred = lgb.predict(X_val)

from sklearn.metrics import r2_score, mean_absolute_error, mean_squared_error
# print("r2 : ", r2_score(y_val, pred)) #0.2392705394376351
# print("mae : ", mean_absolute_error(y_val, pred)) #71.81171796246842
# print("mse : ", mean_squared_error(y_val, pred)) #63344.209788490516

pred_res = lgb.predict(test)

pd.DataFrame({'price': pred_res}).to_csv('result.csv', index=False)

print(pd.read_csv('result.csv'))

y_test = pd.read_csv("y_test.csv")
print(r2_score(y_test, pred_res)) #0.22012967580409581

안녕하세요, 딴짓님

lightGBM 모델 설명 주셔서 적용해보았는데요.

이렇게 하는 게 맞을까요?

for col in cols : 
  train[col] = train[col].astype('category')
  test[col] = test[col].astype('category')

이 부분을 하지 않으면 에러가 나긴 하더라구요.

 

train[col]을 하지 않으면 아래와 같은 에러메시지가 나옵니다.

'DataFrame.dtypes for data must be int, float or bool.

Did not expect the data types in the following fields: name, host_name, neighbourhood_group, neighbourhood, room_type, last_review'

 

test[col]을 하지 않으면 아래와 같은 에러메시지가 나옵니다.

'train and valid dataset categorical_feature do not match.'

 

  1. lightGBM모델은 데이터 타입이 int, float, bool 이 세가지만 허용하게 되어 object 타입을 category 타입으로 변경

  2. train만 변경해주면 test[col]을 하지 않았을 때와 같은 에러메시지가 출력되니 test도 category로 변경

이게 맞을까요?

 

평가지표 같은 것도 주석으로 작성했는데, lightGBM을 이렇게 사용하는 것이 맞는지 확인 한 번 부탁드립니다!

답변 1

1

퇴근후딴짓님의 프로필 이미지
퇴근후딴짓
지식공유자

2023. 06. 20. 21:22

네, train과 test 에 있는 범주형 변수는 모두 category로 변경하는 것이 맞습니다.

lightgbm이 인코딩이 필요는 없지만 준비는 해가길 추천합니다. 데이터에 따라 어떤 에러가 발생할지 모릅니다.