Replicated

전이 학습 (Transfer Learning) 본문

학부/딥러닝

전이 학습 (Transfer Learning)

라구넹 2025. 12. 7. 04:01

전이학습

- 기계학습에서 한 문제를 해결하면서 얻은 지식을 저장해두었다가, 관련있는 문제를 해결할 때 활용

- ImageNet 문제를 해결할 때 사용한 DNN 모델을 다른 이미지 분류 문제를 다른 이미지 분류 문제에 활용하는 것이 예

 

재사용되는 요소

- 신경망 구조

- 학습된 가중치

 

DenseNet121

from keras.preprocessing.image import load_img
from keras.preprocessing.image import img_to_array
from keras.applications import DenseNet121
from keras.applications.densenet import preprocess_input
from keras.applications.densenet import decode_predictions

model = DenseNet121(weights='imagenet')

image = load_img('경로.jpg', target_size=(224, 224))
image = img_to_array(image)
image = image.reshape((1, image.shape[0], image.shape[1], image.shape[2]))

image = preprocess_input(image)
pred = model.predict(image)

label = decode_predictions(pred)
label = label[0][0]
print('%s (%.2f%%)' % (label[1], label[2]*100))

이미지 보고 뭔지 분류하는 코드

 

from tensorflow.keras.models import Model
import matplotlib.pyplot as plt

this_layer = model.layers[2]
tmp_model = Model(inputs=model.input, outputs=this_layer.output)
feature_map =tmp_model.predict(image, verbose=0)

print('Layer Name: ', this_layer.name)
print('feature map shape: ', feature_map.shape)

plt.imshow(feature_map[0, :, :, 0], cmap='gray')
plt.show()
plt.imshow(feature_map[0, :, :, 1], cmap='gray')
plt.show()

첫번째 컨볼루션 레이어 출력

 

 

CIFAR-10 Classification

작은 컬러 이미지로 구성된 이미지 분류용 벤치마크 데이터셋

 

목표

ImageNet의 데이터셋으로 구축된 MobileNetV3 모델에 대해

Cifar 데이터셋으로 전이 학습하기.. MobilNetV3 모델의 아키텍처 변형

 

from keras import optimizers
from keras.datasets import cifar10
from keras.models import Sequential
from keras.layers import Dropout, Flatten, Dense
from tensorflow.python.keras.utils import np_utils
from keras.applications import MobileNetV3Small
import keras.backend as K
K.clear_session()

img_width, img_height = 32, 32
base_model = MobileNetV3Small(weights='imagenet',
include_top=False,
input_shape= (img_width, img_height, 3))

base_model.trainable = False # fix original weights
base_model.summary()

nb_epoch = 50 
nb_classes = 10

준비 단계 코드

weights='imagenet' -> imageNet으로 학습된 가중치 가져옴

include_top=False -> MobileNetV2의 마지막 Fully Connected Layer 제거

base_model.trainable = False -> 사전 학습된 가중치 고정

 

(X_train, y_train), (X_test, y_test) = cifar10.load_data()
y_train = np_utils.to_categorical(y_train, nb_classes)
y_test = np_utils.to_categorical(y_test, nb_classes)

model = Sequential()
model.add(base_model)
model.add(Flatten())
model.add(Dense(1024,activation=('relu')))
model.add(Dense(512,activation=('relu')))
model.add(Dense(256,activation=('relu')))
model.add(Dense(128,activation=('relu')))
model.add(Dense(10,activation=('softmax')))

model.summary()

준비해놨던 모델에 덧붙이기

 

model.compile(loss='binary_crossentropy',
	optimizer=optimizers.SGD(learning_rate=1e-2),
	metrics=['accuracy'])
model.fit(X_train, y_train,
	validation_data=(X_test, y_test),
	epochs=nb_epoch,
	batch_size=200,
	verbose=1)

scores = model.evaluate(X_test, y_test, verbose=0)
print("loss: %.2f" % scores[0])
print("acc: %.2f" % scores[1])

학습

 

* 전이 학습에서 base model의 파라미터 값들을 갱신할지 말지를 정할 수 있음

base_model.trainable = False

- 베이스 모델의 파라미터 값들은 고정하고 사용자가 추가한 레이어들의 파라미터에 대해서만 갱신이 일어나도록 함(오류 역전파시)

- 학습이 빠르게 진행될 수 있으나 모델의 성능이 저하될 가능성이 있음

 

 

Keras Regression

from keras.models import Sequential
from keras.layers import Dense
from sklearn.model_selection import train_test_split
from keras.datasets import boston_housing

(X_train, y_train), (X_test, y_test) = boston_housing.load_data()
model = Sequential()
model.add(Dense(16, input_dim=13, activation='relu'))
model.add(Dense(8, activation='relu'))
model.add(Dense(1)) # output

model.compile(loss='mean_squared_error', optimizer='adam')
model.fit(X_train, y_train, epochs=200, batch_size=10)

Y_prediction = model.predict(X_test).flatten()
for i in range(10):
	real_price = y_test[i]
	predicted_price = Y_prediction[i]
	print('Real Price: {:.3f}, Predicted Price: {:.3f}'.format(real_price,
			predicted_price))

보스턴 집값

 

 

컴퓨터 비전에서 딥러닝 활용

1. 이미지 분류

2. 지역화된 이미지 분류

3. 물체 감지

4. 물체 세그멘트화

5. 스타일 변화

6. 이미지 색칠

7. 이미지 복원

8. 해상도 올리기

9. 이미지 합성

 

'학부 > 딥러닝' 카테고리의 다른 글

자연어 처리 : RNN, LSTM  (0) 2025.12.07
자연어 처리 : Word representation  (0) 2025.12.07
Keras CNN - Argumentation  (0) 2025.10.25
Keras CNN - MNIST  (0) 2025.10.25
Keras CNN  (0) 2025.10.25