'How to create and plot XOR data for a specific range in Python?

I want to create such data like in the image below

Desired image

To do this I used this code;

centers = [[-2,2],[-2,-2],[2,-2],[2,2]]
X, y = make_blobs(n_samples = 400, n_features=2, centers=centers, cluster_std=0.8, random_state=40)

Then I splited X into two part

X1 = X[:,0]
X2 = X[:,1]

When plot this data I got this image

plt.scatter(X1,y,color="green")
plt.scatter(X2,y,color="red")

What I got

Is there a way to create such data, or is there any idea about what I did wrong?



Solution 1:[1]

Your y hold the integer labels of the categories, which are 0,1,2 or 3 in your example. So you are plotting x against those four values. Split the X (which holds the x,y coord) like so:

import matplotlib.pyplot as plt
from sklearn.datasets import make_blobs

centers = [[-2,2],[-2,-2],[2,-2],[2,2]]
X, y = make_blobs(n_samples = 400, n_features=2, centers=centers, cluster_std=0.8, random_state=40)

X1 = [x for idx,x in enumerate(X[:,0]) if y[idx]<=2]
Y1 = [x for idx,x in enumerate(X[:,1]) if y[idx]<=2]
X2 = [x for idx,x in enumerate(X[:,0]) if y[idx]>=3]
Y2 = [x for idx,x in enumerate(X[:,1]) if y[idx]>=3]

plt.scatter(X1,Y1,color="green")
plt.scatter(X2,Y2,color="red")

plt.show()

which gives (you can use different criteria for the split, just an example):

enter image description here

Solution 2:[2]

To create and plot the XOR dataset between a specific range, I wrote this code:

import numpy as np
import matplotlib.pyplot as plt

x = np.random.uniform(low=-4, high=4, size=(400,2))
y = np.bitwise_xor(np.sign(x[:,0]).astype(int),np.sign(x[:,1]).astype(int))
plt.scatter(x[:,0],x[:,1],c=y)
plt.xlabel('X1')
plt.ylabel('X2')

plt.show()

As you can see I set an arbitrary interval and I used the .bitwise_xor to calculate the XOR. Notice that I used the .astype(int) attribute to cast the random float numbers to integers.

Which gives this plot

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 GrimTrigger
Solution 2 Dharman