Untitled
unknown
plain_text
a year ago
1.7 kB
7
Indexable
import tensorflow as tf
from tensorflow.keras.applications import ResNet50
from tensorflow.keras.layers import Dense, GlobalAveragePooling2D
from tensorflow.keras.models import Model
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.callbacks import ReduceLROnPlateau
# Load pre-trained ResNet50 model
base_model = ResNet50(weights='imagenet', include_top=False, input_shape=(img_height, img_width, 3))
# Freeze all layers except the last 5
for layer in base_model.layers[:-5]:
layer.trainable = False
# Add custom layers
x = base_model.output
x = GlobalAveragePooling2D()(x)
x = Dense(1024, activation='relu')(x)
predictions = Dense(len(lb.classes_), activation='softmax')(x)
# Create the model
model = Model(inputs=base_model.input, outputs=predictions)
# Compile the model
model.compile(optimizer=Adam(learning_rate=1e-4), loss='categorical_crossentropy', metrics=['accuracy'])
# Train the model
history = model.fit(
train_generator,
epochs=8,
validation_data=val_generator,
callbacks=[ReduceLROnPlateau(monitor='val_loss', factor=0.2, patience=2, min_lr=1e-6)]
)
for layer in model.layers:
layer.trainable = True
model.compile(optimizer=Adam(learning_rate=1e-4), loss='categorical_crossentropy', metrics=['accuracy'])
history = model.fit(
train_generator,
epochs=3,
validation_data=val_generator,
callbacks=[ReduceLROnPlateau(monitor='val_loss', factor=0.2, patience=2, min_lr=1e-6)]
)
# Evaluate the model
loss, accuracy = model.evaluate(val_generator)
print(f'Test loss: {loss:.3f}')
print(f'Test accuracy: {accuracy:.3f}')
# Save the model
model.save('resnet50_fine_tuned.h5')
Editor is loading...
Leave a Comment