generated from dogeplusplus/python-template
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathscript.py
More file actions
142 lines (104 loc) · 3.6 KB
/
script.py
File metadata and controls
142 lines (104 loc) · 3.6 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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
import torchaudio
import torch
from torchaudio.datasets import SPEECHCOMMANDS
import os
import torch.optim as optim
import torch.nn.functional as F
from tqdm import tqdm
from models.m5 import M5
device = "cuda"
class SubsetSC(SPEECHCOMMANDS):
def __init__(self, subset: str = None):
super().__init__("./", download=True)
def load_list(filename):
filepath = os.path.join(self._path, filename)
with open(filepath) as fileobj:
return [os.path.join(self._path, line.strip())
for line in fileobj]
if subset == "validation":
self._walker = load_list("validation_list.txt")
elif subset == "testing":
self._walker = load_list("testing_list.txt")
elif subset == "training":
excludes = load_list("validation_list.txt") + \
load_list("testing_list.txt")
excludes = set(excludes)
self._walker = [w for w in self._walker if w not in excludes]
train_set = SubsetSC("training")
test_set = SubsetSC("testing")
waveform, sample_rate, label, speaker_id, utterance_number = train_set[0]
labels = sorted(list(set(datapoint[2] for datapoint in train_set)))
def label_to_index(w):
return torch.tensor(labels.index(w))
def index_to_label(i):
return labels[i]
def pad_sequence(batch):
batch = [item.t() for item in batch]
batch = torch.nn.utils.rnn.pad_sequence(
batch, batch_first=True, padding_value=0.)
return batch.permute(0, 2, 1)
def collate_fn(batch):
tensors, targets = [], []
for waveform, _, label, *_ in batch:
tensors += [waveform]
targets += [label_to_index(label)]
tensors = pad_sequence(tensors)
targets = torch.stack(targets)
return tensors, targets
batch_size = 4
num_workers = 1
pin_memory = True
train_loader = torch.utils.data.DataLoader(
train_set,
batch_size=batch_size,
shuffle=True,
collate_fn=collate_fn,
num_workers=num_workers,
pin_memory=pin_memory,
)
test_loader = torch.utils.data.DataLoader(
test_set,
batch_size=batch_size,
shuffle=False,
drop_last=False,
collate_fn=collate_fn,
num_workers=num_workers,
pin_memory=pin_memory,
)
def train(model, epoch, log_interval):
model.train()
for batch_idx, (data, target) in enumerate(train_loader):
data = data.to(device)
target = target.to(device)
# apply transform and model on whole batch directly on device
data = transform(data)
output = model(data)
# negative log-likelihood for a tensor of size (batch x 1 x n_output)
loss = F.nll_loss(output.squeeze(), target)
optimizer.zero_grad()
loss.backward()
optimizer.step()
# print training stats
# if batch_idx % log_interval == 0:
# update progress bar
# pbar.update(pbar_update)
pbar.set_postfix(dict(loss=loss.item()))
# record loss
losses.append(loss.item())
model = M5(num_classes=35)
model.to(device)
optimizer = optim.Adam(model.parameters(), lr=0.01, weight_decay=0.0001)
# reduce the learning after 20 epochs by a factor of 10
scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=20, gamma=0.1)
log_interval = 20
n_epoch = 2
# pbar_update = 1 / (len(train_loader) + len(test_loader))
losses = []
new_sample_rate = 8000
transform = torchaudio.transforms.Resample(
orig_freq=sample_rate, new_freq=new_sample_rate)
transform = transform.to(device)
with tqdm(total=n_epoch) as pbar:
for epoch in range(1, n_epoch + 1):
train(model, epoch, log_interval)
scheduler.step()