subindev 님의 블로그

[실기] 빅데이터 분석기사 작업 2유형(6문제) 본문

데이터 관련/빅데이터 분석기사

[실기] 빅데이터 분석기사 작업 2유형(6문제)

subindev 2025. 7. 9. 18:27

 

2025/06/21 시행한 시험 합격했어요!

 

일단 저는 컴퓨터 공학을 전공했고 데이터에 아예 무지한 상태는 아니였어요.

웹 개발 프로젝트 중 사용자 로그를 수집하여 분석하는 과제를 맡았었는데

그 때 빅데이터에 대한 관심이 생겨서 취득하게 되었습니다 : )

코테를 준비중이라 파이썬은 어느정도 익숙한 상태에서 시작하였고 실기 공부는 2주 정도 한 것 같습니다.

 

저는 2유형 제일 먼저 공부하시고 3유형 후 1유형을 하는 것을 추천 드리고 싶어요.

3유형은 아직 기출이 많이 없어 기출 위주로 핵심 내용만 익히고 갔는데 실수로 한문제 틀렸지만 다 풀 수 있겠더라구요!

 

또, 제 1유형은 python을 원래도 쓰실 수 있으시다면 크게 어려울 것 같지 않아요

help 와 dir을 이용하여서 기억 안나는 함수도 사용할 수 있기에 너무 걱정 안하셔도 될 거 같아요!

pandas 100제 문제 푸는 것이 python와 pandas를 처음 익히고 익숙해 지기에 너무 좋은 거 같아요

그치만 시험 대비로 생각한다면 약간 난이도가 있는거 같아서

다 완벽하게 풀지 못하여도 이런 함수가 있구나 정도만 익히시고 넘어가도 괜찮을 거 같습니다!

 

다들 화이팅입니다 :)


 

 

https://www.kaggle.com/datasets/agileteam/bigdatacertificationkr

 

Big Data Certification KR

퇴근후딴짓 의 빅데이터 분석기사 실기 (Python, R tutorial code) 커뮤니티

www.kaggle.com

 

 

RandomForestClassifier() - 분류

RandomForestRegressor() - 값예측

 

하이라이퍼 튜닝 - n_estimators , max_depth 건들기

# 하이라이퍼튜닝 - 분류

from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score

# y_train이 숫자형인 경우 (0~3 등)
X_tr, X_val, y_tr, y_val = train_test_split(X_train, y_train, test_size=0.2, random_state=42)

print("검증 정확도 (accuracy):", accuracy_score(y_val, val_pred))
for depth in [5, 7, 9, 11]:
    for trees in [100, 200, 300]:
        model = RandomForestClassifier(n_estimators=trees, max_depth=depth, random_state=42)
        model.fit(X_tr, y_tr)
        val_pred = model.predict(X_val)
        acc = accuracy_score(y_val, val_pred)
        print(f"max_depth={depth}, n_estimators={trees} → accuracy: {acc:.4f}")
# 하이라이퍼튜닝 - 회귀
from sklearn.model_selection import train_test_split
from sklearn.metrics import r2_score

X_tr, X_val, y_tr, y_val = train_test_split(X_train, y_train, test_size=0.2, random_state=42)

for depth in [5, 7, 9, 11]:
    for trees in [100, 200, 300]:
        model = RandomForestRegressor(n_estimators=trees, max_depth=depth, random_state=42)
        model.fit(X_tr, y_tr)
        val_pred = model.predict(X_val)
        score = r2_score(y_val, val_pred)
        print(f"max_depth={depth}, n_estimators={trees} → R² score: {score:.4f}")

 

 

2-1 타이타닉 생존여부 (분류)

# 라이브러리 불러오기
import pandas as pd

# 데이터 불러오기
X_train.shape, y_train.shape, X_test.shape

# 생존 여부(y값)만 추출
y = y_train["Survived"]

# 결과에 영향을 줄 특징 목록
features = ["Pclass", "Sex", "SibSp", "Parch", "Age"]

# Age 결측치 처리
X_train['Age'] = X_train['Age'].fillna(X_train['Age'].mean())
X_test['Age'] = X_test['Age'].fillna(X_train['Age'].mean())  # 반드시 train 기준 평균!

