28 KiB
28 KiB
Broadcasting exercises¶
In [1]:
import numpy as np
Exercise 1¶
What is the expected output shape for each operation?
In [2]:
a = np.arange(5)
b = 5
np.shape(a - b)
Out[2]:
In [3]:
a = np.ones((7, 1))
b = np.arange(7)
np.shape(a * b)
Out[3]:
In [4]:
a = np.random.randint(0, 50, (2, 3, 3))
b = np.random.randint(0, 10, (3, 1))
np.shape(a - b)
Out[4]:
In [5]:
a = np.arange(100).reshape(10, 10)
b = np.arange(0, 10)
np.shape(a + b)
Out[5]:
Exercise 2¶
1. Create a random 2D array of dimension (5, 3)
2. Calculate the maximum value of each row
3. Divide each row by its maximum
Remember to use broadcasting : NO FOR LOOPS!
In [6]:
x = np.random.random((5,3))
x
Out[6]:
In [7]:
m = x.max(axis=1)
y = x / m[:, None]
y
Out[7]:
In [8]:
# check
y.max(axis=1)[:, None]
Out[8]:
Exercise 3¶
Task: Find the closest cluster to the observation.
Again, use broadcasting: DO NOT iterate cluster by cluster
In [9]:
observation = np.array([30.0, 99.0]) #Observation
#Clusters
clusters = np.array([
[102.0, 203.0],
[132.0, 193.0],
[45.0, 155.0],
[57.0, 173.0]
])
Let's plot this data
In the plot below, + is the observation and dots are the cluster coordinates
In [10]:
import matplotlib.pyplot as plt
plt.scatter(clusters[:, 0], clusters[:, 1]) #Scatter plot of clusters
for n, x in enumerate(clusters):
print('cluster %d' %n)
plt.annotate('cluster%d' %n, (x[0], x[1])) #Label each cluster
plt.plot(observation[0], observation[1], 'r+'); #Plot observation
Closest cluster as seen in the plot is 2. Your task is to write a function to calculate this
hint: Find the distance between the observation and each row in the cluster. The cluster to which the observation belongs to is the row with the minimum distance.
distance = $\sqrt {\left( {x_1 - x_2 } \right)^2 + \left( {y_1 - y_2 } \right)^2 }$
In [11]:
np.argmin( np.sqrt( np.sum((clusters - observation)**2, axis=1) ) )
Out[11]:
In [12]:
(clusters - observation).__pow__(2).sum(axis=1).__pow__(0.5).argmin()
Out[12]: