njs03332 / ml_study

3 stars 0 forks source link

2023/07/26 ~ 2023/08/03 #71

Open njs03332 opened 1 year ago

njs03332 commented 1 year ago
njs03332 commented 1 year ago

assign roles -s 0726 -c 14.5 14.6 14.7

njs03332 commented 1 year ago
0 1 2
member 김유리 한단비 주선미
chapter 14.5 14.6 14.7
givitallugot commented 1 year ago

14.7 사전훈련된 모델을 사용한 전이학습

충분하지 않은 데이터로 이미지 분류기를 훈련하려면 사전훈련된 하위층을 사용하는 것이 좋음

Xception 모델을 사용하여 꽃 이미지를 분류하는 모델 훈련

dataset, info = tfds.load("tf_flowers", as_supervised=True, with_info=True) dataset_size = info.splits["train"].num_examples class_names = info.features["label"].names # ["dandelion", "daisy", ] n_classes = info.features["label"].num_classes


- 데이터셋의 처음 10%를 테스트 세트로, 15%를 검증 세트로, 나머지 75%를 훈련 세트로 나눔
```python
test_set_raw, valid_set_raw, train_set_raw = tfds.load(
    "tf_flowers",
    split=["train[:10%]", "train[10%:25%]", "train[25%:]"],
    as_supervised=True)

optimizer = keras.optimizers.SGD(learning_rate=0.2, momentum=0.9, decay=0.01) model.compile(loss="sparse_categorical_crossentropy", optimizer=optimizer, metrics=["accuracy"]) history = model.fit(train_set, steps_per_epoch=int(0.75 dataset_size / batch_size), validation_data=valid_set, validation_steps=int(0.15 dataset_size / batch_size), epochs=5)


- 몇 번의 에포크동안 검증 정확도가 75% ~ 80%에 도달하고, 더 나아지지 않을 것 => 이는 새로 추가한 최상위 층이 잘 훈련된 것
- 이제 고정했던 것을 해제하고 훈련을 계속 함, 이때 사전 훈련된 가중치가 훼손되는 것을 피하기 위해 훨씬 작은 학습률을 이용
```python
for layer in base_model.layers:
    layer.trainable = True

optimizer = keras.optimizers.SGD(learning_rate=0.01, momentum=0.9,
                                 nesterov=True, decay=0.001)
model.compile(loss="sparse_categorical_crossentropy", optimizer=optimizer,
              metrics=["accuracy"])
history = model.fit(train_set,
                    steps_per_epoch=int(0.75 * dataset_size / batch_size),
                    validation_data=valid_set,
                    validation_steps=int(0.15 * dataset_size / batch_size),
                    epochs=40)
danbi5228 commented 1 year ago

14.6 케라스에서 제공하는 사전훈련된 모델 사용하기

ResNet-50 모델을 만들고 이미지넷 데이터셋에서 사전훈련된 가중치를 다운로드

model = keras.applications.resnet50.ResNet50(weights="imagenet")

모델에 맞게 이미지 크기 변경

resize는 가로세로 비율을 유지하지 않으므로 문제가 될 경우 crop_and_resize 함수를 사용

images_resized = tf.image.resize(images, [224,224])

모델이 기대하는 입력값의 범위는 0 ~ 255 사이. 전처리 진행

inputs = keras.applications.resnet50.preprocess_input(images_resized * 255)

사전훈련된 모델을 사용해 예측 수행

Y_proba는 행이 하나의 이미지이고 열이 하나의 클래스인 행렬

최상위 K개의 예측을 클래스 이름과 예측 클래스의 추정 확률을 출력하려면 decode_predictions() 함수를 사용 (p.259 상단 확인)

Y_proba = model.predict(inputs)

njs03332 commented 1 year ago

14.5 케라스를 사용해 ResNet-34 CNN 구현하기

model.add(keras.layers.GlobalAvgPool2D()) model.add(keras.layers.Flatten()) model.add(keras.layers.Dense(10,activation='softmax'))



- for 루프 - 처음 3개 RU는 64개 필터, 그 다음 4개 RU는 128개 필터를 가짐
- 필터 개수가 이전 RU와 동일할 경우 스트라이드를 1로 설정하고, 아니면 2로 설정
- 그 다음 `ResidualUnit`을 더하고 마지막에 `prev_filters`를 업데이트함