inflearn logo
강의

강의

N
챌린지

챌린지

멘토링

멘토링

N
클립

클립

로드맵

로드맵

지식공유

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

작업형2 모의문제2

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

해결된 질문

815

눈누난나

작성한 질문수 8

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을 이렇게 사용하는 것이 맞는지 확인 한 번 부탁드립니다!

python 머신러닝 빅데이터 pandas 빅데이터분석기사

답변 1

1

퇴근후딴짓

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

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

 

실기시험 제출관련

0

127

2

6.20 작업형 2 과적합

0

139

3

코딩팡 장업형2 베이스 라인 인코딩 종류 질문

0

38

2

로지스틱회귀, 회귀

0

47

2

회귀 문제를 풀때 질문입니다.

0

52

1

불균형 처리 후 성능이 더 낮아졌다면,

0

60

2

실기 체험 제2유형 에러 문의

0

60

1

LIGHTGBM 으로 하면 pred값이 소수점 6자리까지 나오는게 맞나요

0

46

2

3번문제 등분산 가정

0

46

2

작업형3 target 형 변환 질문

0

34

2

[작업형1] 연습문제 섹션1 ~ 10 의 section4

0

36

3

원핫인코딩과 레이블 인코딩에서 concat

0

56

2

제2유형 질문입니다.

0

46

2

C()

0

44

2

작업형 2에서 strafity 적용 유무

0

49

2

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

0

58

1

ols

0

43

2

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

0

38

2

2유형 작성관련 질문

0

39

2

2유형 object컬럼 개수 다르면

0

48

2

코딩팡질문이요ㅠㅠ

0

45

2

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

0

25

2

작업형2 ID 컬럼 삭제 질문

0

45

2

2유형 작성관련 질문

0

32

2