인공 신경망을 기반이며, 데이터를 바탕으로 복잡한 해턴을 학습하고 문제를 해결하는 머신러닝의 하위 분야
머신러닝: 상대적으로 적은 양의 데이터로도 학습 가능
ㄴ> 작은 데이터셋에서 좋은 성능을 낼 수 있도록 설계된 알고리즘이 많음
딥러닝: 매우 큰 데이터셋 필요
ㄴ> 계층이 깊고 복잡하여 충분히 많은 데이터를 사용해서 높은 성능 보장
컴퓨터가 사람의 뇌를 본떠서 만든 알고리즘
여러 입력을 받아 하나의 출력을 생성하는 단순한 모델
① 초기화:가중치와 편향을 임의의 값으로 설정
② 예측 및 오차 계산: 입력 데이터를 통해 예측 값을 계싼, 실제 값과의 차이를 구함
③ 가중치 및 편향 업데이트: 오차를 기반으로 가중치와 편향을 조정하여 모델이 점차 정확한 예측을 할 수 있도록 함
④ 반복: 오차가 최소화될 때까지 또는 정해진 횟수만큼 위 과정 반복
① 데이터 입력: 입력층에서 데이터 전달
② 패턴 학습: 은닉층에서 활성화 함수를 사용해 입력 데이터의 패턴을 학습
③ 결과 출력: 출력층에서 학습된 정보를 바탕으로 예측값 계산
④ 손실 계산: 예측값과 실제값 간 차이를 손실 함수로 계산
⑤ 가중치 업데이트: 역전파와 경사하강법을 사용하여 가중치와 편향을 조정
입력 값을 기반으로 출력 값을 비선형적으로 변환하여 신경망이 복잡한 패턴과 관계를 학습
𝑓(𝑥) = max(0,𝑥)
𝑓(𝑥) = 1/1+e^3
예측 값과 실제 값 간의 차이를 측정하는 함수
신경망의 학습 과정에서 오류를 기반으로 가중치를 조정하는 알고리즘
① 순방향 전달: 입력 데이터를 각 층에 전달하여 출력 계산
각 뉴런에서 활성화 함수 적용하여 비선형성 추가 -> 마지막 층에서 출력값 생성
② 손실 계산: 손실 함수로 예측 값과 실제 값 간의 손실 계산
③ 오류 역전파: 손실 함수의 출력값을 기준, 출력층 -> 입력층으로 이동하며 각 가중치에 대한 기울기 계산
ㄴ> 이 과정은 체인 룰을 사용하여 이루어짐
ㄴ> 체인 룰: 복잡한 함수의 미분 계산 시, 각 단계별 미분 값을 곱하는 방법
④ 가중치 업데이트: 경사 하강법을 사용하여 가중치 조정
딥러닝 모델을 쉽고 효율적으로 개발할 수 있도록 도와주는 도구
import numpy as np
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from sklearn.model_selection import train_test_split
from sklearn.datasets import make_classification
# 1. 데이터 생성 및 전처리
x, y = make_classification(
n_samples=1000, # 데이터 샘플 수
n_features=20, # 특징(특성) 수
n_classes=2, # 클래스 수
random_state=42 # 랜덤 시드 고정
)
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=42)
# 2. 모델 생성
model = Sequential([
Dense(16, activation='relu', input_shape=(x_train.shape[1],)),
Dense(8, activation='relu'),
Dense(1, activation='sigmoid')
])
# 3. 모델 컴파일
model.compile(
optimizer='adam',
loss='binary_crossentropy',
metrics=['accuracy']
)
# 4. 모델 훈련
history = model.fit(
x_train, y_train, # 학습용 데이터와 레이블
validation_split=0.2, # 검증 데이터 비율 (학습 데이터의 20%)
epochs=10, # 학습 반복 횟수
batch_size=32, # 한 번의 학습에서 사용하는 데이터 샘플 수
verbose=1 # 학습 진행 상태를 출력
)
# 5. 모델 평가
test_loss, test_accuracy = model.evaluate(x_test, y_test)
print(f"테스트 손실: {test_loss:.4f}, 테스트 정확도: {test_accuracy:.4f}")
# 6. 모델 예측
predictions = model.predict(x_test[:5]) # 테스트 데이터 중 5개의 샘플 예측
print("예측 결과:", predictions)
① 모델의 구성: 입력층 -> 은닉층 -> 출력층으로 구성
ㄴ> 활성화 함수는 모델이 데이터를 비선형적으로 표현
② 학습의 흐름: 데이터 준비 -> 모델 설계 -> 모델 컴파일 -> 훈련 -> 평가 -> 예측
③ Keras 장점: 코드가 직관적이고 간단하여 초보자도 쉽게 모델 설계 및 학습 가능
주어진 데이터를 두 개의 클래스로 구분하는 문제를 해결하는 과정
model.compile(optimizer='adam',
loss='binary_crossentropy',
metrics=['accuracy'])
history = model.fit(x_train, y_train,
validation_data=(x_val, y_val),
epochs=20,
batch_size=32)
from tensorflow.keras.callbacks import EarlyStopping
early_stopping = EarlyStopping(monitor='val_loss', patience=3)
history = model.fit(x_train, y_train,
validation_data=(x_val, y_val),
epochs=50,
batch_size=32,
callbacks=[early_stopping])
from tensorflow.keras.layers import Dropout
model.add(Dropout(0.5))
test_loss, test_accuracy = model.evaluate(x_test, y_test)
print(test_accuracy)
predictions = model.predict(new_data)
predicted_classes = (predictions > 0.5).astype(int)
혼련(Training), 검증(Validation), 테스트(Test) 데이터셋이 있으며, 모델 학습 과정에서 중요한 역할을 함
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.datasets import make_classification
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import classification_report
# 1. 데이터 생성 및 전처리
X, y = make_classification(
n_samples=1000,
n_features=20,
n_informative=15,
n_redundant=5,
random_state=42
)
X_train, X_temp, y_train, y_temp = train_test_split(X, y, test_size=0.3, random_state=42)
X_val, X_test, y_val, y_test = train_test_split(X_temp, y_temp, test_size=0.5, random_state=42)
# 정규화
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_val = scaler.transform(X_val)
X_test = scaler. transform(X_test)
# 2. 모델 설계
model = tf.keras.Sequential([
tf.keras.layers.Input(shape=(X_train.shape[1],)),
tf.keras.layers.Dense(64, activation='relu'),
tf.keras.layers.Dropout(0.5),
tf.keras.layers.Dense(32, activation='relu'),
tf.keras.layers.Dense(1, activation='sigmoid')
])
# 3. 모델 컴파일
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
# 4. Early Stopping 설정
early_stopping = tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=5, restore_best_weights=True)
# 5. 모델 훈련
history = model.fit(X_train, y_train,
validation_data=(X_val, y_val),
epochs=50, batch_size=32,
callbacks=[early_stopping])
# 6. 모델 평가
test_loss, test_accuracy = model.evaluate(X_test, y_test)
print(f"Test Loss: {test_loss:.4f}, Test Accuracy: {test_accuracy:.4f}")
# 7. 예측
predictions = model.predict(X_test)
predicted_classes = (predictions > 0.5).astype(int)
# 8. 분류 보고서 출력
print(classification_report(y_test, predicted_classes))
# 9. 학습 결과 시각화
# 훈련 및 검증 손실 시각화
plt.plot(history.history['loss'], label='Training Loss')
plt.plot(history.history['val_loss'], label='Validation Loss')
plt.title('Loss Over Epochs')
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.legend()
plt.show()
# 훈련 및 검증 정확도 시각화
plt.plot(history.history['accuracy'], label='Training Accuracy')
plt.plot(history.history['val_accuracy'], label='Validation Accuracy')
plt.title('Accuracy Over Epochs')
plt.xlabel('Epochs')
plt.ylabel('Accuracy')
plt.legend()
plt.show()
입력 데이터를 여러 클래스 중 하나로 분류하는 문제
① 데이터 수집: 사용할 데이터셋을 준비 (각 클래스에 해당하는 레이블이 있어야 함)
② 데이터 전처리: One-Hot Encoding, 정규화
③ 데이터 분리: 데이터를 훈련, 검증, 테스트로 나눔
① 입력층: 데이터의 차원과 동일한 입력을 받는 층
② 은닉층: 활성화 함수로 ReLU를 사용하여 비선형성 추가
ㄴ> Fully Connected Layer(완전 연결층), Convolutional Layer(이미지 문제의 경우)를 포함
③ 출력층: 출력 뉴런의 수는 클래스 수와 동일
ㄴ> Softmax 활성화 함수를 사용하여 각 클래스에 대한 확률을 계산
① 손실 함수: Categorical Crossentropy 손실 함수 사용
② 옵티마이저: Gradient Descent 기반 알고리즘(ex. Adam)을 사용하여 가중치 업데이트
③ 훈련 프로세스: 모델에 훈련 데이터를 입력 -> 반복적으로 가중치 업데이트하여 손실 최소화
ㄴ> 과적합 방지, 성능 모니터링