In [1]:
import numpy as np
Create the following array (without typing the elements!):
array([[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9]])
In [ ]:
In [3]:
a = np.arange(9).reshape(3,3)
In [7]:
a.mean?
Let's create a couple of large arrays:
a=random.random([1000, 1000])
b=arange([1000])
Save them to disk with save with savez and with savetxt. Delete a and b (del a,b) and recover them from disk. Check the size of the saved text file. Now append a .gz to the filename when saving with savetxt and see what happens. How do you load this file?
In [ ]:
In [ ]:
np.random.seed(3)
a = np.random.random((4,3))-.2
In [ ]:
a
Find the indices where this array is negative:
In [ ]:
index = #Finish
Convert those indices into a zero:
In [ ]:
We can also generte the indices in the same expression where we set a
In [ ]:
np.random.seed(3) #This way we can reproduce the same "random" array as before.
a = np.random.random((4,3))-.2
a[a<0] = 0
a
We could have also used the where method. But this method does not change a in place.
In [ ]:
np.random.seed(3) #This way we can reproduce the same "random" array as before.
a = np.random.random((4,3))-.2
np.where(a<0,0, a) #This does not change a
In [ ]:
a = np.arange(12).reshape((4,3))
a
we can use the 'min method (or numpy function)
In [ ]:
amin = a.min(axis=0)
amin
Finally we substract this from a:
In [ ]:
Imagine we want to do the same for rows:
In [ ]:
a = np.arange(12).reshape((4,3))
a
In [ ]:
amin = a.min(axis=1)
In [ ]:
a-amin
How can we solve this? We could transpose the arrays to get the right dimensions for broadcasting, or extend the dimensions of amin get again the right dimensions for broadcastinc
In [ ]:
#Transposing (use .T method):
In [ ]:
#Extending axis
In [ ]:
#Extending axis
The dot product is so common that it is implemented in numpy. But if it was not there, could you code it?
In [ ]:
a = np.arange(5)
b = np.arange(5)+10
In [ ]:
result = #Finish
In [ ]:
assert result == a.dot(b)
Let's check which is faster for large vectors:
In [ ]:
a = np.random.random(10000)
b = np.random.random(10000)
In [ ]:
%timeit a.dot(b)
In [ ]:
%timeit #Your code
Try writing the code in a for loop (if you haven't) and check its performance with the %timeit magic function.
In [ ]:
The dot vector can be represented as $\vec x^T \vec y$ if vectors are matrices of dimensions $(N, 1)$. As such we could also mupliply them this way $\vec x \vec y^T$. This returns a matrix of dimensions $(N, N)$, where each element $i, j$ of this matrix is $x_i y_j$. Can you code that?
In [ ]:
a = np.arange(5)
b = np.arange(5)+10
a,b
In [7]:
m=np.random.random((10,10))-np.random.normal(scale=0.2, size=(10,10))
Out[7]:
In [4]:
np.random.normal?
In [ ]: