헤맨 만큼 내 땅이다

Python/빅데이터분석기사 실기

빅데이터 분석기사 실기 작업형 2(회귀) 예제

mm대장 2025. 6. 6. 17:39

코드의 출처는 <AI 너는 아니 you know?> 님의 코드를 보고 공부했습니다.

 

이런저런 실기 2유형 코드들을 봤는데 이분께서 해주신게 제가 평소에 알건 Baseline 과 가장 유사하고

깔끔하여 이 코드로 실기 공부 중입니다.

https://youtu.be/NzYS2Npasnw?si=wVLcPzAdllLlJuUb

 

공부하면서 따라한 코드 공유 드립니다.

 

 

 

#회귀 평가 모델: 모델 평가 지표는 RMSE 할 것

 

import pandas as pd 


df = pd.read_csv("https://raw.githubusercontent.com/JEunJin/BigData_python/refs/heads/master/bigdata_csvfile/used_cars_price_data.csv")
#print(df.head())

#데이터 전처리(결측값, 라벨 인코딩), 결측값 먼저 처리하고 라벨 인코딩 하기
df['fuel_type'].fillna(df['fuel_type'].mode()[0], inplace=True) #mode가 영어로 최빈값이다.
df['accident'].fillna(df['accident'].mode()[0], inplace=True) #[0]는 0번째 최빈값을 뜻함
df['clean_title'].fillna(df['clean_title'].mode()[0], inplace=True)

#print(df.info())

#라벨 인코딩, object 로 된 Dtype을 정수로 바꿔줌
from sklearn.preprocessing import LabelEncoder
le = LabelEncoder()

df['brand'] = le.fit_transform(df['brand'])
df['model'] = le.fit_transform(df['model'])
df['milage'] = le.fit_transform(df['milage'])
df['fuel_type'] = le.fit_transform(df['fuel_type'])
df['engine'] = le.fit_transform(df['engine'])
df['transmission'] = le.fit_transform(df['transmission'])
df['ext_col'] = le.fit_transform(df['ext_col'])
df['int_col'] = le.fit_transform(df['int_col'])
df['accident'] = le.fit_transform(df['accident'])
df['clean_title'] = le.fit_transform(df['clean_title'])
df['price'] = le.fit_transform(df['price'])

#print(df.info())
print(df.head())





#자료 나누기, train과 test로 구분하기
train = df.iloc[:3800,:] #iloc = integer location based, 슬라이싱
test = df.iloc[-209:,:]

#print(train.info())
#print(test.info())

#데이터 분할, train 데이터에서 test 와 validation 분할하기
from sklearn.model_selection import train_test_split

x = train.drop(columns=['price']) #평가 지표 제외하기
y = train['price']

x_train, x_val, y_train, y_val = train_test_split(x, y, test_size=0.2, random_state=10) 


#모델링 및 학습 #모델생성
from sklearn.ensemble import RandomForestRegressor #Regressor가 회귀


#help(RandomForestRegressor) 하면 RandomForestRegressor 상세 내용 확인 가능

rfr = RandomForestRegressor(n_estimators=120, max_depth=15, random_state=10)
 
#학습
rfr.fit(x_train, y_train) #rfr에 x_train과 y_train간 관계를 학습



#예측
pred1 = rfr.predict(x_val) #pred1에는 x_val에 대한 모델의 예측값이 변수에 할당된다

#모델 및 성능평가
from sklearn.metrics import mean_squared_error
import numpy as np

mse = mean_squared_error(y_val, pred1) #x_test로 예측한 pred1과 y_val가 mse 구하기
rmse = np.sqrt(mse)



#결과 예측
test_x_data = test.drop(columns=['price'])
pred2 = rfr.predict(test_x_data)

#결과 제출 및 확인
pd.DataFrame({'price':pred2}).to_csv('result.csv', index=False) #index 가 없어야 한다.

result = pd.read_csv('result.csv')
print(result.head())
print(result.shape)