Header Ads Widget

How to classify monkeys images using convolutional neural network , Keras tuner hyper parameters , and transfer learning ?

 Certainly! Here's a step-by-step guide on how to classify monkey images using a Convolutional Neural Network (CNN) with Keras Tuner for hyperparameter tuning and transfer learning using a pre-trained model:


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)

```


This code will help you build a CNN for classifying monkey images using transfer learning with a pre-trained MobileNetV2 model, Keras Tuner for hyperparameter tuning, and evaluate its performance. Make sure to replace `'path_to_train_data'`, `'path_to_test_data'` with the actual paths to your training and testing data directories.

Post a Comment

0 Comments