Tricks in numpy: solution
Tricky actions numpy could provide
import numpy as np
here we have separate RGB channels of an image, concatenate them using np.concatenate
and np.stack
separately
h, w = 224, 224
R = np.random.randint(0, 256, size=(h, w))
G = np.random.randint(0, 256, size=(h, w))
B = np.random.randint(0, 256, size=(h, w))
# your code here #
img1 = np.concatenate(
[R[None, ...],
G[None, ...],
B[None, ...]], axis=0)
assert img1.shape == (3, h, w)
img2 = np.stack([R, G, B], axis=0)
assert img2.shape == (3, h, w)
p
is a 1D array indicating probability of being dog(y=1). let's say all samples are truly dog and we need to create a ground-truth array for loss computation (don't worry :) you don't need to implement loss function here). imagine you can't explicitly use any shape information for this matter.
num_samples = 100
p = np.random.rand(num_samples)
# your code here
y_gt = np.ones_like(p)
salary
is a 2D array denoting salaries of six employees during 100 months. let's say the manager asks you to analyze his/her employees by answering the following questions (np.argmax
, np.max
, np.argwhere
, np.median
and np.percentile
could be helpful :) )
salary = np.random.randint(5, 150, size=(6, 100))
# your code here
print(salary[1].max(), salary[1].argmax())
# your code here
print(salary.max())
np.argwhere(salary == salary.max())
# your code here
np.median(salary, 1)
# your code here
np.percentile(salary, 75, axis=1)
salary
is salaries of six employees during a year. implement code for the following parts
salary = np.random.randint(5, 100, size=(6, 12))
# your code here
salary[:, 1]
# your code here
salary[[0, 2], 1::2]
# your code here
salary[np.arange(0, 3), [4, 10, 6]]
# your code here
salary[salary >= 90] = 90
assert salary.max() == 90
np.linspace
and check the difference of all two subsequent elements are close to 0.001# your code here
arr = np.linspace(0, 1, 1000)
assert np.allclose(np.diff(arr), 0.001, atol=1e-4)
arr
by one in places provided by indices
arr = np.zeros(5)
indices = np.random.randint(0, 5, size=(1000))
# your code here
np.add.at(arr, indices, 1)
assert np.sum(arr) == 1000
arr
, select the 4th and 5th axis of last dimension using both numpy indexing and ellipsis and check their value equality using np.all
arr = np.random.rand(10, 10, 10, 10, 10, 8)
# your code here
res1 = arr[..., [4, 5]]
res2 = arr[:, :, :, :, :, [4, 5]]
assert np.all(res1 == res2)