🎓 A1Learner
🔍

PyTorch Making Blob Data

A blob is a round cloud of points gathered around one centre. Blob data gives each cloud one class label, so the clouds form a small classification dataset.

One blob around a centre

randn draws points near zero. Adding a centre moves the whole cloud to that centre.

torch.manual_seed(0)
centre = torch.tensor([-2.0, -2.0])
blob = torch.randn(5, 2) * 0.8 + centre
print(blob.shape)
print(blob[0])

Labels for the blobs

The first blob gets label 0. The second blob gets label 1.

labels = torch.cat([torch.zeros(4), torch.ones(4)]).long()
print(labels)
print(labels.dtype)

Count the points per class

A comparison gives a bool tensor. Summing it counts the matches.

labels = torch.tensor([0, 1, 1, 0, 1, 0, 0])
print(int((labels == 0).sum()))
print(int((labels == 1).sum()))

Example

import torch

torch.manual_seed(0)

per_class = 60
centre_a = torch.tensor([-2.0, -2.0])
centre_b = torch.tensor([2.0, 2.0])

blob_a = torch.randn(per_class, 2) * 0.8 + centre_a
blob_b = torch.randn(per_class, 2) * 0.8 + centre_b

points = torch.cat([blob_a, blob_b])
labels = torch.cat([torch.zeros(per_class), torch.ones(per_class)]).long()

print("Total points:", points.shape[0])
print("Class 0 points:", int((labels == 0).sum()))
print("Class 1 points:", int((labels == 1).sum()))

width, height = 21, 11
grid = [["."] * width for _ in range(height)]
for (x, y), label in zip(points.tolist(), labels.tolist()):
    col = int((x + 5.0) / 10.0 * width)
    row = int((5.0 - y) / 10.0 * height)
    col = max(0, min(width - 1, col))
    row = max(0, min(height - 1, row))
    grid[row][col] = str(label)

print("Map of the two blobs (top is high y):")
for row in grid:
    print("".join(row))

Key points

  • Use torch.randn(n, 2) * spread + centre to scatter points around a centre
  • Each blob is random points pulled toward one centre
  • Use torch.cat to join the blobs into one points tensor
  • Labels: one class number per point, in the same order as the points
  • Use torch.manual_seed so the same blobs appear on every run

In this example, the seed is set first, so the blobs are the same on every run. Two centres sit at (-2, -2) and (2, 2). Each blob holds 60 points drawn with randn and spread by 0.8. torch.cat joins the blobs into one tensor of 120 points. The labels hold 60 zeros and then 60 ones. The counts print first. Then each point is placed into a grid cell, and the grid prints as a map. The two clouds sit in opposite corners.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

What makes a set of points a blob?