# ✅ 원-핫 인코딩 (범주형 변수 변환: 'Sex')
X = pd.get_dummies(X_train[features])
test = pd.get_dummies(X_test[features])
# LabelEncoder는 순서가 있는 범주형 변수를 변환할 때 사용

# 랜덤포레스트 모델 학습 및 예측
from sklearn.ensemble import RandomForestClassifier
model = RandomForestClassifier(n_estimators=200, max_depth=7, random_state=2021)
model.fit(X, y)

predictions = model.predict(test)

# ✅ 결과 저장
output = pd.DataFrame({'PassengerId': X_test.PassengerId, 'Survived': predictions})
output.to_csv('1234567.csv', index=False)

 

2-2 당뇨병일 확률 (분류)

# 라이브러리
import pandas as pd

train = pd.read_csv("/kaggle/input/bigdatacertificationkr/diabetes_train.csv")
test = pd.read_csv("/kaggle/input/bigdatacertificationkr/diabetes_test.csv")
train.shape, test.shape

X_train = train.drop('Outcome', axis = 1)
y_train = train['Outcome']
X_test = test

print(X_train.shape , y_train.shape, X_test.shape)
#(576, 9) (576,) (192, 9)

from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler()

X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)

# 인코딩 - 범주형 없으므로 생략
# 결측치 - 없으므로 생략

from sklearn.model_selection import train_test_split

X_tra, X_val, y_tra, y_val = train_test_split(X_train, y_train, test_size =0.2, random_state= 42)
print(X_tra.shape, X_val.shape, y_tra.shape, y_val.shape)

from sklearn.ensemble import RandomForestClassifier
model = RandomForestClassifier(random_state=42)
model.fit(X_tra, y_tra)
y_val_pred = model.predict(X_val)

from sklearn.metrics import roc_auc_score
roc_score = roc_auc_score(y_val, y_val_pred)
print('roc_Score' , roc_score)

pred_proba = model.predict_proba(X_test)[:,1]

outcome = pd.DataFrame({'pred':pred_proba})
outcome.to_csv('345234.csv',index=False)

result = pd.read_csv('345234.csv')
result

 

2-3 성인 고소득 여부 (분류)

# 시험환경 세팅 (코드 변경 X)
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=2021)
    
    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("../input/adult-census-income/adult.csv")
X_train, X_test, y_train, y_test = exam_data_load(df, target='income', null_name='?')

# ----- 데이터 만드는 코드 (위는 손대지 마세요)

print(X_train.shape, X_test.shape, y_train.shape, y_test.shape)

# y_train 컬럼 2개이므로 하나로 맞춤
# 출력값을 0, 1로 하라고 한다면 이런식으로 처리하면 됨
y_train = (y_train['income'] == '<=50K').astype(int) # <=50K 1  |  >50K  0

# 결측치 채우기
X_train.isnull().sum() # workclass , occupation , native.country

X_train['workclass'].value_counts() # 최빈값
X_train['occupation'].value_counts() # null
X_train['native.country'].value_counts() # 최빈값

X_train['workclass'] = X_train['workclass'].fillna(X_train['workclass'].mode()[0])
X_train['occupation'] = X_train['occupation'].fillna('null')
X_train['native.country'] = X_train['native.country'].fillna(X_train['native.country'].mode()[0])

X_test['workclass'] = X_test['workclass'].fillna(X_test['workclass'].mode()[0])
X_test['occupation'] = X_test['occupation'].fillna('null')
X_test['native.country'] = X_test['native.country'].fillna(X_test['native.country'].mode()[0])

# 수치형, 범주형 나누기
X_train.info()
X_train = X_train.drop('education',axis=1)
X_test = X_test.drop('education', axis=1)

num_features = ['id','age','fnlwgt','capital.gain','capital.loss','hours.per.week']
cate_features = ['workclass','marital.status','occupation','relationship','race','sex','native.country']

# 스케일링
from sklearn.preprocessing import MinMaxScaler

scaler = MinMaxScaler()

X_train[num_features] = scaler.fit_transform(X_train[num_features])
X_test[num_features] = scaler.transform(X_test[num_features])

# 인코딩
from sklearn.preprocessing import LabelEncoder
for col in cate_features:
    le = LabelEncoder()
    combined = pd.concat([X_train[col],X_test[col]],axis = 0)
    le.fit(combined)

    X_train[col] = le.transform(X_train[col])
    X_test[col] = le.transform(X_test[col])

