How to resolve 'ImportError: `save_weights` requires h5py when saving in hdf5'

46 Views Asked by At

I have this code for training a facial emotion recognition model using tensorflow.
after i trained it and took hours the h5 file didnt saved so i added a time range of 10seconds just to test saving of h5 file.

The problem is that each time i get this message
ImportError: `save_weights` requires h5py when saving in hdf5, but h5py is not available. Try installing h5py package.

# Import required packages
import cv2
import time
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D, Dense, Dropout, Flatten
from keras.optimizers import Adam
from keras.preprocessing.image import ImageDataGenerator
from tqdm import tqdm

# Initialize image data generator with rescaling
train_data_gen = ImageDataGenerator(rescale=1./255)
validation_data_gen = ImageDataGenerator(rescale=1./255)

# Preprocess all test images
train_generator = train_data_gen.flow_from_directory(
        r'A:\OneDrive - The British University in Egypt\FER RP\Datasets\Fer2013\train',
        target_size=(48, 48),
        batch_size=64,
        color_mode="grayscale",
        class_mode='categorical')

# Preprocess all train images
validation_generator = validation_data_gen.flow_from_directory(
        r'A:\OneDrive - The British University in Egypt\FER RP\Datasets\Fer2013\test',
        target_size=(48, 48),
        batch_size=64,
        color_mode="grayscale",
        class_mode='categorical')

# Create model structure
emotion_model = Sequential()

emotion_model.add(Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=(48, 48, 1)))
emotion_model.add(Conv2D(64, kernel_size=(3, 3), activation='relu'))
emotion_model.add(MaxPooling2D(pool_size=(2, 2)))
emotion_model.add(Dropout(0.25))

emotion_model.add(Conv2D(128, kernel_size=(3, 3), activation='relu'))
emotion_model.add(MaxPooling2D(pool_size=(2, 2)))
emotion_model.add(Conv2D(128, kernel_size=(3, 3), activation='relu'))
emotion_model.add(MaxPooling2D(pool_size=(2, 2)))
emotion_model.add(Dropout(0.25))

emotion_model.add(Flatten())
emotion_model.add(Dense(1024, activation='relu'))
emotion_model.add(Dropout(0.5))
emotion_model.add(Dense(7, activation='softmax'))

cv2.ocl.setUseOpenCL(False)

emotion_model.compile(loss='categorical_crossentropy', optimizer=Adam(learning_rate=0.0001), metrics=['accuracy'])

# Train the neural network/model with tqdm progress bar
max_training_time = 10# in seconds (adjust as needed)
training_start_time = time.time()

for epoch in range(50):
    print(f"Epoch {epoch + 1}/{50}")
    
    for _ in tqdm(range(28709 // 64)):
        emotion_model.train_on_batch(*next(train_generator))
        
        # Check elapsed time and interrupt if it exceeds the maximum training time
        if time.time() - training_start_time > max_training_time:
            break
    
    emotion_model_info = emotion_model.evaluate_generator(
        validation_generator, steps=7178 // 64)
    print(f"Validation Accuracy: {emotion_model_info[1] * 100:.2f}%")
    
    # Save model structure in json file
    model_json = emotion_model.to_json()
    with open("emotion_model.json", "w") as json_file:
        json_file.write(model_json)

    # Save trained model weight in .h5 file
    emotion_model.save_weights('emotion_model.h5')

    # Reset training start time for the next epoch
    training_start_time = time.time()

The library h5py is installed using anaconda. I tried reinstalling the library multiple times but it didnt work.

0

There are 0 best solutions below