+ return frames, actions
+
+
+######################################################################
+
+
+# ||x_i - c_j||^2 = ||x_i||^2 + ||c_j||^2 - 2<x_i, c_j>
+def sq2matrix(x, c):
+ nx = x.pow(2).sum(1)
+ nc = c.pow(2).sum(1)
+ return nx[:, None] + nc[None, :] - 2 * x @ c.t()
+
+
+def update_centroids(x, c, nb_min=1):
+ _, b = sq2matrix(x, c).min(1)
+ b.squeeze_()
+ nb_resets = 0
+
+ for k in range(0, c.size(0)):
+ i = b.eq(k).nonzero(as_tuple=False).squeeze()
+ if i.numel() >= nb_min:
+ c[k] = x.index_select(0, i).mean(0)
+ else:
+ n = torch.randint(x.size(0), (1,))
+ nb_resets += 1
+ c[k] = x[n]
+
+ return c, b, nb_resets
+
+
+def kmeans(x, nb_centroids, nb_min=1):
+ if x.size(0) < nb_centroids * nb_min:
+ print("Not enough points!")
+ exit(1)
+
+ c = x[torch.randperm(x.size(0))[:nb_centroids]]
+ t = torch.full((x.size(0),), -1)
+ n = 0
+
+ while True:
+ c, u, nb_resets = update_centroids(x, c, nb_min)
+ n = n + 1
+ nb_changes = (u - t).sign().abs().sum() + nb_resets
+ t = u
+ if nb_changes == 0:
+ break
+
+ return c, t
+
+
+######################################################################
+
+
+def patchify(x, factor, invert_size=None):
+ if invert_size is None:
+ return (
+ x.reshape(
+ x.size(0), # 0
+ x.size(1), # 1
+ factor, # 2
+ x.size(2) // factor, # 3
+ factor, # 4
+ x.size(3) // factor, # 5
+ )
+ .permute(0, 2, 4, 1, 3, 5)
+ .reshape(-1, x.size(1), x.size(2) // factor, x.size(3) // factor)
+ )
+ else:
+ return (
+ x.reshape(
+ invert_size[0], # 0
+ factor, # 1
+ factor, # 2
+ invert_size[1], # 3
+ invert_size[2] // factor, # 4
+ invert_size[3] // factor, # 5
+ )
+ .permute(0, 3, 1, 4, 2, 5)
+ .reshape(invert_size)
+ )
+
+
+def train_encoder(input, device=torch.device("cpu")):
+ class SomeLeNet(nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.conv1 = nn.Conv2d(1, 32, kernel_size=5)
+ self.conv2 = nn.Conv2d(32, 64, kernel_size=5)
+ self.fc1 = nn.Linear(256, 200)
+ self.fc2 = nn.Linear(200, 10)
+
+ def forward(self, x):
+ x = F.relu(F.max_pool2d(self.conv1(x), kernel_size=3))
+ x = F.relu(F.max_pool2d(self.conv2(x), kernel_size=2))
+ x = x.view(x.size(0), -1)
+ x = F.relu(self.fc1(x))
+ x = self.fc2(x)
+ return x
+
+ ######################################################################
+
+ model = SomeLeNet()
+
+ nb_parameters = sum(p.numel() for p in model.parameters())
+
+ print(f"nb_parameters {nb_parameters}")
+
+ optimizer = torch.optim.SGD(model.parameters(), lr=lr)
+ criterion = nn.CrossEntropyLoss()
+
+ model.to(device)
+ criterion.to(device)
+
+ train_input, train_targets = train_input.to(device), train_targets.to(device)
+ test_input, test_targets = test_input.to(device), test_targets.to(device)
+
+ mu, std = train_input.mean(), train_input.std()
+ train_input.sub_(mu).div_(std)
+ test_input.sub_(mu).div_(std)
+
+ start_time = time.perf_counter()