In [2]:
import numpy as np
a = np.array([1,2,3,4])
print(a)


[1 2 3 4]

In [11]:
import time

a = np.random.rand(1000000)
b = np.random.rand(1000000)

tic = time.time()
c = np.dot(a,b)
toc = time.time()
print("Vectorized version: " + str(1000*(toc-tic)) + " ms")

c = 0
tic = time.time()
for i in range(1000000):
    c += a[i]*b[i]
toc = time.time()
print("For loop version: " + str(1000*(toc-tic)) + " ms")


Vectorized version: 1.1131763458251953 ms
For loop version: 456.8037986755371 ms

In [12]:
A = np.array([[56.0, 0.0, 4.4, 68.0],
              [1.2, 104.0, 52.0, 8.0],
              [1.8, 135.0, 99.0, 0.9]])
print(A)


[[  56.     0.     4.4   68. ]
 [   1.2  104.    53.     8. ]
 [   1.8  135.    99.     0.9]]

In [13]:
cal = A.sum(axis = 0)
print(cal)


[  59.   239.   156.4   76.9]

In [14]:
percentage = 100*A/cal.reshape(1,4)
print(percentage)


[[ 94.91525424   0.           2.81329923  88.42652796]
 [  2.03389831  43.51464435  33.88746803  10.40312094]
 [  3.05084746  56.48535565  63.29923274   1.17035111]]

In [26]:
a = np.random.randn(5,1)
print(a)


[[ 0.80643159]
 [ 0.16739576]
 [-0.64283226]
 [-0.71635633]
 [-0.78895899]]

In [27]:
print(a.shape)


(5, 1)

In [28]:
print(a.T)


[[ 0.80643159  0.16739576 -0.64283226 -0.71635633 -0.78895899]]

In [31]:
print(np.dot(a,a.T))


[[ 0.65033191  0.13499323 -0.51840025 -0.57769238 -0.63624145]
 [ 0.13499323  0.02802134 -0.1076074  -0.11991501 -0.13206839]
 [-0.51840025 -0.1076074   0.41323332  0.46049696  0.50716829]
 [-0.57769238 -0.11991501  0.46049696  0.51316639  0.56517577]
 [-0.63624145 -0.13206839  0.50716829  0.56517577  0.62245629]]

In [63]:
a = np.random.randn(3,4)
b = np.random.randn(4,1)
c = np.zeros([3,4])
# for loop
for i in range(3):
  for j in range(4):
    c[i][j] = a[i][j] + b[j]
print(c)

# vectorization
c = np.zeros([3,4])
c = a + b.T
print(c)


[[ 1.89047446  1.81516654 -0.55663873  0.40002315]
 [-1.00239767  0.37057919 -0.78413048  0.38743639]
 [ 0.14915671 -0.11771435 -3.50683681  2.27243449]]
[[ 1.89047446  1.81516654 -0.55663873  0.40002315]
 [-1.00239767  0.37057919 -0.78413048  0.38743639]
 [ 0.14915671 -0.11771435 -3.50683681  2.27243449]]

In [65]:
a = np.random.randn(3, 3)
b = np.random.randn(3, 1)
c = a*b
print(a)
print(b)
print(c)


[[ 1.08871671  0.2307551   0.77398578]
 [-1.07901086 -1.02137179  1.42280655]
 [-0.62845197  0.61533219  0.87603158]]
[[-0.43546332]
 [ 0.73977139]
 [-0.8067938 ]]
[[-0.4740962  -0.10048538 -0.33704242]
 [-0.79822136 -0.75558162  1.05255158]
 [ 0.50703115 -0.49644619 -0.70677685]]

In [70]:
a = np.random.randn(32,32,3)
x = a.reshape((32*32*3,1))
print(x)


[[ 0.02217948]
 [ 0.14539074]
 [ 0.1044169 ]
 ..., 
 [-1.91844572]
 [ 0.50626723]
 [ 0.14971706]]

In [ ]: