import numpy as np
import time
a = np.random.randint(10E6,size=(50,1000))
print(np.shape(a))
w = np.random.randint(100,size=(50,1))
print(np.shape(w))
t_start = time.time()
z = np.dot(w.T,a).T
t_stop = time.time()
print('Time take: {} ms'.format(1000*(t_stop-t_start)))
#Non vectorized version
z_for = []
t_start = time.time()
for j in range(np.shape(a)[1]):
_count = 0.0
for i in range(np.shape(a)[0]):
_count+=w[i,0]*a[i,j]
z_for.append(_count)
t_stop = time.time()
print('Time take for for-loop: {} ms'.format(1000*(t_stop-t_start)))
#Check the output
print('Check sum: {}'.format(np.sum(np.asarray(z_for).reshape(np.shape(z))-z)))
#If I want to have expoenential of different values in the array
a = np.random.randint(10,size=(10,2))
#With for loops:
import math
exp_a = np.zeros(np.shape(a))
for j in range(np.shape(a)[1]):
for i in range(np.shape(a)[0]):
exp_a[i,j] = math.exp(a[i,j])
exp_a_numpy = np.exp(a) #Vector already setup -- element-wise exponential
#Other vectorized functions:
# np.log(x)
# np.abs(x)
# np.maximum(x,0) -- computes element-wise maximum comparing to 0
# x**2 for numpy array
# 1/x for numpy array
exp_a_numpy - exp_a
food_cal = np.array([[56.0,0.0,4.4,68.0],
[1.2, 104, 52, 8.],
[1.8, 135.,99., 0.9]])
carb = np.array([food_cal[0,i]/np.sum(food_cal[:,i])*100 for i in range(4)])
protein = np.array([food_cal[1,i]/np.sum(food_cal[:,i])*100 for i in range(4)])
fat = np.array([food_cal[2,i]/np.sum(food_cal[:,i])*100 for i in range(4)])
cal = np.array([carb,protein,fat])
print(cal)
cal = food_cal.sum(axis=0)
#AXIS = 0 is sum vertically -- along column
#AXIS = 1 is sum horizontally -- along row
print(cal)
#Here the cal is BROADCASTING from 1,4 to 4,4
percentage = 100*food_cal/cal.reshape(1,4)
print(percentage)
#Example 1
A = np.linspace(1,5,5)
print(A.shape)
B = A+10.
print(A, B, B.shape)
# Here 10. was broadcasted into 5x1 vector
A = np.array([[1,2,3],
[4,5,6]])
print(A.shape)
B = np.array([100,200,300])
print(B.shape)
C = A + B
print(C.shape)
print(A,B)
print(C)
# Here B was broadcasted from (3,) to 2x3!
import numpy as np
a = np.random.randn(5)
print(a)
print(a.shape)
Here a
is a array of rank 1. It is neither a row or a column vector. So this has some non-intuitive effects
print(a.T)
print(np.dot(a,a.T))
So it is recommended for consistency to NOT use data-structures have rank 1 like the one above but instead instantiate the array as the fixed array of known size
ALWAYS COMMIT TO MAKING DEFINED ROW AND COLUMN VECTORS
a1 = np.random.randn(5,1)
print(a1)
print(a1.shape)
print(a1.T)
Here there are two Square Brackets compared to the previous transport of a
suggesting in the case of a1
it is well-defined 1x5 row vector
print(np.dot(a1,a1.T)) #Outer product
assert(a1.shape==(5,1)) #Assertion statement to check the known size
a = a.reshape((5,1))
print(a.shape)
A = np.random.randn(4,3)
print(A)
np.sum(A,axis=1,keepdims=True).shape