Skip to content

Instantly share code, notes, and snippets.

@idontcalculate
Created May 17, 2024 19:15
Show Gist options
  • Save idontcalculate/dbf72935de3fc20af3e5bdc4a57949bc to your computer and use it in GitHub Desktop.
Save idontcalculate/dbf72935de3fc20af3e5bdc4a57949bc to your computer and use it in GitHub Desktop.
example of transfer learning with tf hub models
from tensorflow.keras.applications import VGG16
from tensorflow.keras import layers, models
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.losses import BinaryCrossentropy
from tensorflow.keras.metrics import BinaryAccuracy
# Load the pre-trained VGG16 model without the top layer
pretrained = VGG16(input_shape=(256, 256, 3), include_top=False, weights="imagenet")
pretrained.trainable = False
# Build the new model architecture
model = models.Sequential([
pretrained,
layers.Dropout(0.4),
layers.Flatten(),
layers.Dense(1024, activation='relu'),
layers.Dropout(0.3),
layers.Dense(1, activation='sigmoid')
])
# Compile the model
model.compile(optimizer=Adam(learning_rate=0.001),
loss=BinaryCrossentropy(),
metrics=[BinaryAccuracy()])
from tensorflow.keras.callbacks import EarlyStopping
# Set up early stopping
callback = EarlyStopping(monitor='val_loss', patience=3)
# Train the model
history = model.fit(train_flow, epochs=20, validation_data=valid_flow, verbose=1, callbacks=[callback])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment