Tricks in numpy

Tricky actions numpy could provide

In [1]:
import numpy as np

Array concatenation

here we have separate RGB channels of an image, concatenate them using np.concatenate and np.stack separately

In [2]:
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))
In [3]:
# your code here #

Array creation

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.

In [4]:
num_samples = 100
p = np.random.rand(num_samples)
In [5]:
# your code here

Data stats

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 :) )

In [6]:
salary = np.random.randint(5, 150, size=(6, 100))
  1. for the 2nd employee, most salary earned during a month and when
In [7]:
# your code here
  1. find the most salary earned, by whom and when (might be multiple employees in multiple times)
In [8]:
# your code here
  1. per employee, the median salary they earned
In [9]:
# your code here
  1. per employee, their 25th max salary they earned
In [10]:
# your code here

Indexing (including boolean) and slicing

salary is salaries of six employees during a year. implement code for the following parts

In [11]:
salary = np.random.randint(5, 100, size=(6, 12))
  1. show the salary of all employees in second month
In [12]:
# your code here
  1. show the salary of 1st and 3rd employees in even months
In [13]:
# your code here
  1. show salary of 1st employee in 5th month, 2nd one in 11st, 3rd in 7th
In [14]:
# your code here
  1. one day boss comes and seems angry :) telling you the most salary someone can earn is 90 and asks you to shift the salaries more than that to it.
In [ ]:
# your code here

Other utilities

  1. create an array of 1000 samples in a linear form between 0 and 1 using np.linspace and check the difference of all two subsequent elements are close to 0.001
In [15]:
# your code here
  1. increase value of arr by one in places provided by indices
In [16]:
arr = np.zeros(5)
indices = np.random.randint(0, 5, size=(1000))
In [17]:
# your code here
  1. for arr, select the 4th and 5th axis of last dimension using both numpy indexing and ellipsis and check their value equality using np.all
In [18]:
arr = np.random.rand(10, 10, 10, 10, 10, 8)
In [19]:
# your code here