열정적인 하루

Aice Associate 합격 준비 공부범위 실습 최소한 가이드 본문

IT

Aice Associate 합격 준비 공부범위 실습 최소한 가이드

열정샷 2025. 9. 30. 22:29
머신러닝/딥러닝 시험 완벽 대비 가이드

🚀 머신러닝/딥러닝 시험 완벽 대비 가이드

시험 개요

이 시험은 Python 기반의 머신러닝과 딥러닝 실무 능력을 평가합니다. 오픈북 시험이므로 numpy, pandas, matplotlib, seaborn, scikit-learn 등의 공식 문서를 참조할 수 있습니다. Google Colab 환경에서 실습하며 준비하는 것을 추천합니다.

📚 핵심 학습 영역 7가지

1데이터 Import 및 시각화

필수 기술:
  • CSV, Excel 등 다양한 형식의 데이터 불러오기
  • 데이터 구조 파악 (head, info, describe)
  • 적절한 그래프 선택 및 작성

예시 문제: 타이타닉 데이터셋을 불러와서 생존률을 성별로 시각화하세요

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

# 데이터 로드
df = pd.read_csv('titanic.csv')

# 데이터 확인
print(df.head())
print(df.info())

# 성별에 따른 생존률 막대그래프
survival_by_gender = df.groupby('Sex')['Survived'].mean()
plt.figure(figsize=(8, 6))
survival_by_gender.plot(kind='bar', color=['skyblue', 'salmon'])
plt.title('Survival Rate by Gender')
plt.ylabel('Survival Rate')
plt.xlabel('Gender')
plt.xticks(rotation=0)
plt.show()
핵심 포인트:
  • pd.read_csv() - CSV 파일 불러오기
  • groupby() - 그룹별 집계
  • plt.figure(), plot() - 시각화

2데이터 전처리

필수 기술:
  • 결측치 처리 (삭제, 평균값/중앙값/최빈값 대체)
  • 이상치 제거
  • 불필요한 문자열 데이터 처리

예시 문제: 주택 가격 데이터에서 결측치와 '-' 문자열을 처리하세요

import pandas as pd
import numpy as np

# 샘플 데이터
data = {
    'price': [300000, 450000, np.nan, 520000, '-'],
    'sqft': [1500, 2000, 1800, '-', 2200],
    'bedrooms': [3, 4, np.nan, 4, 5]
}
df = pd.DataFrame(data)

print("전처리 전:")
print(df)
print(f"\n결측치 개수:\n{df.isnull().sum()}")

# '-' 문자열을 NaN으로 변경
df = df.replace('-', np.nan)

# 숫자형으로 변환
df['price'] = pd.to_numeric(df['price'], errors='coerce')
df['sqft'] = pd.to_numeric(df['sqft'], errors='coerce')

# 결측치 처리 방법 1: 삭제
df_dropped = df.dropna()
print("\n결측치 삭제 후:")
print(df_dropped)

# 결측치 처리 방법 2: 평균값으로 대체
df_filled = df.fillna(df.mean())
print("\n평균값으로 대체 후:")
print(df_filled)
핵심 포인트:
  • isnull(), sum() - 결측치 확인
  • replace() - 특정 값 변경
  • dropna() - 결측치 삭제
  • fillna() - 결측치 채우기
  • pd.to_numeric() - 숫자형 변환

3벡터 변환 (Feature Engineering)

필수 기술:
  • 범주형 데이터의 수치화
  • One-Hot Encoding, Label Encoding
  • 정규화/표준화

예시 문제: 범주형 변수를 One-Hot Encoding으로 변환하세요

from sklearn.preprocessing import LabelEncoder, OneHotEncoder
import pandas as pd

# 샘플 데이터
data = {
    'color': ['red', 'blue', 'green', 'red', 'blue'],
    'size': ['S', 'M', 'L', 'M', 'S'],
    'price': [10, 15, 20, 12, 11]
}
df = pd.DataFrame(data)

print("원본 데이터:")
print(df)

# 방법 1: pandas get_dummies (가장 간단)
df_encoded = pd.get_dummies(df, columns=['color', 'size'])
print("\nOne-Hot Encoding 결과:")
print(df_encoded)

# 방법 2: sklearn OneHotEncoder
encoder = OneHotEncoder(sparse_output=False)
color_encoded = encoder.fit_transform(df[['color']])
color_df = pd.DataFrame(color_encoded, 
                        columns=encoder.get_feature_names_out(['color']))
print("\nscikit-learn OneHotEncoder 결과:")
print(color_df)

# Label Encoding 예시
le = LabelEncoder()
df['size_encoded'] = le.fit_transform(df['size'])
print("\nLabel Encoding 결과:")
print(df[['size', 'size_encoded']])
핵심 포인트:
  • pd.get_dummies() - 간편한 One-Hot Encoding
  • LabelEncoder - 순서가 있는 범주형 데이터
  • OneHotEncoder - 순서가 없는 범주형 데이터