# 데이터 분리
from sklearn.model_selection import train_test_split

X_tra, X_val, y_tra, y_val = train_test_split(X_train, y_train, test_size=0.2, random_state=42)
X_tra.shape , X_val.shape, y_tra.shape, y_val.shape

# 모델 생성 및 학습
from sklearn.ensemble import RandomForestClassifier
model = RandomForestClassifier(random_state= 42)
model.fit(X_tra,y_tra)
y_val_pred = model.predict(X_val)

# 테스트 데이터로 평가
from sklearn.metrics import accuracy_score
acc_score = accuracy_score(y_val, y_val_pred)

# 모델 예측 및 결과 저장
y_pred = model.predict(X_test)

output = pd.DataFrame({'pred':y_pred})
output.to_csv('result.csv', index=False)

result = pd.read_csv('result.csv')
print(result)
# 제출 데이터 평가 (시험 X)
y_test = (y_test['income'] == '<=50K').astype(int)
acc_score2 = accuracy_score(y_test, y_pred)

acc_score, acc_score2

 

2-5 보험료 (회귀)

X_train.info()

# 결측치 확인 - 없음

print(X_train.shape, X_test.shape, y_train.shape)

y_train = y_train['charges']

num_features = ['age','bmi','children']
cate_features = ['sex','smoker','region']

# 스케일링
from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler()

X_train[num_features] = scaler.fit_transform(X_train[num_features])
X_test[num_features] = scaler.transform(X_test[num_features])

# 인코딩
from sklearn.preprocessing import LabelEncoder
for col in cate_features:
    le = LabelEncoder()
    combined = pd.concat([X_train[col], X_test[col]],axis = 0)
    le.fit(combined)

    X_train[col] = le.transform(X_train[col])
    X_test[col] = le.transform(X_test[col])

# 데이터 분리
from sklearn.model_selection import train_test_split

X_tra , X_val, y_tra, y_val = train_test_split(X_train, y_train, test_size = 0.2, random_state=42)
X_tra.shape, X_val.shape, y_tra.shape, y_val.shape

# 모델 생성 및 학습
from sklearn.ensemble import RandomForestRegressor
model = RandomForestRegressor(random_state = 42)
model.fit(X_tra, y_tra)
y_val_pred = model.predict(X_val)

# 평가
from sklearn.metrics import r2_score
r2 = r2_score(y_val, y_val_pred)
print(r2)

# 모델 예측 및 저장
pred = model.predict(X_test)

output = pd.DataFrame({'id':X_test['id'],'pred':pred})
output.to_csv('result.csv',index=False)

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

# 평가 (실제 시험에선 못합니다)
r2 = r2_score(y_test['charges'], result['pred'])
r2

2-6 대여량 (회귀)

import pandas as pd
train = pd.read_csv("/kaggle/input/bike-sharing-demand/train.csv")
test = pd.read_csv("/kaggle/input/bike-sharing-demand/test.csv")

X_train = train.drop(['count', 'casual','registered'],axis=1)
y = train.pop('count')
X_test = test

print(X_train.shape, y.shape, X_test.shape)
#(10886, 9) (10886,) (6493, 9)

# 데이트타임 형식은 라벨인코딩 하지 않고 연, 월, 일로 나누기
X_train['datetime'] = pd.to_datetime(X_train['datetime'])
X_test['datetime'] = pd.to_datetime(X_test['datetime'])

X_train['year'] = X_train['datetime'].dt.year
X_test['year'] = X_test['datetime'].dt.year

X_train['month'] = X_train['datetime'].dt.month
X_test['month'] = X_test['datetime'].dt.month

X_train['day'] = X_train['datetime'].dt.day
X_test['day'] = X_test['datetime'].dt.day

X_train['hour'] = X_train['datetime'].dt.hour
X_test['hour'] = X_test['datetime'].dt.hour

X_train['dayofweek'] = X_train['datetime'].dt.dayofweek
X_test['dayofweek'] = X_test['datetime'].dt.dayofweek

X_train = X_train.drop('datetime',axis=1)
X_test = X_test.drop('datetime',axis=1)

# 숫자형 특징 들 Scaler 
from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler()
num_features = ['year','month','day','dayofweek','season','holiday','workingday','weather','temp','atemp','humidity','windspeed']

