forked from huwprosser/clap-detection
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtrain.py
More file actions
111 lines (82 loc) · 3.14 KB
/
Copy pathtrain.py
File metadata and controls
111 lines (82 loc) · 3.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
import torch
import torch.nn as nn
from dataloader import AudioDataset
from model import AudioClassifier
from torch.utils.data import DataLoader
from torch.utils.data import random_split
# Check if a GPU is available
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# reproducability
torch.manual_seed(42)
# Define the directories
noise_dir = "data/noise2"
clap_dir = "data/claps"
# Create the dataset
dataset = AudioDataset(noise_dir, clap_dir)
# Define the size of the splits
train_size = int(0.95 * len(dataset))
val_size = len(dataset) - train_size
# Split the dataset
train_dataset, val_dataset = random_split(dataset, [train_size, val_size])
# Create the dataloaders
train_dataloader = DataLoader(train_dataset, batch_size=32, shuffle=True)
val_dataloader = DataLoader(val_dataset, batch_size=32, shuffle=False)
# Define the model
model = AudioClassifier()
# Move the model to the GPU
model.to(device)
# Define the loss function and optimizer
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.AdamW(model.parameters(), lr=0.00001, weight_decay=0.02)
num_epochs = 5
# Train the model
for epoch in range(num_epochs):
model.train()
train_losses = []
correct_train_predictions = 0
total_train_predictions = 0
for i, (inputs, labels) in enumerate(train_dataloader):
# Move the data to the GPU
inputs = inputs.to(device)
labels = labels.to(device)
optimizer.zero_grad()
outputs = model(inputs)
# Calculate loss
loss = criterion(outputs, labels)
train_losses.append(loss.item())
# Calculate accuracy
_, predicted = torch.max(outputs.data, 1)
total_train_predictions += labels.size(0)
correct_train_predictions += (predicted == labels).sum().item()
loss.backward()
optimizer.step()
train_loss = sum(train_losses) / len(train_losses)
train_accuracy = correct_train_predictions / total_train_predictions
print(
f"Epoch {epoch + 1}: Train loss: {train_loss}, Train Accuracy: {train_accuracy}"
)
model.eval()
# Validation Phase
with torch.no_grad():
val_losses = []
correct_predictions = 0
total_predictions = 0
for i, (inputs, labels) in enumerate(val_dataloader):
# Move the data to the GPU
inputs = inputs.to(device)
labels = labels.to(device)
outputs = model(inputs)
# Calculate loss
loss = criterion(outputs, labels)
val_losses.append(loss.item())
# Calculate accuracy
_, predicted = torch.max(outputs.data, 1)
total_predictions += labels.size(0)
correct_predictions += (predicted == labels).sum().item()
val_loss = sum(val_losses) / len(val_losses)
val_accuracy = correct_predictions / total_predictions
print(
f"Epoch {epoch+1}/{num_epochs}, Validation Loss: {val_loss}, Validation Accuracy: {val_accuracy}"
)
# Save the model
torch.save(model.state_dict(), "audio_classifier.pth")