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
| def train(net,train_iter,num_epochs): net.train() for epoch in range(num_epochs): train_l_sum,train_acc_sum,n=0.0,0.0,0
for X, y in train_iter('validation'): X = X.to(device) y = y.to(device) y_hat = net(X).to(device) l = loss(y_hat, y).sum().to(device) optimizer.zero_grad() l.backward() optimizer.step() train_l_sum += l.item() n += y.shape[0] print('epoch %d, loss %.4f' % (epoch + 1, train_l_sum / n))
def eval(net, test_iter): net.eval() p_true, p_hat, p_TP=0, 0, 0
for X, y in test_iter('test'): X = X.to(device) y = y.to(device) y_hat = net(X).to(device) idy, idy_h = [], [] for i in range(vocab_size): if y[0][i]==1: idy.append(i) if y_hat[0][i] > conf_prob: idy_h.append(i) p_true += len(idy) p_hat += len(idy_h) for t in idy_h: if t in idy: p_TP +=1 Recall = p_TP / p_true Precision = p_TP / p_hat f1 = 2*(Recall*Precision)/(Recall+Precision) print('Recall %.4f, Precision %.4f, F1 %.4f' % (Recall, Precision, f1))
train(net, data_iter, num_epochs) eval(net, data_iter)
|