(self, setting, test=0)
| 143 | return self.model |
| 144 | |
| 145 | def test(self, setting, test=0): |
| 146 | test_data, test_loader = self._get_data(flag='TEST') |
| 147 | if test: |
| 148 | print('loading model') |
| 149 | self.model.load_state_dict(torch.load(os.path.join(self.args.checkpoints, setting, 'checkpoint.pth'))) |
| 150 | |
| 151 | preds = [] |
| 152 | trues = [] |
| 153 | folder_path = './test_results/' + setting + '/' |
| 154 | if not os.path.exists(folder_path): |
| 155 | os.makedirs(folder_path) |
| 156 | |
| 157 | self.model.eval() |
| 158 | with torch.no_grad(): |
| 159 | for i, (batch_x, label, padding_mask) in enumerate(test_loader): |
| 160 | batch_x = batch_x.float().to(self.device) |
| 161 | padding_mask = padding_mask.float().to(self.device) |
| 162 | label = label.to(self.device) |
| 163 | |
| 164 | outputs = self.model(batch_x, padding_mask, None, None) |
| 165 | |
| 166 | preds.append(outputs.detach()) |
| 167 | trues.append(label) |
| 168 | |
| 169 | preds = torch.cat(preds, 0) |
| 170 | trues = torch.cat(trues, 0) |
| 171 | print('test shape:', preds.shape, trues.shape) |
| 172 | |
| 173 | probs = torch.nn.functional.softmax(preds) # (total_samples, num_classes) est. prob. for each class and sample |
| 174 | predictions = torch.argmax(probs, dim=1).cpu().numpy() # (total_samples,) int class index for each sample |
| 175 | trues = trues.flatten().cpu().numpy() |
| 176 | accuracy = cal_accuracy(predictions, trues) |
| 177 | |
| 178 | # result save |
| 179 | folder_path = './results/' + setting + '/' |
| 180 | if not os.path.exists(folder_path): |
| 181 | os.makedirs(folder_path) |
| 182 | |
| 183 | print('accuracy:{}'.format(accuracy)) |
| 184 | file_name='result_classification.txt' |
| 185 | f = open(os.path.join(folder_path,file_name), 'a') |
| 186 | f.write(setting + " \n") |
| 187 | f.write('accuracy:{}'.format(accuracy)) |
| 188 | f.write('\n') |
| 189 | f.write('\n') |
| 190 | f.close() |
| 191 | return |
nothing calls this directly
no test coverage detected