HaryaniAnjali's picture
Create emotion_model.py
6c8529b verified
raw
history blame
1.84 kB
import tensorflow as tf
import torch
import numpy as np
import os
# Load the Keras model
keras_model = tf.keras.models.load_model('wav2vec_model.h5')
# Create a PyTorch model with the same architecture
class EmotionClassifier(torch.nn.Module):
def __init__(self, input_shape, num_classes):
super().__init__()
# Adjust this architecture to match your Keras model
self.flatten = torch.nn.Flatten()
self.layers = torch.nn.Sequential(
torch.nn.Linear(input_shape, 128),
torch.nn.ReLU(),
torch.nn.Dropout(0.3),
torch.nn.Linear(128, 64),
torch.nn.ReLU(),
torch.nn.Dropout(0.3),
torch.nn.Linear(64, num_classes)
)
def forward(self, x):
x = self.flatten(x)
return self.layers(x)
# Create PyTorch model
# Adjust these parameters based on your Keras model
input_shape = 13 * 128 # n_mfcc * max_length
num_classes = 7 # Number of emotions
pytorch_model = EmotionClassifier(input_shape, num_classes)
# Copy weights from Keras to PyTorch
# This would need to be adjusted based on your exact architecture
for i, layer in enumerate(keras_model.layers):
if isinstance(layer, tf.keras.layers.Dense):
# Get Keras weights and bias
keras_weights = layer.get_weights()[0]
keras_bias = layer.get_weights()[1]
# Find the corresponding PyTorch layer
# This is simplified; you'd need to match layers properly
pytorch_layer = pytorch_model.layers[i * 2]
# Copy weights and bias
pytorch_layer.weight.data = torch.tensor(keras_weights.T, dtype=torch.float32)
pytorch_layer.bias.data = torch.tensor(keras_bias, dtype=torch.float32)
# Save the PyTorch model
torch.save(pytorch_model.state_dict(), 'emotion_model.pt')