Matplotlib exercise

Post Reply
Rodri
Posts: 4
Joined: Mon Jun 15, 2020 8:33 am

Matplotlib exercise

Post by Rodri » Tue Jun 16, 2020 11:27 am

I have made the Matplotlib exercise, but not sure if I found the correct solution.
the solution can be summarized in the next steps:
-Creating 2 dimensional random array with .randn under 0.5 maximum margin each
-Divide the distribution points into 4 groups, and move each distribution center to corresponding quadrant
-Create the array colour variable in function of each point position
-Scatter representation

Code: Select all

import matplotlib.pyplot as plt
import numpy as np

quantity = 100

def XOR(x1,x2):
    xorResult = False

    if x1 > 0 and x2 >= 0:
        xorResult = False
    elif x1 > 0 and x2 < 0:
        xorResult = True
    elif x1 <= 0 and x2 <= 0:
        xorResult = False
    elif x1 <=0 and x2 > 0:
        xorResult = True

    return xorResult

def colorDecider(x,quantity):
    colourSequence = np.zeros(quantity)

    for i in range(0,quantity):
        colourSequence[i] = int(XOR(x[i][0],x[i][1]))
    
    return colourSequence

quantity = 700

x =(np.random.randn(quantity,2))*0.125
x[:int(quantity/4)] += 0.5
x[int(quantity/4):int(quantity/2)] -= 0.5
x[int(quantity/2):int(3*quantity/4)] += [0.5, -0.5]
x[int(3*quantity/4):quantity] += [-0.5, 0.5]

y = colorDecider(x,quantity)

plt.scatter(x[:,0], x[:,1], c=y)
plt.show()
Image

So, in my opinion, this solution is a work around, because if I see the solution, the distribution looks like more homogeneous, not like Gauss distribution as my solution shows. I think that the correct solution would be a crazy mathematical function that calculate points position and assign colours and epic things like that.
Other solutions?

EFortier
Posts: 4
Joined: Sat Jun 06, 2020 2:21 pm

Re: Matplotlib exercise

Post by EFortier » Wed Jun 17, 2020 12:57 pm

The way I did it is just spread a uniformly-distributed set of points between -1 and 1, then assign them colors depending on their position.

Code: Select all

# Import required libraries
import numpy as np
import matplotlib.pyplot as plt

# Make 1D arrays for x and y axes and spread them around -1 and 1
x1 = (np.random.random(2000)-0.5)*2
x2 = (np.random.random(2000)-0.5)*2

# Make an array for color picking
Y = np.zeros(2000)

for e in range(len(Y)):
  if (x1[e] <= 0 and x2[e] > 0) or (x1[e] > 0 and x2[e] <= 0):
    Y[e] = 1

# Plot it all
plt.xlabel('x1')
plt.ylabel('x2')
plt.title('Matplotlib Exercise')
plt.scatter(x1,x2,c=Y);

Rodri
Posts: 4
Joined: Mon Jun 15, 2020 8:33 am

Re: Matplotlib exercise

Post by Rodri » Thu Jun 18, 2020 11:36 am

Thank you for the answer, finally I did another aproximation similar to your answer:

Code: Select all

import matplotlib.pyplot as plt
import numpy as np

quantity = 1500


def XOR(x):
    xorResult = np.zeros(x.shape[0])

    for i in range(0,x.shape[0]):
        x1 = x[i,0]
        x2 = x[i,1]

        if x1 > 0 and x2 >= 0:
            xorResult[i] = 0
        elif x1 > 0 and x2 < 0:
            xorResult[i] = 1
        elif x1 <= 0 and x2 <= 0:
            xorResult[i] = 0
        elif x1 <=0 and x2 > 0:
            xorResult[i] = 1

    return xorResult


#Aleatory numbers generation for quadrant alpha
q_alpha_x = np.random.random(int(quantity/4))
q_alpha_y = np.random.random(int(quantity/4))
q_alpha = np.concatenate([q_alpha_x[np.newaxis].T, q_alpha_y[np.newaxis].T],axis=1)

#Aleatory numbers generation for quadrant beta
q_beta_x = np.random.random(int(quantity/4))*(-1)
q_beta_y = np.random.random(int(quantity/4))
q_beta = np.concatenate([q_beta_x[np.newaxis].T, q_beta_y[np.newaxis].T],axis=1)

#Aleatory numbers generation for quadrant gamma
q_gamma_x = np.random.random(int(quantity/4))*(-1)
q_gamma_y = np.random.random(int(quantity/4))*(-1)
q_gamma = np.concatenate([q_gamma_x[np.newaxis].T, q_gamma_y[np.newaxis].T],axis=1)

#Aleatory numbers generation for quadrant omega
q_omega_x = np.random.random(int(quantity/4))
q_omega_y = np.random.random(int(quantity/4))*(-1)
q_omega = np.concatenate([q_omega_x[np.newaxis].T, q_omega_y[np.newaxis].T],axis=1)

