-
Notifications
You must be signed in to change notification settings - Fork 0
/
Pytorch_Classifier.py
175 lines (133 loc) · 5.49 KB
/
Pytorch_Classifier.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
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
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
import sys
import numpy as np
import torch
import torch.nn as nn
from sklearn.metrics import accuracy_score
import AudioDataset
np.set_printoptions(threshold=sys.maxsize)
class Net(nn.Module):
def __init__(self):
self.device = torch.device("cuda")
self.iterator = AudioDataset.NoisyMusicDataset(noisy_music_folder="Processed")
super(Net, self).__init__()
self.layer1 = nn.Sequential(
nn.Conv1d(2, 32, kernel_size=3, stride=1, padding=0),
nn.Tanhshrink(),
nn.Conv1d(32, 64, kernel_size=3, stride=1, padding=0),
nn.MaxPool1d(kernel_size=2, stride=1),
nn.Dropout(0.25)
)
self.layer2 = nn.Sequential(
nn.Conv1d(64, 64, kernel_size=3, stride=1, padding=0),
nn.Tanhshrink(),
nn.Conv1d(64, 128, kernel_size=3, stride=1, padding=0),
nn.MaxPool1d(kernel_size=2, stride=1),
nn.Dropout(0.5)
)
self.layer3 = nn.Sequential(
nn.Conv1d(128, 128, kernel_size=3, stride=1, padding=0),
nn.Tanhshrink(),
nn.Conv1d(128, 512, kernel_size=3, stride=1, padding=0),
nn.MaxPool1d(kernel_size=2, stride=1),
nn.Dropout(0.5)
)
self.fc1 = nn.Sequential(
nn.Linear(512, 10),
nn.Tanhshrink(),
nn.Dropout(0.5),
nn.Linear(10, 2),
nn.Softmax()
)
def forward(self, x):
x = self.layer1(x)
x = self.layer2(x)
x = self.layer3(x)
x = x.view(-1, x.size(1))
x = self.fc1(x)
return x
def train_classifier(self, optimiser, criterion, device):
self.optimiser = optimiser
self.criterion = criterion
self.device = device
epochs = 15
size_batch = 15
batch = 9 * 1000 // size_batch
print("Training classifier with {} epochs, {} batches of size {}".format(epochs, batch, size_batch))
self.train()
for epoch in range(epochs):
self.iterator = AudioDataset.NoisyMusicDataset()
for num_batch in range(batch):
fake = np.empty((size_batch, 2, 57330))
real = np.empty((size_batch, 2, 57330))
for i in range(size_batch):
noise, music, noise_file, music_file = next(self.iterator)
fake[i] = np.vstack(([noise], [music]))
real[i] = np.vstack(([noise], [noise]))
self.zero_grad()
# Train real
self.optimiser.zero_grad()
input_network_tensor = torch.as_tensor(real, dtype=torch.float32).to(self.device)
output = self(input_network_tensor)
labels = torch.ones(output.size())
labels_tensor = torch.as_tensor(labels, dtype=torch.float32).to(self.device)
loss_real = self.criterion(output, labels_tensor)
loss_real.backward()
self.optimiser.step()
self.zero_grad()
# Train fake
# self.optimiser.zero_grad()
#
# input_network_tensor = torch.as_tensor(fake, dtype=torch.float32).to(self.device)
#
# output = self(input_network_tensor)
#
# labels = torch.zeros(output.size())
# labels_tensor = torch.as_tensor(labels, dtype=torch.float32).to(self.device)
#
# loss_fake = self.criterion(output, labels_tensor)
# loss_fake.backward()
# self.optimiser.step()
print("Epoch {}, batch {}, Classifier loss: {}".format(epoch + 1, num_batch + 1, loss_real))
print()
def testClassifier(self):
# test
music_accuracy = []
noise_accuracy = []
size_batch = 2
self.iterator = AudioDataset.NoisyMusicDataset(noisy_music_folder="Processed")
fake = np.empty((size_batch, 2, 57330))
real = np.empty((size_batch, 2, 57330))
for i in range(size_batch):
music, noise = next(self.iterator)
fake[i] = np.vstack(([noise], [music]))
real[i] = np.vstack(([noise], [noise]))
# # Test music files:
# labels = []
# input_network = torch.as_tensor(fake, dtype=torch.float32).to(self.device)
#
# with torch.no_grad():
# output = self(input_network)
#
# labels = torch.zeros(output.size())
#
# softmax = torch.exp(output).cpu()
# prob = list(softmax.numpy())
# predictions = np.argmax(prob, axis=1)
#
# print("Music predictions: ", predictions)
# # accuracy on training set
# accuracy = accuracy_score(np.argmax(labels, axis=1), predictions)
# music_accuracy.append(accuracy)
# Test noise files
input_network = torch.as_tensor(real, dtype=torch.float32).to(self.device)
with torch.no_grad():
output = self(input_network)
labels = torch.ones(output.size()[0])
softmax = output.detach()
prob = list(softmax.cpu().numpy())
predictions = np.argmax(prob, axis=1)
# accuracy on training set
accuracy = accuracy_score(labels.data, predictions)
noise_accuracy.append(accuracy)
print("Average accuracy of noise: {}".format(np.average(noise_accuracy)))
# print("Average accuracy of music: {}".format(np.average(music_accuracy)))