X_train[num_features] = scaler.fit_transform(X_train[num_features])
X_test[num_features] = scaler.transform(X_test[num_features])

# 데이터 분리

from sklearn.model_selection import train_test_split

X_tra, X_val , y_tra, y_val = train_test_split(X_train, y, test_size=0.2, random_state =42)
X_tra.shape , X_val.shape, y_tra.shape, y_val.shape

# 모델 생성 및 학습

from sklearn.ensemble import RandomForestRegressor

model = RandomForestRegressor(random_state = 42)
model.fit(X_tra,y_tra)
y_val_pred = model.predict(X_val)

# 평가
from sklearn.metrics import r2_score
r2 = r2_score( y_val, y_val_pred)
print(r2)

# 모델 예측 및 결과 저장
pred = model.predict(X_test)
output = pd.DataFrame({'pred':pred})
output.to_csv('result.csv',index=False)

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

 

작업 2유형 템플릿 암기

# 작업유형2 - 데이터 전처리

import seaborn as sns
df = sns.load_dataset('penguins')

# 1. 결측치 제거

missing = ['bill_length_mm','bill_depth_mm','flipper_length_mm','body_mass_g']

for i in missing:
    df[i] = df[i].fillna(df[i].median())

df['sex']=df['sex'].fillna('Male')

# 2. 라벨 인코딩 
# 문자열 - 숫자로 변경

from sklearn.preprocessing import LabelEncoder

le = LabelEncoder()

df['species'] = le.fit_transform(df['species'])
df['island'] = le.fit_transform(df['island'])
df['sex'] = le.fit_transform(df['sex'])

# 3. 데이터 변환, 더미 처리

import pandas as pd

category = ['island','sex']

for i in category:
    df[i] = df[i].astype('category')
df = pd.get_dummies(df)

# 4. 파생변수
# body_mass_g 의 등급컷 열 추가

df['body_mass_g_cut'] = pd.qcut(df['body_mass_g'], 5, labels= False)

# 5. 스케일러
# MinMaxScaler - 0 ~ 1 사이의 값으로 바꾸기

from sklearn.preprocessing import MinMaxScaler

scale_list = ['bill_length_mm','bill_depth_mm','flipper_length_mm','body_mass_g']

scaler = MinMaxScaler()
scaler.fit(df[scale_list])
df[scale_list] = scaler.transform(df[scale_list])

# 6. 데이터 분리

from sklearn.model_selection import train_test_split

X_train, X_test, y_train, y_test = train_test_split(df.iloc[:,1:], df['species'], test_size = 0.2, stratify=df['species'], random_state =1)
print(X_train.shape, X_test.shape, y_train.shape, y_test.shape)

# 7. 모형 학습

from sklearn.ensemble import RandomForestClassifier

model1 = RandomForestClassifier()
model1.fit(X_train, y_train)
pred1 = model1.predict(X_test)

from sklearn.ensemble import AdaBoostClassifier
model2 = AdaBoostClassifier(algorithm = "SAMME")

model2.fit(X_train, y_train)
pred2 = model2.predict(X_test)

# 8. 앙상블 (RandomForestClassifier엔 포함되어 있음)

from sklearn.ensemble import VotingClassifier
clf = VotingClassifier(estimators=[('rf', model1), ('ad',model2)], voting= 'hard')
clf.fit(X_train, y_train)
pred3 = clf.predict(X_test)

# 9. 모형 평가

from sklearn.metrics import accuracy_score

print('랜포 ', accuracy_score(y_test, pred1))
print('에이다 ', accuracy_score(y_test, pred2))
print('보팅 ', accuracy_score(y_test, pred3))

# 10. 하이퍼파라미터 튜닝 (참고)

from sklearn.model_selection import GridSearchCV

parameters = {
    'n_estimators':[50,100], 
    'max_depth':[4,6]
}

model4 = RandomForestClassifier()

clf = GridSearchCV(estimator = model4, param_grid=parameters, cv=3)
clf.fit(X_train, y_train)
print('최적의 파라미터' , clf.best_params_)

# 11. 예측값 저장

pd.DataFrame({'id':y_test.index, 'pred':pred3}).to_csv('result.csv', index =False)
result = pd.read_csv('result.csv')
result