1import torch
2from sklearn.datasets import make_circles
3from sklearn.model_selection import train_test_split
4import matplotlib.pyplot as plt
5
6
7print('data')
8n_samples = 1000
9print(f'n_samples = {n_samples}')
10
11X, y = make_circles(n_samples,
12 noise=0.03,
13 random_state=42)
14
15
16X = torch.from_numpy(X).type(torch.float)
17y = torch.from_numpy(y).type(torch.float).reshape(-1,1)
18
19
20print('Data: train and test sets')
21X_train, X_test, y_train, y_test = train_test_split(X,
22 y,
23 test_size=0.2,
24 random_state=42)
25print(f'n_train = {len(X_train)}')
26print(f'n_test = {len(X_test)}')
27plt.close()
28plt.scatter(X_train[:,0], X_train[:,1], c=y_train,
29 marker='o', cmap=plt.cm.coolwarm, alpha=0.3)
30plt.scatter(X_test[:,0], X_test[:,1], c=y_test,
31 marker='*', cmap=plt.cm.coolwarm)
32plt.show()
33
34
35model = torch.nn.Sequential(
36 torch.nn.Linear(2, 10),
37 torch.nn.ELU(),
38 torch.nn.Linear(10, 1),
39 torch.nn.Sigmoid()
40 )
41
42
43loss_fun = torch.nn.BCELoss()
44
45
46optimizer = torch.optim.SGD(model.parameters(),
47 lr = 1e-1)
48
49
50def accuracy_fun(y_pred, y_exp):
51 correct = torch.eq(y_pred, y_exp).sum().item()
52 acc = correct/len(y_exp) * 100
53 return acc
54
55
56n_epochs = 10000
57n_out = 100
58
59for epoch in range(n_epochs):
60 model.train()
61
62 y_pred = model(X_train)
63
64 loss = loss_fun(y_pred, y_train)
65
66 acc = accuracy_fun(torch.round(y_pred),
67 y_train)
68
69 optimizer.zero_grad()
70 loss.backward()
71 optimizer.step()
72
73 model.eval()
74
75
76 if ((epoch+1) % n_out == 0):
77 with torch.inference_mode():
78 y_pred_test = model(X_test)
79 loss_test = loss_fun(y_pred_test,
80 y_test)
81 acc_test = accuracy_fun(torch.round(y_pred_test),
82 y_test)
83
84 print(f'{epoch+1}: loss = {loss:.5e}, accuracy = {acc:.2f}%')
85 print(f'\ttest: loss = {loss:.5e}, accuracy = {acc:.2f}%\n')