posted by 구로공돌이 2025. 8. 21. 09:18

 

1️⃣ Python & Pandas 필수 문법

import pandas as pd
import numpy as np
 
# 데이터 불러오기
df = pd.read_csv('data.csv') 
 
# 데이터 확인
# 상위 5행
df.head() 
 
# 컬럼, null, 타입
df.info() 
 
# 요약통계
df.describe() 
 
#상관관계 파악
corr()
 
# 결측치 개수
df.isna().sum() 
df.isnull().sum()
 
# 결측치 채우기
df['col'].fillna(0) 
 
# 결측치 제거
df.dropna() 
 
# 이상치 제거
df = df[df['col'] >= 0]
 
# 그룹바이
df.groupby('type')['value'].mean()
 
 
 

#원-핫 인코딩 🧩 문제 요약

  • 대상 데이터프레임: df_del
  • 인코딩 대상: object 타입의 전체 컬럼
  • 함수: pandas.get_dummies()
  • 결과: df_preset 변수에 저장

✅ 정답 코드

 
import pandas as pd # object 타입(범주형) 컬럼만 원-핫 인코딩 수행 
df_preset = pd.get_dummies(df_del, drop_first=False)

✅ 변형 예시 (시험에 자주 등장)

(1) 특정 컬럼만 인코딩

df_preset = pd.get_dummies(df_del, columns=['Gender', 'City'])

(2) 첫 번째 카테고리 제거 (다중공선성 방지용)

df_preset = pd.get_dummies(df_del, drop_first=True)

(3) object 컬럼 자동 인식 후 인코딩

obj_cols = df_del.select_dtypes(include='object').columns
df_preset = pd.get_dummies(df_del, columns=obj_cols)
 
 
 
 
# 데이터 나누기
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, random_state=42)

 

라벨 인코딩 예상 문제

10. 라벨 인코딩(Label encoding)은 범주형 변수를 0부터 시작하는 정수 값으로 변환하는 방법입니다.

가이드에 따라 특정 컬럼 데이터를 라벨 인코딩으로 변환하세요.

  • 대상 데이터프레임: df
  • 대상 컬럼: 'Category' (예: '과일', '채소', '육류' 등의 문자열이 포함됨)
  • 사용할 모듈: sklearn.preprocessing의 LabelEncoder
  • LabelEncoder를 'le'라는 이름의 객체로 생성하세요.
  • 'le' 객체를 사용하여 'Category' 컬럼 데이터에 학습(fit)과 변환(transform)을 동시에 적용하세요. (<blank1>)
  • 변환된 결과를 df의 'Category_encoded'라는 새로운 컬럼에 저장하세요.
  • 코드의 빈칸 <blank1>에 사용된 메서드(함수) 이름을 답안10_1 변수에 저장하세요. (예: 답안10_1 = '함수명')

문제 풀이 및 해설

제시된 조건에 맞는 풀이 코드는 다음과 같습니다.

Python
 
import pandas as pd
from sklearn.preprocessing import LabelEncoder

# (df 데이터프레임이 이미 있다고 가정)
# 예: df = pd.DataFrame({'Item': ['사과', '상추', '소고기', '배추'], 
#                      'Category': ['과일', '채소', '육류', '채소']})

# 1. LabelEncoder 객체 생성
le = LabelEncoder()

# 2. 'Category' 컬럼에 fit과 transform을 동시에 적용 (<blank1>)
#    변환된 결과를 새 컬럼 'Category_encoded'에 저장
df['Category_encoded'] = le.fit_transform(df['Category']) # <blank1> = fit_transform

# --- 답안 저장 ---
답안10_1 = 'fit_transform'

# --- 결과 확인 (선택 사항) ---
# print(df)
#
#   Item Category  Category_encoded
# 0   사과       과일                 0
# 1   상추       채소                 2
# 2  소고기       육류                 1
# 3   배추       채소                 2 
# (참고: '과일':0, '육류':1, '채소':2 로 자동 변환됨. 가나다순)

핵심 개념 설명

  1. LabelEncoder(): sklearn.preprocessing 모듈에서 제공하는 클래스입니다. 먼저 le = LabelEncoder()처럼 객체를 생성해야 합니다.
  2. fit_transform( ): LabelEncoder의 핵심 메서드입니다.
    • fit(): 'Category' 컬럼에 어떤 고유값들(예: '과일', '채소', '육류')이 있는지 학습합니다.
    • transform(): 학습한 고유값들을 0부터 시작하는 정수(0, 1, 2)로 변환합니다.
    • fit_transform()은 이 두 과정을 한 번에 처리해 줍니다.
  3. 원-핫 인코딩(get_dummies)과의 차이점
    • 원-핫 인코딩: Category가 '과일', '채소', '육류' 3종류라면, 'Category_과일', 'Category_채소', 'Category_육류'라는 3개의 새로운 컬럼을 만들고 0과 1로 표시합니다.
    • 라벨 인코딩: 'Category'라는 1개의 컬럼을 유지하되, 값을 0, 1, 2와 같은 숫자로 바꿉니다.
    원본 원-핫 인코딩 (get_dummies) 라벨 인코딩 (LabelEncoder)
    Category Category_과일 Category_채소
    과일 1 0
    채소 0 1
    육류 0 0
    채소 0 1

 

 

