2025-plovdiv-data/exercises/numpy_broadcasting/broadcasting.ipynb

7 KiB

Broadcasting exercises

In [ ]:
import numpy as np

Exercise 1

What is the expected output shape for each operation?
In [ ]:
a = np.arange(5)
b = 5

np.shape(a - b)
In [ ]:
a = np.ones((7, 1))
b = np.arange(7)
np.shape(a * b)
In [ ]:
a = np.random.randint(0, 50, (2, 3, 3))
b = np.random.randint(0, 10, (3, 1))

np.shape(a - b)
In [ ]:
a = np.arange(100).reshape(10, 10)
b = np.arange(0, 10)

np.shape(a + b)

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 [ ]:
## Your code here

Exercise 3

Task: Find the closest cluster to the observation.

Again, use broadcasting: DO NOT iterate cluster by cluster

In [ ]:
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 [ ]:
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 [ ]:
## Your code here