#Append of all elements into single matrix
q = q_alpha
q = np.append(q,q_beta,axis=0)
q = np.append(q,q_gamma,axis=0)
q = np.append(q,q_omega,axis=0)


#Color set
y_alpha = XOR(q_alpha)
y_beta = XOR(q_beta)
y_gamma = XOR(q_gamma)
y_omega = XOR(q_omega)

y = np.concatenate((y_alpha,y_beta,y_gamma,y_omega),axis=0)


#Ploting
plt.scatter(q[:,0], q[:,1], c=y)
plt.show()
Image

By the way, your solution is more optimal than mine.
Thanks for sharing!

EFortier
Posts: 4
Joined: Sat Jun 06, 2020 2:21 pm

Re: Matplotlib exercise

Post by EFortier » Tue Jun 23, 2020 2:11 pm

Glad it worked out for you too!

ashray pai
Posts: 1
Joined: Wed Jul 08, 2020 9:38 am

Re: Matplotlib exercise

Post by ashray pai » Wed Jul 08, 2020 9:43 am

i wrote the program in a simplified version , let me know what you guys think!

#importing library
import numpy as np
import matplotlib.pyplot as plt

# generating an array using random function
x = np.random.random((1200,2))

#at the end of we have a 2D array with combination of all 4 quadrants
# this changes only x values from positive to negative and vice versa
x[:300,0]*=-1
# this reverses the signs of both x values and y values
x[300:600]*=-1
# this changes only y values from positive to negative and vice versa
x[600:900,1]*=-1


#assign colors
y = np.zeros(1200)
count = 0
for e, f in x:
if e*f >0 :
y[count] = 1
count+=1
else:
count+=1

#plotting the graph
plt.scatter(x[:,0], x[:,1], c=y);

zg1seg
Posts: 2
Joined: Mon Jul 20, 2020 10:51 pm

Re: Matplotlib exercise

Post by zg1seg » Mon Jul 20, 2020 11:43 pm

Short version :D

Code: Select all

import numpy as np
import matplotlib.pyplot as plot

arr = np.random.random((2000, 2)) * 2 - 1
Y = np.bitwise_xor(np.sign(arr[:, 0]).astype(int), np.sign(-arr[:, 1]).astype(int))
plot.scatter(arr[:, 0], arr[:, 1], c=Y)

plot.show()

ceaduar
Posts: 1
Joined: Sun Jul 26, 2020 1:39 am

Re: Matplotlib exercise

Post by ceaduar » Sun Jul 26, 2020 5:42 pm

Hello,

Mine is similar to what EFortier has come up with.

Code: Select all

# Determine the vector length
vector_length = 2000

# create dataset
x =  (np.random.random((vector_length,2))-0.5) * 2
x1 = x[:,0] # column 1
x2 = x[:,1] # column 2
y = np.zeros(vector_length)

# assign 0s and 1s based on XOR 
for i in range(len(x1)):
  if x1[i]<=0 and x2[i]<=0:
    y[i] = 0
  elif x1[i]>0 and x2[i]>0:
    y[i] = 0
  else:
    y[i] = 1

# plot data
plt.title('Matplotlib Exercise')
plt.xlabel('x1')
plt.ylabel('x2')
plt.scatter(x1,x2, c = y);
[/code]

argho33
Posts: 1
Joined: Tue Aug 18, 2020 7:22 am

Re: Matplotlib exercise

Post by argho33 » Tue Aug 18, 2020 7:41 am

Found a really easy 4 lines of code solution to this problem.

Code: Select all

import numpy as np
import matplotlib.pyplot as plt

#Generate random 2D array with 2000 elements and dimensionality of 2 and values between -1 to 1
x = np.random.uniform(-1, 1, size=(2000,2))

#Generate a new 2D array of just 0's and 1's using the previous random 2D array. If the random value is previous 2D array is Positive then store 1 ,
# if the random value is negative then store 0
xx = np.where(x[:,:]<0, 0,1)

#Perform the XOR check for each of the 2000 elements by checking whether column 0 and column 1 of the new 2D array is not equal and store a 1 in y when not equal
y = np.where(xx[:,0] != xx[:,1],1,0)

#Plot the scatter plot
plt.scatter(x[:,0],x[:,1],c=y);

Arie
Posts: 1
Joined: Wed Sep 16, 2020 4:34 pm

Re: Matplotlib exercise

Post by Arie » Wed Sep 16, 2020 4:39 pm

I'm taking the deep learning prerequisites course through Udemy. In the video introducing this exercise there is a typo. The slide with the XOR gate should have the bottom row of 1,1,1. It says 0,0,1, which isn't necessarily wrong, but it just repeats the first row. The audio describing the XOR gate is correct.

lazyprogrammer
Site Admin
Posts: 39
Joined: Sat Jul 28, 2018 3:46 am

Re: Matplotlib exercise

Post by lazyprogrammer » Wed Sep 16, 2020 4:55 pm

Did you mean to say that "it says 0,0,0" but it should be "1,1,0"?

Post Reply

Return to “Deep Learning Prerequisites: The Numpy Stack in Python”