머신러닝_전이학습

홍성채·2022년 4월 28일
0

머신러닝

목록 보기
15/15

전이학습

전이학습이란

  1. 다른 데이터 셋을 사용하여 이미 학습한 모델을 유사한 다른 데이터를 인식하는데 사용하는 기법
  2. 특히 새로 훈련 시킬 데이터가 충분히 확보되지 못한경우에 학습 효율을 높여준다
  3. 사전학습모델을 이용하는 방법은 특성 추출방식과 미세 조정 방식이 있다.

특성 추출 방식 코드

from tensorflow.keras.applications import VGG16
pre_trained_model = VGG16(include_top=False,
                          weights = "imagenet",
                          input_shape=(224,224,3))
pre_trained_model.summary()#모델층의 요약정보
  • 출력화면

cnn_model2 = Sequential()
cnn_model2.add(pre_trained_model)
cnn_model2.add(Flatten())
cnn_model2.add(Dense(units=128,activation='relu'))
cnn_model2.add(Dense(units=64,activation='relu'))
cnn_model2.add(Dense(units=2,activation='softmax'))
# 특성추출방식
pre_trained_model.trainable = False
cnn_model2.summary()
  • 출력화면

cnn_model2.compile(loss="sparse_categorical_crossentropy",
                   optimizer="Adam",
                   metrics=['accuracy'])
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=425)
cnn_model2.fit(X_train,y_train,epochs=20)
pre = cnn_model2.predict(X_test)
from sklearn.metrics import classification_report
print(classification_report(y_test,np.argmax(pre,axis=1)))


미세조정방식으로 할 경우 아래처럼 수정하면 된다.

pre_trained_model = VGG16(include_top=False,
                          weights = "imagenet",
                          input_shape=(224,224,3))
#미세조정방식
for layer in pre_trained_model.layers :
  #print(layer.name)
  if layer.name == "block5_conv3" :
    layer.trainable = True
  else :
    layer.trainable = False

데이터 증강


from tensorflow.keras.preprocessing.image import ImageDataGenerator
aug = ImageDataGenerator(rotation_range=90,
                         zoom_range=0.2,
                         horizontal_flip=True,
                         height_shift_range=0.2)
from tensorflow.keras.applications import MobileNetV2
pre_trained_model = MobileNetV2(include_top=False,
                          weights = "imagenet",
                          input_shape=(224,224,3))
pre_trained_model.trainable=False
pre_trained_model.summary()

from tensorflow.keras.layers import AveragePooling2D
cnn_model4 = Sequential()
cnn_model4.add(pre_trained_model)
cnn_model4.add(AveragePooling2D())
cnn_model4.add(Flatten())
cnn_model4.add(Dense(units=128,activation='relu'))
cnn_model4.add(Dense(units=64,activation='relu'))
cnn_model4.add(Dense(units=2,activation='softmax'))
from sklearn import metrics
cnn_model4.compile(loss="sparse_categorical_crossentropy",
                   optimizer='Adam',
                   metrics=['accuracy'])
cnn_model4.fit(aug.flow(X_train,y_train),
               epochs=50)
profile
초보 코딩

0개의 댓글

관련 채용 정보