printf("ho_tari\n");

PCA #10 본문

대학교 4학년 1학기/인공신경망과딥러닝

PCA #10

호타리 2023. 9. 5. 09:15

<코드>

from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras import models, layers, optimizers
from tensorflow.keras.callbacks import EarlyStopping
import matplotlib.pyplot as plt
from tensorflow.keras.applications import VGG16

# set image generators
train_dir='./datasets/cats_and_dogs_small/train/'
test_dir='./datasets/cats_and_dogs_small/test/'
validation_dir='./datasets/cats_and_dogs_small/validation/'

train_datagen = ImageDataGenerator(rescale=1./255,
                    rotation_range=20, shear_range=0.1,
                    width_shift_range=0.1, height_shift_range=0.1,
                    zoom_range=0.1, horizontal_flip=True, fill_mode='nearest')
validation_datagen = ImageDataGenerator(rescale=1./255)
test_datagen = ImageDataGenerator(rescale=1./255)

train_generator = train_datagen.flow_from_directory(
        train_dir,
        target_size=(150, 150),
        batch_size=20,
        class_mode='binary')
test_generator = test_datagen.flow_from_directory(
        test_dir,
        target_size=(150, 150),
        batch_size=20,
        class_mode='binary')
validation_generator = validation_datagen.flow_from_directory(
        validation_dir,
        target_size=(150, 150),
        batch_size=20,
        class_mode='binary')

# model definition
input_shape = [150, 150, 3] # as a shape of image
def build_model():
    model=models.Sequential()
    conv_base = InceptionV3(weights='imagenet',
                      include_top=False,
                      input_shape=input_shape)
    conv_base.trainable=False
    model.add(conv_base)
    model.add(layers.Flatten())
    model.add(layers.Dense(256, activation='relu'))
    model.add(layers.Dense(1, activation='sigmoid'))
    # compile
    model.compile(optimizer=optimizers.RMSprop(lr=1e-4),
                  loss='binary_crossentropy', metrics=['accuracy'])
    return model

# main loop without cross-validation
import time
starttime=time.time();
num_epochs = 30
model = build_model()
history = model.fit_generator(train_generator,
                    epochs=num_epochs, steps_per_epoch=100,
                    validation_data=validation_generator, validation_steps=50)

# saving the model
model.save('cats_and_dogs_small_pretrained.h5')

# evaluation
train_loss, train_acc = model.evaluate_generator(train_generator)
test_loss, test_acc = model.evaluate(test_generator)
print('train_acc:', train_acc)
print('test_acc:', test_acc)
print("elapsed time (in sec): ", time.time()-starttime)

# visualization
def plot_acc(h, title="accuracy"):
    plt.plot(h.history['acc'])
    plt.plot(h.history ['val_acc'])
    plt.title(title)
    plt.ylabel('Accuracy')
    plt.xlabel('Epoch')
    plt.legend(['Training', 'Validation'], loc=0)

def plot_loss(h, title="loss"):
    plt.plot(h.history ['loss'])
    plt.plot(h.history ['val_loss'])
    plt.title(title)
    plt.ylabel('Loss')
    plt.xlabel('Epoch')
    plt.legend(['Training', 'Validation'], loc=0)

plot_loss(history)
plt.savefig('chapter5-2_basic.loss.png')
plt.clf()
plot_acc(history)
plt.savefig('chapter5-2_basic.accuracy.png')

 

Q1 

(Start with Chatper5_3.py and modify it.)

Now, we’re trying “transfer learning”. Chapter5_3.py uses “VGG16” as a pretrained model.

Let’s try to use “InceptionV3” instead of “VGG16”

Show your code.

 

 

Q2 

Run the code. Attach its loss graph. What is the test accuracy?

Is it better than the best result among the last week’s results?

 

Loss graph

Final test accuracy:

Accuracy의 크기가 InceptionV3를 모델로 사용하였을 때가 VGG16을 모델로 사용하였을 때보다 더 크게 나왔다. 따라서 정확도의 값만 보면 더 결과가 잘 나왔다고 생각할 수 있다. 하지만 loss 그래프를 보면 InceptionV3를 모델로 사용했을 때는 loss값이 점점 우상향하는 overfitting하는 결과를 볼 수 있고 VGG16을 모델로 사용하였을 때는 overfitting이 예방되는 결과를 볼 수 있다. 또한, 학습되는 시간의 길이도 InceptionV3 모델이 VGG16보다 대략 3배 정도 더 오래 걸리는 것을 알 수 있다. 이렇게 그래프의 퍼포먼스는 VGG16보다 좋지 않은 모습을 볼 수 있다. 따라서 accuracy의 값만 보고 InceptionV3를 모델로 사용하는 것이 더 좋다고는 할 수 없다.

 

Q3

Let’s do the 2-step fine-tuning.

Copy Chatper5_3.py into a new file.

Let’s load the saved weights of Q4’s learning, instead of build_model(). The code contains the statement for model saving.

model.save('cats_and_dogs_small_pretrained.h5’)

We will fine-tune only top 2 inception blocks. (we will freeze the first 249 layers, and unfreeze the rest.) We note that “conv_base=model.layers[0]”

Show your modified code.

 

 

Q4 

Set the number of epochs to 50.

 

Re-run the code, and attach its loss graph. What is the test accuracy?

Is it better than the last week’s results?

 

Loss graph

Final test accuracy:

Finetuning을 진행시킨 이 후의 결과를 비교해보면 accuracy의 크기는 VGG16을 사용했을 때보다 더 높게 나왔다. 하지만 퍼포먼스적인 부분을 비교해보면 InceptionV3를 모델로 사용하였을 때 loss 그래프에서 loss값이 아주 약간의 우상향 모습을 보여주긴 하지만 비교적 값의 크기가 차이가 많이 나지 않고 일관적인 모습을 보여주고 있다. , 학습시키는데 걸리는 시간이 VGG16에 비해 대략 3배정도 걸린 것을 알 수 있다. 따라서 accuracy의 값만 보면 finetuning을 한 InceptionV3 모델이 VGG16보다 훨씬 좋은 결과를 보여준다고 할 수 있지만 loss 그래프나 학습시간과 같은 퍼포먼스적인 부분도 같이 비교해보면 InceptionV3가 무조건 더 좋다고 할 수는 없다. , pretrained만 한 결과와 finetuning도 한 결과를 비교해보면 finetuning을 한 결과가 더 accuracy값이 크게 나오고 loss 그래프에서 overfitting의 모습도 pretrained한 결과에 비해 잘 안보인 것을 확인할 수 있다.

'대학교 4학년 1학기 > 인공신경망과딥러닝' 카테고리의 다른 글

PCA #12  (0) 2023.09.05
PCA #11  (0) 2023.09.05
PCA #9  (0) 2023.09.05
PCA #8  (0) 2023.09.05
PCA #7  (0) 2023.09.05