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
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:
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With