4훈련/검증 데이터셋 분할

필수 기술:
  • train_test_split 사용
  • 적절한 비율 설정 (일반적으로 7:3 또는 8:2)
  • random_state로 재현성 확보

예시 문제: 데이터를 훈련:검증 = 8:2 비율로 분할하세요

from sklearn.model_selection import train_test_split
from sklearn.datasets import load_iris
import pandas as pd

# 데이터 로드
iris = load_iris()
X = pd.DataFrame(iris.data, columns=iris.feature_names)
y = iris.target

print(f"전체 데이터 크기: {X.shape}")

# 훈련/테스트 분할 (80:20)
X_train, X_test, y_train, y_test = train_test_split(
    X, y, 
    test_size=0.2,      # 테스트 데이터 비율
    random_state=42,    # 재현성을 위한 랜덤 시드
    stratify=y          # 클래스 비율 유지
)

print(f"\n훈련 데이터 크기: {X_train.shape}")
print(f"테스트 데이터 크기: {X_test.shape}")
print(f"\n훈련 데이터 레이블 분포:\n{pd.Series(y_train).value_counts()}")
print(f"\n테스트 데이터 레이블 분포:\n{pd.Series(y_test).value_counts()}")
핵심 포인트:
  • train_test_split() - 데이터 분할 함수
  • test_size - 테스트 데이터 비율
  • random_state - 재현성 보장
  • stratify - 클래스 불균형 해결

5머신러닝 모델 학습

필수 기술:
  • 다양한 알고리즘 구현 (회귀, 분류)
  • 모델 학습 및 예측
  • 하이퍼파라미터 이해

예시 문제 1 - 회귀: 주택 가격을 예측하는 선형 회귀 모델을 만드세요

from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.datasets import fetch_california_housing
import pandas as pd

# 데이터 로드
housing = fetch_california_housing()
X = pd.DataFrame(housing.data, columns=housing.feature_names)
y = housing.target

# 데이터 분할
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42
)

# 모델 생성 및 학습
model = LinearRegression()
model.fit(X_train, y_train)

# 예측
y_pred = model.predict(X_test)

print("모델 계수:", model.coef_)
print("절편:", model.intercept_)
print(f"\n실제값 (처음 5개): {y_test[:5]}")
print(f"예측값 (처음 5개): {y_pred[:5]}")

예시 문제 2 - 분류: Random Forest로 붓꽃 품종을 분류하세요

from sklearn.ensemble import RandomForestClassifier
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split

# 데이터 로드
iris = load_iris()
X_train, X_test, y_train, y_test = train_test_split(
    iris.data, iris.target, test_size=0.2, random_state=42
)

# Random Forest 모델 생성 및 학습
model = RandomForestClassifier(
    n_estimators=100,    # 트리 개수
    max_depth=5,         # 최대 깊이
    random_state=42
)
model.fit(X_train, y_train)

# 예측
y_pred = model.predict(X_test)

print(f"예측 결과: {y_pred}")
print(f"실제 결과: {y_test}")
문제 유형 주요 알고리즘
회귀 LinearRegression, Ridge, Lasso, RandomForestRegressor
분류 LogisticRegression, DecisionTreeClassifier, RandomForestClassifier, SVM

6머신러닝 성능 평가

필수 기술:
  • 회귀 평가지표: MAE, MSE, RMSE, R²
  • 분류 평가지표: Accuracy, Precision, Recall, F1-Score

예시 문제: 회귀 모델의 성능을 MAE, MSE, RMSE로 평가하세요

from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score
from sklearn.linear_model import LinearRegression
from sklearn.datasets import fetch_california_housing
from sklearn.model_selection import train_test_split
import numpy as np

# 데이터 준비 및 모델 학습
housing = fetch_california_housing()
X_train, X_test, y_train, y_test = train_test_split(
    housing.data, housing.target, test_size=0.2, random_state=42
)

model = LinearRegression()
model.fit(X_train, y_train)
y_pred = model.predict(X_test)

# 성능 평가
mae = mean_absolute_error(y_test, y_pred)
mse = mean_squared_error(y_test, y_pred)
rmse = np.sqrt(mse)
r2 = r2_score(y_test, y_pred)

print("=" * 40)
print("회귀 모델 성능 평가")
print("=" * 40)
print(f"MAE (Mean Absolute Error):     {mae:.4f}")
print(f"MSE (Mean Squared Error):      {mse:.4f}")
print(f"RMSE (Root Mean Squared Error): {rmse:.4f}")
print(f"R² Score:                      {r2:.4f}")
print("=" * 40)
평가지표 설명 특징
MAE 평균 절대 오차 이해하기 쉬움
MSE 평균 제곱 오차 큰 오차에 페널티
RMSE MSE의 제곱근 실제 단위와 같음
결정계수 1에 가까울수록 좋음

