trainmodel | Cell 7 | Cell 9 | Search

The extract_features function extracts features from a list of images and returns a 4D numpy array containing the features. It assumes images are loaded as grayscale arrays and does not perform any preprocessing or feature extraction.

Cell 8

def extract_features(images):
    features = []
    for image in tqdm(images):
        img = load_img(image,grayscale =  True )
        img = np.array(img)
        features.append(img)
    features = np.array(features)
    features = features.reshape(len(features),48,48,1)
    return features
    

What the code could have been:

import numpy as np
from tqdm import tqdm
from tensorflow import keras

def extract_features(images):
    """
    Extracts features from a list of images and returns a 4D numpy array.
    
    Args:
    images (list): A list of image file paths or numpy arrays.
    
    Returns:
    numpy.ndarray: A 4D numpy array containing the extracted features.
    """
    
    # Load the required libraries and models
    from tensorflow.keras import layers as kl
    from tensorflow.keras import models as km
    from tensorflow.keras import preprocessing as kp
    
    # Load the pre-trained model (e.g. MobileNet)
    model = km.load_model('mobilenet.h5')
    
    # Initialize an empty list to store the features
    features = []
    
    # Iterate over each image and extract its features
    for image in tqdm(images):
        # Load and preprocess the image
        img = kp.image.load_img(image, grayscale=True)
        img = kp.image.array_to_img(img)
        img = kp.image.img_to_array(img)
        img = np.expand_dims(img, axis=0)
        
        # Extract the features using the pre-trained model
        feature = model.predict(img)
        
        # Append the feature to the list
        features.append(feature)
    
    # Convert the list to a 4D numpy array
    features = np.array(features)
    
    # Reshape the array to the required dimensions
    features = features.reshape(len(features), 48, 48, 1)
    
    return features

Function: extract_features

Purpose

Extracts features from a list of images.

Parameters

Returns

A 4D numpy array of shape (n_samples, 48, 48, 1) containing the features of the input images.

Notes