|
@@ -1,5 +1,3 @@
|
|
|
-# pytorch_trainer.py
|
|
|
|
|
-
|
|
|
|
|
import torch
|
|
import torch
|
|
|
import torch.nn as nn
|
|
import torch.nn as nn
|
|
|
import torch.optim as optim
|
|
import torch.optim as optim
|
|
@@ -9,7 +7,6 @@ import numpy as np
|
|
|
from sklearn.model_selection import train_test_split
|
|
from sklearn.model_selection import train_test_split
|
|
|
from utils.training_interface import TrainerInterface
|
|
from utils.training_interface import TrainerInterface
|
|
|
from utils.file_utils import list_files_in_directory
|
|
from utils.file_utils import list_files_in_directory
|
|
|
-import multiprocessing as mp
|
|
|
|
|
import time
|
|
import time
|
|
|
import json
|
|
import json
|
|
|
|
|
|
|
@@ -38,7 +35,7 @@ class PyTorchTrainer(TrainerInterface):
|
|
|
self.sample_directory = None
|
|
self.sample_directory = None
|
|
|
self.background_directory = None
|
|
self.background_directory = None
|
|
|
self.dropout_rate = 0.5
|
|
self.dropout_rate = 0.5
|
|
|
- self.epochs = 10
|
|
|
|
|
|
|
+ self.epochs = 3000
|
|
|
self.batch_size = 32
|
|
self.batch_size = 32
|
|
|
self.learning_rate = learning_rate
|
|
self.learning_rate = learning_rate
|
|
|
self.model = None
|
|
self.model = None
|
|
@@ -49,10 +46,6 @@ class PyTorchTrainer(TrainerInterface):
|
|
|
self.training_status = "Not started"
|
|
self.training_status = "Not started"
|
|
|
self.train_loader = None
|
|
self.train_loader = None
|
|
|
self.val_loader = None
|
|
self.val_loader = None
|
|
|
- self.status_ref = None
|
|
|
|
|
- self.progress_ref = None
|
|
|
|
|
- self.loss_ref = None
|
|
|
|
|
- self.accuracy_ref = None
|
|
|
|
|
|
|
|
|
|
def set_model_path(self, model_path):
|
|
def set_model_path(self, model_path):
|
|
|
self.model_path = model_path
|
|
self.model_path = model_path
|
|
@@ -106,7 +99,7 @@ class PyTorchTrainer(TrainerInterface):
|
|
|
self.train_loader = torch.utils.data.DataLoader(CustomDataset(X_train, y_train), batch_size=self.batch_size, shuffle=True)
|
|
self.train_loader = torch.utils.data.DataLoader(CustomDataset(X_train, y_train), batch_size=self.batch_size, shuffle=True)
|
|
|
self.val_loader = torch.utils.data.DataLoader(CustomDataset(X_val, y_val), batch_size=self.batch_size, shuffle=False)
|
|
self.val_loader = torch.utils.data.DataLoader(CustomDataset(X_val, y_val), batch_size=self.batch_size, shuffle=False)
|
|
|
|
|
|
|
|
- def preprocess_training_data(self, update_progress_callback):
|
|
|
|
|
|
|
+ def preprocess_training_data(self):
|
|
|
import librosa
|
|
import librosa
|
|
|
data_path_dict = {}
|
|
data_path_dict = {}
|
|
|
data_path_dict[0] = list_files_in_directory(self.background_directory, extension='.wav')
|
|
data_path_dict[0] = list_files_in_directory(self.background_directory, extension='.wav')
|
|
@@ -125,7 +118,8 @@ class PyTorchTrainer(TrainerInterface):
|
|
|
mfcc_processed = np.mean(mfcc.T, axis=0)
|
|
mfcc_processed = np.mean(mfcc.T, axis=0)
|
|
|
all_data.append([mfcc_processed, class_label])
|
|
all_data.append([mfcc_processed, class_label])
|
|
|
processed_files += 1
|
|
processed_files += 1
|
|
|
- update_progress_callback(processed_files / total_files * 100)
|
|
|
|
|
|
|
+ global current_progress
|
|
|
|
|
+ current_progress = (processed_files / total_files) * 100
|
|
|
except Exception as e:
|
|
except Exception as e:
|
|
|
print(f"Exception: {str(e)}")
|
|
print(f"Exception: {str(e)}")
|
|
|
|
|
|
|
@@ -133,23 +127,32 @@ class PyTorchTrainer(TrainerInterface):
|
|
|
df.to_pickle(self.model_path + "audio_data.csv")
|
|
df.to_pickle(self.model_path + "audio_data.csv")
|
|
|
|
|
|
|
|
def load_model(self):
|
|
def load_model(self):
|
|
|
|
|
+ num_classes = len(self.training_directories) + 1 # Assuming one extra for background or unknown
|
|
|
model = nn.Sequential(
|
|
model = nn.Sequential(
|
|
|
nn.Linear(40, 128),
|
|
nn.Linear(40, 128),
|
|
|
nn.ReLU(),
|
|
nn.ReLU(),
|
|
|
nn.Dropout(self.dropout_rate),
|
|
nn.Dropout(self.dropout_rate),
|
|
|
- nn.Linear(128, len(self.training_directories) + 1),
|
|
|
|
|
|
|
+ nn.Linear(128, num_classes), # Update output layer to match num_classes
|
|
|
nn.Softmax(dim=1)
|
|
nn.Softmax(dim=1)
|
|
|
)
|
|
)
|
|
|
- if os.path.exists(self.model_path + "hotword_model.pth"):
|
|
|
|
|
- model.load_state_dict(torch.load(self.model_path + "hotword_model.pth"))
|
|
|
|
|
|
|
+ model_path = self.model_path + "hotword_model.pth"
|
|
|
|
|
+ if os.path.exists(model_path):
|
|
|
|
|
+ state_dict = torch.load(model_path)
|
|
|
|
|
+ try:
|
|
|
|
|
+ model.load_state_dict(state_dict)
|
|
|
|
|
+ except RuntimeError as e:
|
|
|
|
|
+ print(f"Error loading model state dict: {e}")
|
|
|
|
|
+ # Handle dimension mismatch by reinitializing the last layer
|
|
|
|
|
+ model = nn.Sequential(
|
|
|
|
|
+ nn.Linear(40, 128),
|
|
|
|
|
+ nn.ReLU(),
|
|
|
|
|
+ nn.Dropout(self.dropout_rate),
|
|
|
|
|
+ nn.Linear(128, num_classes),
|
|
|
|
|
+ nn.Softmax(dim=1)
|
|
|
|
|
+ )
|
|
|
|
|
+ print("Reinitialized the final layer to match the number of classes.")
|
|
|
return model
|
|
return model
|
|
|
|
|
|
|
|
- def set_status_references(self, status_ref, progress_ref, loss_ref, accuracy_ref):
|
|
|
|
|
- self.status_ref = status_ref
|
|
|
|
|
- self.progress_ref = progress_ref
|
|
|
|
|
- self.loss_ref = loss_ref
|
|
|
|
|
- self.accuracy_ref = accuracy_ref
|
|
|
|
|
-
|
|
|
|
|
def start(self):
|
|
def start(self):
|
|
|
self.training_status = "Training"
|
|
self.training_status = "Training"
|
|
|
self.stop_training = False
|
|
self.stop_training = False
|
|
@@ -176,50 +179,64 @@ class PyTorchTrainer(TrainerInterface):
|
|
|
self.stop_training = True
|
|
self.stop_training = True
|
|
|
|
|
|
|
|
def run_training(self):
|
|
def run_training(self):
|
|
|
- manager = mp.Manager()
|
|
|
|
|
- progress = manager.list()
|
|
|
|
|
- loss = manager.list()
|
|
|
|
|
- accuracy = manager.list()
|
|
|
|
|
- self.set_status_references(None, progress, loss, accuracy)
|
|
|
|
|
-
|
|
|
|
|
- self.preprocess_training_data(lambda p: self.update_progress(p, progress))
|
|
|
|
|
|
|
+ global current_progress, current_loss, current_accuracy, total_epochs, total_batches
|
|
|
|
|
+ self.preprocess_training_data()
|
|
|
|
|
+ start_time = time.time()
|
|
|
df = pd.read_pickle(self.model_path + "audio_data.csv")
|
|
df = pd.read_pickle(self.model_path + "audio_data.csv")
|
|
|
X = df["feature"].values
|
|
X = df["feature"].values
|
|
|
X = np.concatenate(X, axis=0).reshape(len(X), 40)
|
|
X = np.concatenate(X, axis=0).reshape(len(X), 40)
|
|
|
y = np.array(df["class_label"].tolist())
|
|
y = np.array(df["class_label"].tolist())
|
|
|
self.set_training_data(X, y)
|
|
self.set_training_data(X, y)
|
|
|
|
|
|
|
|
|
|
+ total_batches = len(self.train_loader)
|
|
|
|
|
+ total_epochs = self.epochs
|
|
|
|
|
+
|
|
|
|
|
+ training_info = {
|
|
|
|
|
+ "trainer_script": "tensorflow_trainer",
|
|
|
|
|
+ "training_time": 0,
|
|
|
|
|
+ "model_size": 0,
|
|
|
|
|
+ "epochs": self.epochs,
|
|
|
|
|
+ "dropout_rate": self.dropout_rate,
|
|
|
|
|
+ "batch_size": self.batch_size,
|
|
|
|
|
+ "total_training_data": len(X),
|
|
|
|
|
+ "training_directories": self.training_directories,
|
|
|
|
|
+ "accuracy": [],
|
|
|
|
|
+ "loss": [],
|
|
|
|
|
+ "test_accuracy": 0
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
for epoch in range(self.current_epoch, self.epochs):
|
|
for epoch in range(self.current_epoch, self.epochs):
|
|
|
if self.stop_training:
|
|
if self.stop_training:
|
|
|
break
|
|
break
|
|
|
self.current_epoch = epoch
|
|
self.current_epoch = epoch
|
|
|
self.model.train()
|
|
self.model.train()
|
|
|
- for batch_X, batch_y in self.train_loader:
|
|
|
|
|
|
|
+ for batch_idx, (batch_X, batch_y) in enumerate(self.train_loader):
|
|
|
|
|
+ global current_loss, current_accuracy
|
|
|
self.optimizer.zero_grad()
|
|
self.optimizer.zero_grad()
|
|
|
outputs = self.model(batch_X)
|
|
outputs = self.model(batch_X)
|
|
|
- loss_value = self.criterion(outputs, batch_y.long())
|
|
|
|
|
- loss_value.backward()
|
|
|
|
|
|
|
+ loss = self.criterion(outputs, batch_y.long()) # Convert labels to Long type
|
|
|
|
|
+ loss.backward()
|
|
|
self.optimizer.step()
|
|
self.optimizer.step()
|
|
|
- self.update_training_status(loss_value.item(), (outputs.argmax(dim=1) == batch_y).float().mean().item(), progress, loss, accuracy)
|
|
|
|
|
|
|
+ # Update global progress variables
|
|
|
|
|
+ current_loss = loss.item()
|
|
|
|
|
+ current_accuracy = (outputs.argmax(dim=1) == batch_y).float().mean().item()
|
|
|
|
|
+ current_progress = (epoch * len(self.train_loader) + batch_idx + 1) / (self.epochs * len(self.train_loader)) * 100
|
|
|
|
|
+ training_info["accuracy"].append(current_accuracy)
|
|
|
|
|
+ training_info["loss"].append(current_loss)
|
|
|
|
|
|
|
|
- print(f"Epoch {epoch + 1}/{self.epochs}, Loss: {loss[-1]}, Accuracy: {accuracy[-1]}")
|
|
|
|
|
|
|
+ print(f"Epoch {epoch + 1}/{self.epochs}, Loss: {current_loss}, Accuracy: {current_accuracy}")
|
|
|
|
|
|
|
|
|
|
+ epoch_time = time.time() - start_time
|
|
|
|
|
+ training_info["training_time"] = epoch_time
|
|
|
|
|
+
|
|
|
if not self.stop_training:
|
|
if not self.stop_training:
|
|
|
torch.save(self.model.state_dict(), self.model_path + "hotword_model.pth")
|
|
torch.save(self.model.state_dict(), self.model_path + "hotword_model.pth")
|
|
|
self.evaluate_model(X, y)
|
|
self.evaluate_model(X, y)
|
|
|
|
|
+ self.save_training_info(training_info)
|
|
|
self.training_status = "Finished"
|
|
self.training_status = "Finished"
|
|
|
else:
|
|
else:
|
|
|
self.training_status = "Paused"
|
|
self.training_status = "Paused"
|
|
|
|
|
|
|
|
- def update_progress(self, value, progress_ref):
|
|
|
|
|
- progress_ref.append(value)
|
|
|
|
|
-
|
|
|
|
|
- def update_training_status(self, loss_value, accuracy_value, progress_ref, loss_ref, accuracy_ref):
|
|
|
|
|
- loss_ref.append(loss_value)
|
|
|
|
|
- accuracy_ref.append(accuracy_value)
|
|
|
|
|
- current_progress = (self.current_epoch + 1) / self.epochs * 100
|
|
|
|
|
- progress_ref.append(current_progress)
|
|
|
|
|
-
|
|
|
|
|
def evaluate_model(self, X_test, y_test):
|
|
def evaluate_model(self, X_test, y_test):
|
|
|
self.model.eval()
|
|
self.model.eval()
|
|
|
with torch.no_grad():
|
|
with torch.no_grad():
|
|
@@ -229,12 +246,16 @@ class PyTorchTrainer(TrainerInterface):
|
|
|
_, predicted = torch.max(outputs, 1)
|
|
_, predicted = torch.max(outputs, 1)
|
|
|
accuracy = (predicted == y_test_tensor).sum().item() / len(y_test_tensor)
|
|
accuracy = (predicted == y_test_tensor).sum().item() / len(y_test_tensor)
|
|
|
print(f"Test Accuracy: {accuracy * 100:.2f}%")
|
|
print(f"Test Accuracy: {accuracy * 100:.2f}%")
|
|
|
|
|
+
|
|
|
|
|
+ def save_training_info(self, info):
|
|
|
|
|
+ with open(self.model_path + "info_pytorch_trainer.json", "w") as f:
|
|
|
|
|
+ json.dump(info, f)
|
|
|
|
|
|
|
|
def get_training_info(self):
|
|
def get_training_info(self):
|
|
|
return {
|
|
return {
|
|
|
"status": self.training_status,
|
|
"status": self.training_status,
|
|
|
"current_epoch": self.current_epoch,
|
|
"current_epoch": self.current_epoch,
|
|
|
"total_epochs": self.epochs,
|
|
"total_epochs": self.epochs,
|
|
|
- "loss": self.loss_ref,
|
|
|
|
|
- "accuracy": self.accuracy_ref
|
|
|
|
|
|
|
+ "loss": current_loss,
|
|
|
|
|
+ "accuracy": current_accuracy
|
|
|
}
|
|
}
|