7딥러닝 구현 및 평가

필수 기술:
  • Neural Network 구조 설계
  • 활성화 함수, 손실 함수 선택
  • 모델 컴파일 및 학습
  • MSE 등으로 성능 평가

예시 문제 - 회귀: Keras로 주택 가격 예측 신경망을 만드세요

from tensorflow import keras
from tensorflow.keras import layers
from sklearn.datasets import fetch_california_housing
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler

# 데이터 로드
housing = fetch_california_housing()
X_train, X_test, y_train, y_test = train_test_split(
    housing.data, housing.target, test_size=0.2, random_state=42
)

# 데이터 정규화 (딥러닝에서 중요!)
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)

# 신경망 모델 구축
model = keras.Sequential([
    layers.Dense(64, activation='relu', input_shape=(X_train.shape[1],)),
    layers.Dense(32, activation='relu'),
    layers.Dense(16, activation='relu'),
    layers.Dense(1)  # 회귀는 출력층에 활성화 함수 없음
])

# 모델 컴파일
model.compile(
    optimizer='adam',
    loss='mse',           # 회귀 문제는 MSE 손실 함수
    metrics=['mae']       # 추가 평가지표
)

# 모델 구조 확인
print(model.summary())

# 모델 학습
history = model.fit(
    X_train_scaled, y_train,
    epochs=100,
    batch_size=32,
    validation_split=0.2,
    verbose=0
)

# 모델 평가
test_loss, test_mae = model.evaluate(X_test_scaled, y_test, verbose=0)
print(f"\nTest MSE: {test_loss:.4f}")
print(f"Test MAE: {test_mae:.4f}")
구분 용도 옵션
활성화 함수 은닉층 relu
활성화 함수 이진 분류 출력층 sigmoid
활성화 함수 다중 분류 출력층 softmax
손실 함수 회귀 mse
손실 함수 이진 분류 binary_crossentropy
손실 함수 다중 분류 categorical_crossentropy

🎯 합격 전략

1. 코드 패턴 암기하기

각 작업별로 전형적인 코드 패턴을 익혀두세요.

# 전처리 패턴
df.isnull().sum()  # 결측치 확인
df.fillna()        # 결측치 채우기
df.dropna()        # 결측치 삭제
pd.get_dummies()   # 원-핫 인코딩

# 모델 학습 패턴
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
model.fit(X_train, y_train)
y_pred = model.predict(X_test)

# 성능 평가 패턴
from sklearn.metrics import mean_absolute_error
mae = mean_absolute_error(y_test, y_pred)

2. 주석으로 구조 파악하기

코드를 작성할 때 각 부분이 무엇을 하는지 주석으로 표시하세요.

# 1. 데이터 로드
df = pd.read_csv('data.csv')

# 2. 전처리 - 결측치 처리
df = df.fillna(df.mean())

# 3. 벡터 변환 - 원-핫 인코딩
df = pd.get_dummies(df)

# 4. 데이터 분할
X_train, X_test, y_train, y_test = train_test_split(X, y)

# 5. 모델 학습
model.fit(X_train, y_train)

# 6. 성능 평가
score = model.score(X_test, y_test)

3. 공식 문서 활용법 익히기

시험 중에는 공식 문서를 볼 수 있으므로, 어디에서 무엇을 찾을지 미리 알아두세요.

  • pandas: 데이터 전처리 관련
  • scikit-learn: 모델, 평가지표, 전처리
  • matplotlib/seaborn: 시각화
  • tensorflow/keras: 딥러닝

4. 실전 연습

Colab에서 다음 순서로 반복 연습하세요:

  1. 기출문제 코드 따라 치기
  2. 주석으로 각 부분 설명 달기
  3. 코드 보지 않고 직접 작성해보기
  4. 데이터만 바꿔서 다시 해보기

📋 시험 전 체크리스트

필수 암기 사항

  • pd.read_csv() - 데이터 로드
  • df.isnull().sum() - 결측치 확인
  • df.fillna(), df.dropna() - 결측치 처리
  • pd.get_dummies() - 원-핫 인코딩
  • train_test_split() - 데이터 분할
  • model.fit(), model.predict() - 모델 학습/예측
  • mean_absolute_error(), mean_squared_error() - 평가

자주 사용하는 Import 구문

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LinearRegression
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import mean_absolute_error, mean_squared_error, accuracy_score

from tensorflow import keras
from tensorflow.keras import layers

💡 마무리 팁

  1. 시간 배분: 문제를 읽고 어떤 작업이 필요한지 먼저 파악하세요.
  2. 에러 대응: 에러가 나면 침착하게 에러 메시지를 읽고 해결하세요.
  3. 검증: 코드 실행 후 결과가 예상대로 나왔는지