import numpy as np
import pandas as pd
import os
from tensorflow.keras.applications.densenet import DenseNet121, preprocess_input
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Flatten, GlobalAveragePooling2D, Dropout
from keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.optimizers import Adam
import matplotlib.pyplot as plt

os.chdir(‘/content/drive/MyDrive/data/ani’)

train_dir = ‘/content/drive/MyDrive/data/ani/ani/train’
val_dir = ‘/content/drive/MyDrive/data/ani/ani/val’

data_generator_with_aug = ImageDataGenerator(preprocessing_function=preprocess_input,
                                              horizontal_flip = True,
                                              width_shift_range = 0.2,
                                              height_shift_range = 0.2)
data_generator_no_aug = ImageDataGenerator(preprocessing_function=preprocess_input)

image_size = 224

train_generator = data_generator_with_aug.flow_from_directory(
    directory = train_dir,
    target_size=(image_size, image size),
    batch_size=12,
    class_mode=‘categorical’)

validation_generator = data_generator_no_aug.flow_from_directory(
    directory = val_dir,
    target_size=(image_size, image size),
    class_mode=‘categorical’)

num_classes = 7

# 모델 정의 함수
def build_model(with_dropout=True):
    model = Sequential()
    model.add(DenseNet121(weights=‘imagenet’, include_top=False, input_shape=(224,224,3)))
    model.add(Flatten())
    model.add(Dense(1024, activation=‘relu’))
    if with_dropout:
        model.add(Dropout(0.5))  # 드롭아웃 적용 여부
    model.add(Dense(num_classes, activation=‘softmax’))
    model.compile(loss=‘categorical_crossentropy’, optimizer=Adam(0.0001), metrics=[‘accuracy’])
    return model

# 드롭아웃 없는 모델 훈련
model_no_dropout = build_model(with_dropout=False)
history_no_dropout = model_no_dropout.fit(
    train_generator,
    epochs=30,
    validation_data=validation_generator
)

# 드롭아웃 있는 모델 훈련
model_with_dropout = build_model(with_dropout=True)
history_with_dropout = model_with_dropout.fit(
    train_generator,
    epochs=30,
    validation_data=validation_generator
)

# 정확도와 손실률 그래프 그리기
plt.figure(figsize=(14, 6))
plt.subplot(1, 2, 1)
plt.plot(history_no_dropout.history[‘accuracy’], label=‘Train Accuracy w/o Dropout’)
plt.plot(history_no_dropout.history[‘val_accuracy’], label=‘Validation Accuracy w/o Dropout’)
plt.plot(history_with_dropout.history[‘accuracy’], label=‘Train Accuracy w/ Dropout’)
plt.plot(history_with_accuracy.history['val_accuracy], label=‘Validation Accuracy w/ Dropout’)
plt.title(‘Model Accuracy: With vs. Without Dropout’)
plt.xlabel(‘Epoch’)
plt.ylabel(‘Accuracy’)
plt.legend()

plt.subplot(1, 2, 2)
plt.plot(history_no_dropout.history[‘loss’], label=‘Train Loss w/o Dropout’)
plt.plot(history_no_dropout.history[‘val_loss’], label=‘Validation Loss w/o Dropout’)
plt.plot(history_with_dropout.history[‘loss’], label=‘Train Loss w/ Dropout’)
plt.plot(historyw_with_dropout.history[‘val_loss’], label=‘Validation Loss w/ Dropout’)
plt.title(‘Model Loss: With vs. Without Dropout’)
plt.xlabel(‘Epoch’)
plt.ylabel(‘Loss’)
plt.legend()

plt.show()
위의 코드에다가 K-폴드 교차 검증을 수행 하는 코드를 추가해줘