1. **Import necessary libraries:**
```python
import tensorflow as tf
from tensorflow.keras import layers
from tensorflow.keras.models import Sequential
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from kerastuner.tuners import RandomSearch
```
2. **Prepare the data:**
```python
train_datagen = ImageDataGenerator(rescale=1./255, validation_split=0.2)
train_generator = train_datagen.flow_from_directory(
'path_to_train_data',
target_size=(224, 224),
batch_size=32,
class_mode='categorical',
subset='training'
)
validation_generator = train_datagen.flow_from_directory(
'path_to_train_data',
target_size=(224, 224),
batch_size=32,
class_mode='categorical',
subset='validation'
)
```
3. **Load a pre-trained model for transfer learning:**
```python
base_model = tf.keras.applications.MobileNetV2(input_shape=(224, 224, 3),
include_top=False,
weights='imagenet')
```
4. **Freeze the pre-trained layers:**
```python
for layer in base_model.layers:
layer.trainable = False
```
5. **Define the model architecture and tune hyperparameters using Keras Tuner:**
```python
def build_model(hp):
model = Sequential([
base_model,
layers.GlobalAveragePooling2D(),
layers.Dense(hp.Int('units', min_value=32, max_value=512, step=32),
activation='relu'),
layers.Dropout(0.5),
layers.Dense(10, activation='softmax')
])
model.compile(optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy'])
return model
tuner = RandomSearch(
build_model,
objective='val_accuracy',
max_trials=5,
executions_per_trial=3,
directory='my_dir',
project_name='monkey_classification'
)
tuner.search(train_generator,
validation_data=validation_generator,
epochs=10)
```
6. **Get the best model and retrain with unfreezed layers:**
```python
best_model = tuner.get_best_models(num_models=1)[0]
for layer in best_model.layers[0].layers:
layer.trainable = True
best_model.compile(optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy'])
history = best_model.fit(train_generator,
validation_data=validation_generator,
epochs=10)
```
7. **Evaluate the model and make predictions:**
```python
test_datagen = ImageDataGenerator(rescale=1./255)
test_generator = test_datagen.flow_from_directory(
'path_to_test_data',
target_size=(224, 224),
batch_size=32,
class_mode='categorical'
)
loss, accuracy = best_model.evaluate(test_generator)
print("Test Accuracy:", accuracy)
```
0 Comments