-
Notifications
You must be signed in to change notification settings - Fork 0
/
creating_custom_dataset.py
129 lines (104 loc) · 3.15 KB
/
creating_custom_dataset.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
"""
Trying to create a non default dataset with PyTorch.
Problem : try to classify if sum of 2 numbers numbers are odd or even
(just training to create a dataset)
"""
import numpy as np
np.random.seed(1995)
import matplotlib.pyplot as plt
import torch
import torch as T
import torch.nn as nn
from torch.nn.modules import *
from tqdm import tqdm, trange
from torch.utils.data import Dataset
from torchvision import datasets, transforms
T.set_default_tensor_type('torch.FloatTensor')
class OddEvenNumbersDataset(Dataset):
def __init__(self, train=True, dataset_size=2048):
#on cree le dataset
if train:
self.x = T.tensor(np.array([
[np.random.randint(0, 1000), np.random.randint(0, 1000)]
for i in range(dataset_size)
])).float()
self.y = T.tensor(self.x.sum(1) % 2).float()
else:
self.x = T.tensor(np.array([
[np.random.randint(0, 1000), np.random.randint(0, 1000)]
for i in range(dataset_size)
])).float()
self.y = T.tensor(self.x.sum(1) % 2).float()
def __len__(self):
return len(self.y)
def __getitem__(self, item):
return self.x[item], self.y[item]
class OENet(Module):
def __init__(self):
super(OENet, self).__init__()
self.clf = Sequential(
nn.Linear(2, 20),
nn.ReLU(),
nn.Linear(20, 20),
nn.ReLU(),
nn.Linear(20, 20),
nn.ReLU(),
nn.Linear(20, 20),
nn.ReLU(),
nn.Linear(20, 1),
nn.Sigmoid()
)
def forward(self, x):
return self.clf(x)
batch_size = 16
my_model = OENet()
optimizer = torch.optim.Adam(my_model.parameters())
loss_function = BCELoss()
train_loader = T.utils.data.DataLoader(
OddEvenNumbersDataset(train=True),
batch_size=batch_size,
shuffle=True
)
test_loader = T.utils.data.DataLoader(
OddEvenNumbersDataset(train=False),
batch_size=batch_size,
shuffle=True
)
nb_epochs = 10
train_history = []
test_history = []
for i in trange(nb_epochs):
batchs_history = []
for x, y in train_loader:
if x.shape[0] != batch_size:
continue
optimizer.zero_grad()
yhat = my_model(x.view([batch_size, 2]))
loss = loss_function(yhat, y)
loss.backward()
optimizer.step()
batchs_history.append(loss.item())
train_history.append(np.array(batchs_history).mean())
batchs_history = []
for x, y in test_loader:
if x.shape[0] != batch_size:
continue
yhat = my_model(x.view([batch_size, 2]))
loss_test = loss_function(yhat, y)
batchs_history.append(loss.item())
test_history.append(np.array(batchs_history).mean())
plt.title("Loss")
plt.plot(train_history, label='train')
plt.plot(test_history, label='test')
plt.legend()
plt.show()
#train accuracy
accuracy = []
for x, y in test_loader:
if x.shape[0] != batch_size:
continue
yhat = my_model(x.view([batch_size, 2]))
accuracy.append(
((yhat > .5).t()[0].float() == y).float().mean().item()
)
print(np.mean(accuracy))