2️⃣데이터 전처리 & 스케일링

 
from sklearn.preprocessing import StandardScaler, MinMaxScaler, RobustScaler
 
# 표준화 (평균 0, 분산 1) → 가장 많이 씀
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)
# 정규화 (0~1 범위)
scaler = MinMaxScaler()
 
# 이상치에 강건한 스케일링
scaler = RobustScaler()

📌 기억할 점:

  • StandardScaler → 기본값, 정규분포 가정
  • MinMaxScaler → [0, 1] 범위 (신경망에 자주 사용)
  • RobustScaler → 이상치 많을 때

3️⃣머신러닝 기본 구조

# 모델 불러오기
from sklearn.linear_model
import LinearRegression, LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score, mean_squared_error
 
# 학습
model = LogisticRegression()
model.fit(X_train, y_train)
 
# 예측
y_pred = model.predict(X_test)
# 평가
acc = accuracy_score(y_test, y_pred)
mse = mean_squared_error(y_test, y_pred)

📌 기억할 점:

  • 지도학습 = 입력(X), 라벨(y) 있음 → 회귀(연속값), 분류(범주값)
  • 비지도학습 = 라벨 없음 → 군집, 차원축소

4️⃣딥러닝 필수 개념

 
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout

# 다층 신경망 (입력층 → 은닉층 → 출력층)
model = Sequential([
    Dense(128, activation='relu', input_shape=(X_train.shape[1],)),
    Dropout(0.3),
    Dense(64, activation='relu'),
    Dropout(0.3),
    Dense(10, activation='softmax')  # 다중 클래스 분류 (출력 10개)
])

model.compile(optimizer='adam', 
              loss='categorical_crossentropy', 
              metrics=['accuracy'])

model.fit(X_train, y_train, epochs=10, batch_size=32, validation_split=0.2)

📌 기억할 점:

  • loss vs val_loss → 과적합 여부 확인
  • Dropout: 과적합 방지 (무작위 뉴런 끊기)
  • BatchNormalization: 학습 안정화 (정규화)

DL 핵심 개념 정리

  • Scaling(스케일링): 입력 특성 범위를 맞춰 모델 학습 안정화
  • Dropout: 과적합 방지
  • BatchNormalization: 학습 안정화 (각 층 입력 정규화)
  • Activation:
    • relu: 은닉층
    • sigmoid: 이진 분류 출력층
    • softmax: 다중 분류 출력층

DL 정리 (업데이트)

  1. fit → predict → evaluate 사이클만 기억하면 된다.
  2. 스케일링(표준화/정규화)은 모델 학습 안정성에 필수다.
  3. 과적합은 train↑ test↓, Dropout/Regularization으로 막는다.
  4. 이진 분류는 Sigmoid, 다중 분류는 Softmax를 출력층에 쓴다.
  5. ML도 DL도 LLM도 결국 “데이터 → 손실 → 최적화 → 반복”이다.

5️⃣핵심 용어

  • Overfitting(과적합): train ↑, test ↓
  • Underfitting(과소적합): train/test 둘 다 ↓
  • Regularization: 과적합 방지 (L1, L2, Dropout)
  • Hyperparameter: 사용자가 설정 (learning rate, batch size, epoch 등)
  • Parameter: 모델이 학습으로 찾는 값 (가중치, bias)
  • Epoch: 전체 데이터 1회 학습
  • Batch: 한 번에 학습하는 데이터 묶음

6️⃣시각화 필수 (Seaborn / Matplotlib)

 
import seaborn as sns
import matplotlib.pyplot as plt
 
sns.barplot(data=df, x='col1', y='col2', hue='type')
 
plt.show()

7️⃣ 시험 포인트

✅ 결측치 확인: isna(), sum()
✅ 데이터 분리: train_test_split
✅ 모델 학습: fit()
✅ 모델 평가: accuracy_score, mean_squared_error
✅ 과적합 방지: Dropout, Regularization
✅ 지도 vs 비지도 차이: 라벨 유무
✅ loss / val_loss 차이
✅ Hyperparameter vs Parameter 구분


🎯 5문장 정리

  1. fit → predict → evaluate 사이클만 기억하면 된다.
  2. 결측치는 isna()로 확인, dropna/fillna로 처리한다.
  3. 과적합은 train↑ test↓, Dropout/Regularization으로 막는다.
  4. Hyperparameter는 내가 정하고, Parameter는 모델이 학습한다.
  5. ML도 DL도 LLM도 결국 “데이터 → 손실 → 최적화 → 반복”이다.