November, 2021 - François HU
Master of Science in Artificial Intelligence Systems - EPITA
This lecture is available here: https://curiousml.github.io/
import numpy as np
generate arr1:
[[ 0 4 8 12 16]
[ 1 5 9 13 17]
[ 2 6 10 14 18]
[ 3 7 11 15 19]]
arr = np.arange(0, 20)
arr1 = arr.reshape((4, 5), order='F')
print(arr1)
[[ 0 4 8 12 16] [ 1 5 9 13 17] [ 2 6 10 14 18] [ 3 7 11 15 19]]
generate arr2
[[ 0 1 4 9 16]
[ 1 4 9 16 25]
[ 4 9 16 25 36]
[ 9 16 25 36 49]]
# method 1: with a single for loop
arr2 = np.empty((4, 5), dtype=int)
for i in range(4):
arr2[i] = np.arange(0+i, 5+i)**2
print(arr2)
[[ 0 1 4 9 16] [ 1 4 9 16 25] [ 4 9 16 25 36] [ 9 16 25 36 49]]
# method 2: tile method
A = np.tile(np.arange(5), (4,1))
B = np.tile(np.arange(4), (5,1)).T
arr2 = (A+B)**2
print(arr2)
[[ 0 1 4 9 16] [ 1 4 9 16 25] [ 4 9 16 25 36] [ 9 16 25 36 49]]
# method 3: with mgrid method
A, B = np.mgrid[0:4, 0:5]
arr2 = (A+B)**2
print(arr2)
[[ 0 1 4 9 16] [ 1 4 9 16 25] [ 4 9 16 25 36] [ 9 16 25 36 49]]
generate arr3
[[0 1 0 1 0 1]
[1 0 1 0 1 0]
[0 1 0 1 0 1]
[1 0 1 0 1 0]
[0 1 0 1 0 1]
[1 0 1 0 1 0]]
arr = [[0, 1], [1, 0]]
arr3 = np.tile(arr, (3, 3))
print(arr3)
[[0 1 0 1 0 1] [1 0 1 0 1 0] [0 1 0 1 0 1] [1 0 1 0 1 0] [0 1 0 1 0 1] [1 0 1 0 1 0]]
print(arr1)
[[ 0 4 8 12 16] [ 1 5 9 13 17] [ 2 6 10 14 18] [ 3 7 11 15 19]]
arr = arr1[[2, 3, 1], :]
arr = arr[:, [1, 4, 2]]
print(arr)
[[ 6 18 10] [ 7 19 11] [ 5 17 9]]
Replace all the items with value 0 of arr3
by -1
print(arr3)
[[0 1 0 1 0 1] [1 0 1 0 1 0] [0 1 0 1 0 1] [1 0 1 0 1 0] [0 1 0 1 0 1] [1 0 1 0 1 0]]
arr3[arr3 == 0] = -1
print(arr3)
[[-1 1 -1 1 -1 1] [ 1 -1 1 -1 1 -1] [-1 1 -1 1 -1 1] [ 1 -1 1 -1 1 -1] [-1 1 -1 1 -1 1] [ 1 -1 1 -1 1 -1]]
Create a random vector of size 20 (all values between $[0, 1)$) and replace:
arr = np.random.rand(20)
print(arr)
arr[np.argmax(arr)] = -1
arr[np.argmax(arr)] = -2
print(arr)
[0.45872932 0.02738977 0.50322762 0.60618899 0.08398527 0.15019626 0.72605628 0.99079127 0.63991756 0.68164655 0.12079612 0.93871948 0.63168153 0.03420702 0.48203706 0.80210342 0.46730872 0.60330258 0.10317196 0.73161766] [ 0.45872932 0.02738977 0.50322762 0.60618899 0.08398527 0.15019626 0.72605628 -1. 0.63991756 0.68164655 0.12079612 -2. 0.63168153 0.03420702 0.48203706 0.80210342 0.46730872 0.60330258 0.10317196 0.73161766]