Advertisement
UF6

Step II: Transfer Learning

UF6
Aug 5th, 2024
158
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.09 KB | Source Code | 0 0
  1. from tensorflow.keras.applications import VGG16
  2. from tensorflow.keras.models import Model
  3. from tensorflow.keras.layers import Dense, Flatten
  4. from tensorflow.keras.preprocessing.image import ImageDataGenerator
  5.  
  6. # Load the pre-trained VGG16 model
  7. base_model = VGG16(weights='imagenet', include_top=False, input_shape=(150, 150, 3))
  8.  
  9. # Freeze the layers except the last 4 layers
  10. for layer in base_model.layers[:-4]:
  11.     layer.trainable = False
  12.  
  13. # Add custom layers on top
  14. x = base_model.output
  15. x = Flatten()(x)
  16. x = Dense(512, activation='relu')(x)
  17. predictions = Dense(1, activation='sigmoid')(x)
  18.  
  19. model = Model(inputs=base_model.input, outputs=predictions)
  20.  
  21. # Compile the model
  22. model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
  23.  
  24. # Prepare the augmented data generator
  25. train_datagen = ImageDataGenerator(rescale=1./255)
  26.  
  27. train_generator = train_datagen.flow_from_directory(
  28.     'path_to_augmented_images',
  29.     target_size=(150, 150),
  30.     batch_size=32,
  31.     class_mode='binary')
  32.  
  33. # Train the model
  34. model.fit(train_generator, epochs=5, steps_per_epoch=20)
  35.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement