Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create checkerboard distribution with Python

I would like to create a checkerboard distribution in Python.

Currently I use the following script to create a 2 x 2 sized checkerboard:

import numpy as np
import matplotlib.pyplot as plt

n_points = 1000
n_classes = 2

x = np.random.uniform(-1,1, size=(n_points, n_classes))
mask = np.logical_or(np.logical_and(x[:,0] > 0.0, x[:,1] > 0.0), \
np.logical_and(x[:,0] < 0.0, x[:,1] < 0.0))
y = np.eye(n_classes)[1*mask]

plt.scatter(x[:,0], x[:,1], c=y[:,0], cmap="bwr", alpha=0.5)
plt.show()

which creates

enter image description here

I would like to know if there exists a simple way to generalize the above code to create a checkerboard distribution of size n x n?

EDIT

Using @jpf's great solution

import numpy as np
import matplotlib.pyplot as plt
from numpy import sin

n_points = 10000
n_classes = 2
n = 8

x = np.random.uniform(-(n//2)*np.pi, (n//2)*np.pi, size=(n_points, n_classes))
mask = np.logical_or(np.logical_and(sin(x[:,0]) > 0.0, sin(x[:,1]) > 0.0), \
np.logical_and(sin(x[:,0]) < 0.0, sin(x[:,1]) < 0.0))
y = np.eye(n_classes)[1*mask]

plt.scatter(x[:,0], x[:,1], c=y[:,0], s=1, cmap="bwr", alpha=0.5)
plt.savefig("test.png", dpi=150)
plt.show()

I can now generate checkerboard distributions of arbitrary size:

enter image description here

like image 756
Gilfoyle Avatar asked Feb 01 '20 17:02

Gilfoyle


1 Answers

How about using a periodic function like sine?

import numpy as np
import matplotlib.pyplot as plt
from numpy import sin

n_points = 10000
n_classes = 2

x = np.random.uniform(-10,10, size=(n_points, n_classes))
mask = np.logical_or(np.logical_and(sin(x[:,0]) > 0.0, sin(x[:,1]) > 0.0), \
np.logical_and(sin(x[:,0]) < 0.0, sin(x[:,1]) < 0.0))
y = np.eye(n_classes)[1*mask]

plt.scatter(x[:,0], x[:,1], c=y[:,0], cmap="bwr", alpha=0.5)
plt.show()
like image 50
jpf Avatar answered Oct 20 '22 13:10

jpf