-
Notifications
You must be signed in to change notification settings - Fork 6
/
infer.py
60 lines (43 loc) · 1.61 KB
/
infer.py
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
import torch
from torch import nn
from torch.utils.data import DataLoader
from torchvision import transforms
# assuming model and transform functions are already defined
# and 'MODEL_PATH' contains the path to the trained model
class PredictDataset(torch.utils.data.Dataset):
def __init__(self, audio_paths, transform=None):
self.audio_paths = audio_paths
self.transform = transform
def __len__(self):
return len(self.audio_paths)
def __getitem__(self, idx):
audio_path = self.audio_paths[idx]
audio_clip = load_audio_clip(audio_path)
if self.transform:
audio_clip = self.transform(audio_clip)
return audio_clip
def load_model(path):
model = CoAtNet() # should match the architecture of the trained model
model.load_state_dict(torch.load(path))
model.eval()
return model
def predict(audio_paths):
model = load_model(MODEL_PATH)
transform = transforms.Compose([
# add transforms that were used while training
])
dataset = PredictDataset(audio_paths, transform=transform)
data_loader = DataLoader(dataset, batch_size=1, shuffle=False)
predictions = []
for batch in data_loader:
batch = batch.cuda()
outputs = model(batch)
_, predicted = torch.max(outputs.data, 1) # change if multi-label classification
predictions.append(predicted.item())
return predictions
def main():
audio_paths = ["audio1.wav", "audio2.wav", "audio3.wav"] # replace with actual paths
predictions = predict(audio_paths)
print(predictions)
if __name__ == "__main__":
main()