머신러닝/딥러닝�기초 이론 및 실습
왕 재 민
경북대학교
금속재료공학과
인공지능재료과학 분과 여름학교
강의 교수 소개
왕재민
학력처 박사 2024 포항공과대학교�학력처 (Pohang University of Science & Technology, POSTECH)�학력처 학사 2019 포항공과대학교�학력처 (Pohang University of Science & Technology, POSTECH)
경력처 2026.03- 경북대학교 조교수
경력처 2025.05-2026.02 Postdoctoral Researcher at Max-Planck-Institut für
경력처 Nachhaltige Materialien
경력처 2024.02-2025.04 포항공과대학교 항공재료연구센터 박사후연구원
연락처 전화번호 : 053-950-5562
연락처 오피스가 : 미래창직관 510호
연락처 이메일가 : jmwang@knu.ac.kr
2 / 124
재료과학에서 인공지능의 필요성
합금 조성에서 비롯되는 구조-미세조직-특성 관계
3 / 124
인공지능 (AI), 머신러닝 (ML), 딥러닝 (DL)
인공지능 기술의 타임라인
AI 기법의 관계
4 / 124
지도학습, 비지도학습, 강화 학습
| 지도학습 | 비지도학습 | 강화학습 |
데이터의 특성 | 입력 데이터와 정답이 함께 제공 | 정답 없이 입력 데이터만 제공 | 환경과 상호작용하며 보상으로 학습 |
모델의 목적 | 입력과 정답 간의 관계를 학습하여 예측 | 데이터의 구조·패턴·군집 등을 스스로 발견 | 누적 보상을 최대화하는 행동 전략 학습 |
머신러닝의 종류
5 / 124
지도학습 – 분류
스팸 분류를 위한 레이블된 훈련 세트
6 / 124
지도학습 – 회귀
주어진 입력 특성으로 값을 예측
7 / 124
비지도학습 – 군집
유사한 입력들을 여러 군집으로 표현
8 / 124
비지도학습 – 차원 축소
3차원 데이터를 2차원 데이터로 표현
9 / 124
강화학습
강화학습의 예시
10 / 124
나쁜 데이터 – 스몰 데이터와 편향된 데이터
데이터 편향에 의해 왜곡된 선형 모델
11 / 124
나쁜 데이터 – 이상치와 노이즈
이상치가 존재하는 데이터셋
12 / 124
특성 공학
특성 공학 사례
13 / 124
나쁜 모델 – 과대 적합과 과소 적합
과소적합 모델, 최적 모델, 과대적합 모델
14 / 124
데이터 전처리
15 / 124
손실 함수 (Loss Function)
16 / 124
평가 지표 (Evaluation Metric)
17 / 124
머신러닝 모델의 평가
Holdout Validation vs K-fold Cross Validation
18 / 124
하이퍼파라미터 튜닝
그리드 탐색과 랜덤 탐색
19 / 124
기존 파이썬 제거 (해당 시)
20 / 124
기존 파이썬 제거 (해당 시)
21 / 124
파이썬 설치
22 / 124
파이썬 설치
23 / 124
파이썬 설치
24 / 124
파이썬 설치
25 / 124
파이썬 설치
26 / 124
VS Code 설치
27 / 124
VS Code 설치
28 / 124
VS Code 설치
29 / 124
VS Code 설치
30 / 124
VS Code 설치
31 / 124
VS Code 설치
32 / 124
VS Code 설치
33 / 124
VS Code 시작
34 / 124
VS Code 시작
35 / 124
VS Code 시작
36 / 124
VS Code 시작
37 / 124
VS Code 시작
38 / 124
VS Code 시작
39 / 124
필수 라이브러리 설치
40 / 124
새 주피터 노트북 파일 만들기
41 / 124
새 주피터 노트북 파일 만들기
42 / 124
새 주피터 노트북 파일 만들기
43 / 124
라이브러리 import
44 / 124
캘리포니아 주택 가격 데이터 회귀 예제
캘리포니아 주택 가격
45 / 124
캘리포니아 주택 가격 데이터 다운로드
import ssl # HTTPS 연결 시 사용할 SSL 보안 설정 모듈
import certifi # 신뢰할 수 있는 CA 인증서 번들을 제공하는 패키지
import urllib.request # URL을 통해 데이터를 다운로드하기 위한 모듈
import tarfile # .tar / .tgz 압축 파일을 읽고 해제하는 모듈
from pathlib import Path # 파일 경로를 객체 형태로 다루기 위한 모듈
import pandas as pd
def load_housing_data(): # 주택 데이터셋을 다운로드하고 불러오는 함수 정의
tarball_path = Path("datasets/housing.tgz") # 다운로드할 파일의 경로 설정
Path("datasets").mkdir(parents=True, exist_ok=True) # 폴더가 없으면 생성
url = "https://github.com/ageron/data/raw/main/housing.tgz"
ctx = ssl.create_default_context(cafile=certifi.where()) # certifi 인증서를 사용해 SSL 검증 컨텍스트 생성
with urllib.request.urlopen(url, context=ctx) as response: # URL 데이터 열기
tarball_path.write_bytes(response.read()) # 다운로드한 데이터를 저장
with tarfile.open(tarball_path) as housing_tarball: # 압축 파일 열기
housing_tarball.extractall(path="datasets") # 압축 해제
return pd.read_csv(Path("datasets/housing/housing.csv"))
housing = load_housing_data() # 함수 실행하여 데이터 로드
print(housing.head()) # 데이터의 상위 5개 행 출력
46 / 124
데이터 히스토그램 표시
실습
import matplotlib.pyplot as plt
housing.hist(bins=50, figsize=(16, 12))
plt.show()
47 / 124
Holdout Validation (Train/Test split)
규칙 없이 무작위 8:2 분할
출력:
from sklearn.model_selection import train_test_split
train_set, test_set = train_test_split(housing, test_size=0.2, random_state=42)
print(train_set.shape)
print(test_set.shape)
(16512, 10)
(4128, 10)
48 / 124
Pearson Correlation (피어슨 상관계수, r)
실습
출력:
corr_matrix = housing.corr(numeric_only=True)
print(corr_matrix["median_house_value"].sort_values(ascending=False))
median_house_value 1.000000
median_income 0.688075
total_rooms 0.134153
housing_median_age 0.105623
households 0.065843
total_bedrooms 0.049686
population -0.024650
longitude -0.045967
latitude -0.144160
Name: median_house_value, dtype: float64
49 / 124
Pearson Correlation (피어슨 상관계수, r)
실습
plt.scatter(
housing["median_income"],
housing["median_house_value"]
)
plt.xlabel("Median Income")
plt.ylabel("House Value")
plt.show()
r=0.688
50 / 124
Pearson Correlation (피어슨 상관계수, r)
실습
plt.scatter(
housing["population"],
housing["median_house_value"]
)
plt.xlabel("population")
plt.ylabel("House Value")
plt.show()
r=-0.025
51 / 124
결측치 제거
원본 데이터 보존을 위한 데이터 복사
결측치 제거
housing = train_set.drop("median_house_value", axis=1)
housing_labels = train_set["median_house_value"].copy()
print(housing)
print(housing_labels)
housing.dropna(inplace=True)
print(housing)
52 / 124
텍스트 특성 변환
텍스트 특성
출력:
housing_cat = housing[["ocean_proximity"]]
print(housing_cat.head(5))
ocean_proximity
13096 NEAR BAY
14973 <1H OCEAN
3785 INLAND
14689 INLAND
20507 NEAR OCEAN
53 / 124
텍스트 특성 변환
Ordinal Encoding
출력:
from sklearn.preprocessing import OrdinalEncoder
ordinal_encoder = OrdinalEncoder()
housing_cat_encoded = ordinal_encoder.fit_transform(housing_cat)
print(housing_cat_encoded[:5])
print(ordinal_encoder.categories_)
[[3.]
[0.]
[1.]
[1.]
[4.]]
[array(['<1H OCEAN', 'INLAND', 'ISLAND', 'NEAR BAY', 'NEAR OCEAN'],
dtype=object)]
54 / 124
텍스트 특성 변환
One-hot Encoding
출력:
from sklearn.preprocessing import OneHotEncoder
cat_encoder = OneHotEncoder()
housing_cat_1hot = cat_encoder.fit_transform(housing_cat)
print(housing_cat_1hot.toarray()[:5])
print(cat_encoder.categories_)
[[0. 0. 0. 1. 0.]
[1. 0. 0. 0. 0.]
[0. 1. 0. 0. 0.]
[0. 1. 0. 0. 0.]
[0. 0. 0. 0. 1.]]
[array(['<1H OCEAN', 'INLAND', 'ISLAND', 'NEAR BAY', 'NEAR OCEAN'],
dtype=object)]
55 / 124
특성 스케일링 (정규화)
Min-max scaling (0과 1 사이 값으로 정규화)
Mean-std scaling (-1과 1 사이 값으로 정규화)
from sklearn.preprocessing import MinMaxScaler
�housing_num = housing.select_dtypes(include=['number'])
�min_max_scaler = MinMaxScaler()
housing_num_min_max_scaled= min_max_scaler.fit_transform(housing_num)
print(housing_num_min_max_scaled[:5])
from sklearn.preprocessing import StandardScaler
housing_num = housing.select_dtypes(include=['number'])
�std_scaler = StandardScaler()
housing_num_std_scaled = std_scaler.fit_transform(housing_num)
print(housing_num_std_scaled[:5])
56 / 124
데이터 전처리 총정리
실습
from sklearn.compose import ColumnTransformer
### Load Data ###
housing = load_housing_data()
### Drop Missing Data ###
housing.dropna(inplace=True)
### Separate label ###
X = housing.drop("median_house_value", axis=1)
y = housing["median_house_value"]
### Train/Test Split ###
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
### Feature Scaling & One-hot encoding ###
num_cols = X_train.select_dtypes(include=['number']).columns
cat_cols = X_train.select_dtypes(exclude=['number']).columns
preprocessor = ColumnTransformer([
('num', StandardScaler(), num_cols),
('cat', OneHotEncoder(handle_unknown='ignore'), cat_cols)
])
X_train = preprocessor.fit_transform(X_train)
X_test = preprocessor.transform(X_test)
print(X_train[:5], y_train[:5])
57 / 124
선형 회귀 모델
선형 모델
58 / 124
선형 회귀 모델의 예측과 손실 함수
선형 모델
59 / 124
경사 하강법 (Gradient Descent)
손실 함수 (비용)과 경사 하강법
60 / 124
학습률 (Learning rate)
너무 작은 learning rate
61 / 124
학습률 (Learning rate)
너무 큰 learning rate
62 / 124
경사 하강법의 문제점
지역 최소 값과 평지
63 / 124
스케일링 (정규화, 표준화의 필요성)
정규화된 데이터 vs 원시 데이터
64 / 124
손실 함수의 미분 값 계산
65 / 124
과소적합과 과대적합
단순 선형 회귀와 2차, 300차 다항 회귀
66 / 124
선형 회귀 모델 훈련
실습
출력:
from sklearn.linear_model import LinearRegression
from sklearn.metrics import root_mean_squared_error
�lin_reg = LinearRegression()
lin_reg.fit(X_train, y_train)
�housing_predictions = lin_reg.predict(X_train)
print(housing_predictions[:5].round(-2)) # -2 = 십의 자리에서 반올림
lin_rmse = root_mean_squared_error(y_train, housing_predictions)
print(lin_rmse)
[228900. 138300. 228400. 211200. 225400.]
68508.07343981159
67 / 124
결정 트리 회귀 모델 훈련
실습
출력:
from sklearn.tree import DecisionTreeRegressor
tree_reg = DecisionTreeRegressor(random_state=42)
tree_reg.fit(X_train, y_train)
�housing_predictions = tree_reg.predict(X_train)
tree_rmse = root_mean_squared_error(y_train, housing_predictions)
print(tree_rmse)
0.0
68 / 124
머신러닝 모델의 평가
Holdout Validation vs K-fold Cross Validation
69 / 124
K-fold Cross Validation (결정 트리)
실습
출력:
from sklearn.model_selection import cross_val_score
�
tree_rmses = -cross_val_score(tree_reg, X_train, y_train,
scoring="neg_root_mean_squared_error", cv=10)
print(pd.Series(tree_rmses).describe())
count 10.000000
mean 68301.029041
std 2604.590694
min 64656.305437
25% 66464.904762
50% 68151.087180
75% 69118.006052
max 73557.007177
dtype: float64
70 / 124
K-fold Cross Validation (선형 회귀)
실습
출력:
lin_rmses = -cross_val_score(lin_reg, X_train, y_train,
scoring="neg_root_mean_squared_error", cv=10)
print(pd.Series(lin_rmses).describe())
count 10.000000
mean 68680.107227
std 1729.837660
min 65488.438180
25% 67887.430681
50% 69254.426193
75% 69621.550214
max 71116.627933
dtype: float64
71 / 124
K-fold Cross Validation (랜덤 포레스트)
실습
출력:
from sklearn.ensemble import RandomForestRegressor
forest_reg = RandomForestRegressor(random_state=42)
forest_rmses = -cross_val_score(forest_reg, X_train, y_train,
coring="neg_root_mean_squared_error", cv=10)
print(pd.Series(forest_rmses).describe())
count 10.000000
mean 49198.025690
std 1620.880465
min 47022.417532
25% 47954.443320
50% 49384.212936
75% 49744.933929
max 52802.076811
dtype: float64
72 / 124
Holdout Validation (랜덤 포레스트)
실습
출력:
forest_reg.fit(X_train, y_train)
housing_train_predictions = forest_reg.predict(X_train)
forest_train_rmse = root_mean_squared_error(y_train, housing_train_predictions)
print(forest_train_rmse)
housing_test_predictions = forest_reg.predict(X_test)
forest_test_rmse = root_mean_squared_error(y_test, housing_test_predictions)
print(forest_test_rmse)
18260.8865300175
48821.99815195788
73 / 124
하이퍼파라미터 튜닝
그리드 탐색과 랜덤 탐색
74 / 124
그리드 탐색
실습
출력:
from sklearn.model_selection import GridSearchCV
�forest_reg = RandomForestRegressor(random_state=42)
param_grid = {
"max_features": [4, 6, 8, 10]
}
grid_search = GridSearchCV(forest_reg, param_grid, cv=3,
scoring='neg_root_mean_squared_error')
grid_search.fit(X_train, y_train)
print(grid_search.best_params_)
{'max_features': 6}
75 / 124
랜덤 탐색
실습
출력:
from sklearn.model_selection import RandomizedSearchCV
from scipy.stats import randint
�forest_reg = RandomForestRegressor(random_state=42)
�param_distribs = {"max_features": randint(low=2, high=20)}
�rnd_search = RandomizedSearchCV(
forest_reg, param_distributions=param_distribs, n_iter=5, cv=3,
scoring='neg_root_mean_squared_error', random_state=42)
�rnd_search.fit(X_train, y_train)
�print(rnd_search.best_params_)
{'max_features': 9}
76 / 124
모델 저장 및 불러오기
모델 저장
모델 불러오기
import joblib
�
forest_reg.fit(X_train, y_train)
�
joblib.dump(forest_reg, "my_california_housing_model.pkl")
forest_reg_reloaded = joblib.load("my_california_housing_model.pkl")
predictions = forest_reg_reloaded.predict(X_train)
print(predictions[:5])
77 / 124
로지스틱 회귀
로지스틱 함수
78 / 124
로지스틱 회귀의 손실 함수 및 미분 값 계산
79 / 124
붓꽃 데이터셋 (Iris dataset)
붓꽃의 종류
80 / 124
로지스틱 회귀 모델의 결정 경계
추정 확률과 결정 경계
81 / 124
로지스틱 회귀 모델의 결정 경계
선형 결정 경계
82 / 124
소프트맥스 회귀 (Softmax regression)
소프트맥스 함수
83 / 124
소프트맥스 회귀의 손실 함수 및 미분 값 계산
84 / 124
결정 트리 분류
결정 트리 분류 예시
85 / 124
지니 불순도
결정 트리의 결정 경계
86 / 124
CART (Classification and Regression Tree) 훈련 알고리즘
87 / 124
규제 매개변수
규제하지 않은 결정트리와 규제를 추가한 결정트리의 결정 경계
88 / 124
결정 트리 회귀
두 개의 결정 트리 회귀 모델의 예측
89 / 124
앙상블 (Ensemble)
여러 분류기 훈련시키기
90 / 124
직접 투표 (hard voting)
직접 투표 분류기의 예측
91 / 124
직접 투표 (hard voting)
직접 투표 분류기의 예측
92 / 124
랜덤 포레스트 (Random Forest)
랜덤 포레스트
93 / 124
부스팅 (Boosting)
AdaBoost
94 / 124
스태킹 (Stacking)
스태킹과 블렌더
95 / 124
MNIST 분류 데이터 예제
MNIST 손글씨 데이터셋
96 / 124
MNIST 데이터셋 다운 및 확인
실습
출력:
from sklearn.datasets import fetch_openml
�mnist = fetch_openml('mnist_784', as_frame=False)
X, y = mnist.data, mnist.target
�print(X)
print(X.shape)
print(y)
print(y.shape)
[[0 0 0 ... 0 0 0]
[0 0 0 ... 0 0 0]
[0 0 0 ... 0 0 0]
...
[0 0 0 ... 0 0 0]
[0 0 0 ... 0 0 0]
[0 0 0 ... 0 0 0]]
(70000, 784)
['5' '0' '4' ... '4' '5' '6']
(70000,)
97 / 124
MNIST 이미지 확인
실습
import matplotlib.pyplot as plt
def plot_digit(image_data):
image = image_data.reshape(28, 28)
plt.imshow(image, cmap="binary")
plt.axis("off")
some_digit = X[0]
plot_digit(some_digit)
plt.show()
98 / 124
Train/Test 분리
실습
출력:
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
print(X_train.shape)
print(y_train.shape)
print(X_test.shape)
print(y_test.shape)
(56000, 784)
(56000,)
(14000, 784)
(14000,)
99 / 124
이진 분류 (Binary Classification)
실습
출력:
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import cross_val_score
y_train_5 = (y_train == '5') # 5는 True고, 다른 숫자는 모두 False
y_test_5 = (y_test == '5')
tree_clf = DecisionTreeClassifier(random_state=41)
tree_clf.fit(X_train, y_train_5)
print(tree_clf.predict([some_digit]))
print(y[0])
print(cross_val_score(tree_clf, X_train, y_train_5, cv=3, scoring="accuracy"))
[ True]
5
[0.97241121 0.97150051 0.9710704 ]
100 / 124
분류 평가 지표 (Evaluation Metric)
101 / 124
Confusion Matrix
실습
출력:
from sklearn.metrics import confusion_matrix
from sklearn.model_selection import cross_val_predict
y_train_pred = cross_val_predict(sgd_clf, X_train, y_train_5, cv=3)
�cm = confusion_matrix(y_train_5, y_train_pred)
print(cm)
[[50183 777]
[ 810 4230]]
102 / 124
Precision, Recall, F1-score
실습
출력:
from sklearn.metrics import precision_score, recall_score, f1_score
print(precision_score(y_train_5, y_train_pred))
print(cm[1, 1] / (cm[0, 1] + cm[1, 1]))
print(recall_score(y_train_5, y_train_pred))
print(cm[1, 1] / (cm[1, 0] + cm[1, 1]))
print(f1_score(y_train_5, y_train_pred))
print(cm[1, 1] / (cm[1, 1] + (cm[1, 0] + cm[0, 1]) / 2))
0.8448172558418214
0.8448172558418214
0.8392857142857143
0.8392857142857143
0.8420424007166318
0.8420424007166318
103 / 124
모델 변화에 따른 예측 성능 변화
실습
출력:
from sklearn.ensemble import RandomForestClassifier
forest_clf = RandomForestClassifier(random_state=42)
�y_train_pred = cross_val_predict(forest_clf,X_train,y_train_5,cv=3)
cm = confusion_matrix(y_train_5, y_train_pred)
print(cm)
print(precision_score(y_train_5, y_train_pred))
print(recall_score(y_train_5, y_train_pred))
print(f1_score(y_train_5, y_train_pred))
[[50914 46]
[ 679 4361]]
0.9895620603585206
0.8652777777777778
0.9232560601249074
104 / 124
다중 분류 (Multiclass Classification)
실습
출력:
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import cross_val_score
rf_clf = RandomForestClassifier(random_state=42)
rf_clf.fit(X_train[:2000], y_train[:2000])
print(rf_clf.predict([some_digit]))
some_digit_scores = rf_clf.predict_proba([some_digit])
print(some_digit_scores.round(2))
print(some_digit_scores.argmax())
print(cross_val_score(rf_clf, X_train[:2000], y_train[:2000], cv=3, scoring="accuracy"))
['5']
[[0.04 0.02 0.04 0.28 0. 0.45 0.04 0.07 0.05 0.01]]
5
[0.92803598 0.89505247 0.88438438]
105 / 124
Confusion Matrix
실습
from sklearn.metrics import ConfusionMatrixDisplay
y_train_pred = cross_val_predict(rf_clf, X_train[:2000],
y_train[:2000], cv=3)
ConfusionMatrixDisplay.from_predictions(y_train[:2000], y_train_pred)
plt.show()
106 / 124
인공지능 (AI), 머신러닝 (ML), 딥러닝 (DL)
인공지능 기술의 타임라인
AI 기법의 관계
107 / 124
인공 뉴런
생물학적 뉴런과 인공 뉴런
108 / 124
인공 뉴런
생물학적 뉴런과 인공 뉴런
109 / 124
인공신경망
입력, 은닉, 출력 층으로 구성된 인공신경망
110 / 124
Activation Function이 필요한 이유
111 / 124
대표적 Activation Functions
Sigmoid와 ReLU
112 / 124
Forward and Back Propagation
인공신경망의 Back Propagation
113 / 124
Convolutional Neural Network (CNN)
CNN의 구조
114 / 124
Convolution
Convolution의 과정
115 / 124
Pooling
Max Pooling과 Average Pooling
116 / 124
Recurrent Neural Network (RNN)
기본적 인공신경망과 RNN의 비교
117 / 124
Long Short-Term Memory
LSTM
118 / 124
Attention
Self-Attention
119 / 124
Self-Attention
120 / 124
Transformer
GPT = Generative Pre-trained Transformer
121 / 124
Graph Neural Network (GNN)
그래프로 표현된 합금 시스템
122 / 124
Graph Neural Network (GNN)
그래프로 표현된 합금 시스템
123 / 124
Autoencoder
그래프로 표현된 합금 시스템
124 / 124
감사합니다
왕 재 민
경북대학교
금속재료공학과
인공지능재료과학 분과 여름학교