Skip to content
Snippets Groups Projects
Commit bd4db564 authored by Mirko Birbaumer's avatar Mirko Birbaumer
Browse files

changed numpy notebook

parent 17473749
No related branches found
No related tags found
No related merge requests found
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## 3.2 Funktions, Conditionals, and Iteration in Python ## 3.2 Funktions, Conditionals, and Iteration in Python
Let us create a Python function, and call it from a loop. Let us create a Python function, and call it from a loop. very good
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
def HelloWorldXY(x, y): def HelloWorldXY(x, y):
if (x < 10): if (x < 10):
print("Hello World, x was < 10") print("Hello World, x was < 10")
elif (x < 20): elif (x < 20):
print("Hello World, x was >= 10 but < 20") print("Hello World, x was >= 10 but < 20")
else: else:
print("Hello World, x was >= 20") print("Hello World, x was >= 20")
return x + y return x + y
for i in range(8, 25, 5): # i=8, 13, 18, 23 (start, stop, step) for i in range(8, 25, 5): # i=8, 13, 18, 23 (start, stop, step)
print("\n--- Now running with i: {}".format(i)) print("\n--- Now running with i: {}".format(i))
r = HelloWorldXY(i,i) r = HelloWorldXY(i,i)
print("Result from HelloWorld: {}".format(r)) print("Result from HelloWorld: {}".format(r))
``` ```
%% Output %% Output
--- Now running with i: 8 --- Now running with i: 8
Hello World, x was < 10 Hello World, x was < 10
Result from HelloWorld: 16 Result from HelloWorld: 16
--- Now running with i: 13 --- Now running with i: 13
Hello World, x was >= 10 but < 20 Hello World, x was >= 10 but < 20
Result from HelloWorld: 26 Result from HelloWorld: 26
--- Now running with i: 18 --- Now running with i: 18
Hello World, x was >= 10 but < 20 Hello World, x was >= 10 but < 20
Result from HelloWorld: 36 Result from HelloWorld: 36
--- Now running with i: 23 --- Now running with i: 23
Hello World, x was >= 20 Hello World, x was >= 20
Result from HelloWorld: 46 Result from HelloWorld: 46
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
If you want a loop starting at 0 to 2 (exclusive) you could do any of the following: If you want a loop starting at 0 to 2 (exclusive) you could do any of the following:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
print("Iterate over the items. `range(2)` is like a list [0,1].") print("Iterate over the items. `range(2)` is like a list [0,1].")
for i in range(2): for i in range(2):
print(i) print(i)
print("Iterate over an actual list.") print("Iterate over an actual list.")
for i in [0,1]: for i in [0,1]:
print(i) print(i)
print("While works") print("While works")
i = 0 i = 0
while i < 2: while i < 2:
print(i) print(i)
i += 1 i += 1
print("Python supports standard key words like continue and break") print("Python supports standard key words like continue and break")
while True: while True:
print("Entered while") print("Entered while")
break break
print("while broken") print("while broken")
``` ```
%% Output %% Output
Iterate over the items. `range(2)` is like a list [0,1]. Iterate over the items. `range(2)` is like a list [0,1].
0 0
1 1
Iterate over an actual list. Iterate over an actual list.
0 0
1 1
While works While works
0 0
1 1
Python supports standard key words like continue and break Python supports standard key words like continue and break
Entered while Entered while
while broken while broken
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## 3.3 Data in Numpy ## 3.3 Data in Numpy
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
import numpy as np import numpy as np
# Scalar # Scalar
s = np.array(5) s = np.array(5)
# Vector # Vector
v = np.array([1, 2, 10]) v = np.array([1, 2, 10])
# Matrix # Matrix
m = np.array([[1,2,3], m = np.array([[1,2,3],
[4,5,6], [4,5,6],
[7,8,9]]) [7,8,9]])
# Tensor: # Tensor:
t = np.array([[[[1],[2]], [[3],[4]], [[5],[6]]], t = np.array([[[[1],[2]], [[3],[4]], [[5],[6]]],
[[[7],[8]], [[9],[10]], [[11],[12]]], [[[7],[8]], [[9],[10]], [[11],[12]]],
[[[13],[14]], [[15],[16]], [[17],[17]]]]) [[[13],[14]], [[15],[16]], [[17],[17]]]])
# Shape # Shape
print("Shape scaler", s.shape, "\nShape vector", v.shape, "\nShape matrix", m.shape, "\nShape tensor", t.shape) print("Shape scaler", s.shape, "\nShape vector", v.shape, "\nShape matrix", m.shape, "\nShape tensor", t.shape)
# Type # Type
print("Type scalar or array", type(s), "\nType after addition with integer", type(s + 3)) print("Type scalar or array", type(s), "\nType after addition with integer", type(s + 3))
# Slicing # Slicing
print("v[1:] = ", v[1:], "\nm[1:][2:] = \n", m[1:,1:]) print("v[1:] = ", v[1:], "\nm[1:][2:] = \n", m[1:,1:])
# Reshape arrays # Reshape arrays
x = v.reshape(1, 3) x = v.reshape(1, 3)
y = v[None, :] y = v[None, :]
print(v, x, y) print(v, x, y)
print(v.shape, x.shape, y.shape) print(v.shape, x.shape, y.shape)
``` ```
%% Output %% Output
Shape scaler () Shape scaler ()
Shape vector (3,) Shape vector (3,)
Shape matrix (3, 3) Shape matrix (3, 3)
Shape tensor (3, 3, 2, 1) Shape tensor (3, 3, 2, 1)
Type scalar or array <class 'numpy.ndarray'> Type scalar or array <class 'numpy.ndarray'>
Type after addition with integer <class 'numpy.int64'> Type after addition with integer <class 'numpy.int64'>
v[1:] = [ 2 10] v[1:] = [ 2 10]
m[1:][2:] = m[1:][2:] =
[[5 6] [[5 6]
[8 9]] [8 9]]
[ 1 2 10] [[ 1 2 10]] [[ 1 2 10]] [ 1 2 10] [[ 1 2 10]] [[ 1 2 10]]
(3,) (1, 3) (1, 3) (3,) (1, 3) (1, 3)
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## 3.4 Element-wise Operations ## 3.4 Element-wise Operations
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# The Python way: # The Python way:
values = [1, 2, 3, 4, 5] values = [1, 2, 3, 4, 5]
for i in range(len(values)): for i in range(len(values)):
values[i] += 5 values[i] += 5
print(values) print(values)
# The Numpy way: # The Numpy way:
values = np.array([1, 2, 3, 4, 5]) values = np.array([1, 2, 3, 4, 5])
values += 5 values += 5
print(values) print(values)
# Multiplication # Multiplication
x = np.multiply(values, 5) x = np.multiply(values, 5)
y = values * 5 y = values * 5
print(x, "\n", y, "\n") print(x, "\n", y, "\n")
# Element wise matrix operations # Element wise matrix operations
a = np.array([[1,3],[5,7]]) a = np.array([[1,3],[5,7]])
b = np.array([[2,4],[6,8]]) b = np.array([[2,4],[6,8]])
print("a =\n", a, "\nb =\n", b) print("a =\n", a, "\nb =\n", b)
print("a + b =\n", a + b) print("a + b =\n", a + b)
print("a * b =\n", a * b) print("a * b =\n", a * b)
# Shape mismatch: # Shape mismatch:
print("a * values =\n", a * values) print("a * values =\n", a * values)
``` ```
%% Output %% Output
[6, 7, 8, 9, 10] [6, 7, 8, 9, 10]
[ 6 7 8 9 10] [ 6 7 8 9 10]
[30 35 40 45 50] [30 35 40 45 50]
[30 35 40 45 50] [30 35 40 45 50]
a = a =
[[1 3] [[1 3]
[5 7]] [5 7]]
b = b =
[[2 4] [[2 4]
[6 8]] [6 8]]
a + b = a + b =
[[ 3 7] [[ 3 7]
[11 15]] [11 15]]
a * b = a * b =
[[ 2 12] [[ 2 12]
[30 56]] [30 56]]
--------------------------------------------------------------------------- ---------------------------------------------------------------------------
ValueError Traceback (most recent call last) ValueError Traceback (most recent call last)
<ipython-input-4-7ddd6b5f4e75> in <module> <ipython-input-4-7ddd6b5f4e75> in <module>
24 print("a * b =\n", a * b) 24 print("a * b =\n", a * b)
25 # Shape mismatch: 25 # Shape mismatch:
---> 26 print("a * values =\n", a * values) ---> 26 print("a * values =\n", a * values)
ValueError: operands could not be broadcast together with shapes (2,2) (5,) ValueError: operands could not be broadcast together with shapes (2,2) (5,)
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Numpy Matrix Multiplication ## Numpy Matrix Multiplication
Recap element-wise multiplication: Recap element-wise multiplication:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# Elementwise recap: # Elementwise recap:
m = np.array([[1,2,3],[4,5,6]]) m = np.array([[1,2,3],[4,5,6]])
# Scalar multiplication # Scalar multiplication
n = m * 0.25 n = m * 0.25
# Python Elementwise matrix multiplication # Python Elementwise matrix multiplication
x = m * n x = m * n
# Numpy Elementwise matrix multiplication # Numpy Elementwise matrix multiplication
y = np.multiply(m, n) y = np.multiply(m, n)
print("m =\n", m, "\nn =\n", n) print("m =\n", m, "\nn =\n", n)
print("x =\n", x, "\ny =\n", y) print("x =\n", x, "\ny =\n", y)
``` ```
%% Output %% Output
m = m =
[[1 2 3] [[1 2 3]
[4 5 6]] [4 5 6]]
n = n =
[[0.25 0.5 0.75] [[0.25 0.5 0.75]
[1. 1.25 1.5 ]] [1. 1.25 1.5 ]]
x = x =
[[0.25 1. 2.25] [[0.25 1. 2.25]
[4. 6.25 9. ]] [4. 6.25 9. ]]
y = y =
[[0.25 1. 2.25] [[0.25 1. 2.25]
[4. 6.25 9. ]] [4. 6.25 9. ]]
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
Matrix Product: Matrix Product:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
""" Using np.matmul """ """ Using np.matmul """
a = np.array([[1,2,3,4],[5,6,7,8]]) a = np.array([[1,2,3,4],[5,6,7,8]])
b = np.array([[1,2,3],[4,5,6],[7,8,9],[10,11,12]]) b = np.array([[1,2,3],[4,5,6],[7,8,9],[10,11,12]])
print("a =\n", a, "\na.shape =\n", a.shape, "\nb =\n", b, "\nb.shape =\n", b.shape) print("a =\n", a, "\na.shape =\n", a.shape, "\nb =\n", b, "\nb.shape =\n", b.shape)
# Matrix product # Matrix product
c = np.matmul(a, b) c = np.matmul(a, b)
print("c = \n", c, "\nc.shape =\n", c.shape) print("c = \n", c, "\nc.shape =\n", c.shape)
# Dimension mismatch: # Dimension mismatch:
# print(np.matmul(b, a)) # print(np.matmul(b, a))
""" Using np.dot """ """ Using np.dot """
d = np.dot(a, b) d = np.dot(a, b)
print("d = \n", d, "\nd.shape =\n", d.shape) print("d = \n", d, "\nd.shape =\n", d.shape)
``` ```
%% Output %% Output
a = a =
[[1 2 3 4] [[1 2 3 4]
[5 6 7 8]] [5 6 7 8]]
a.shape = a.shape =
(2, 4) (2, 4)
b = b =
[[ 1 2 3] [[ 1 2 3]
[ 4 5 6] [ 4 5 6]
[ 7 8 9] [ 7 8 9]
[10 11 12]] [10 11 12]]
b.shape = b.shape =
(4, 3) (4, 3)
c = c =
[[ 70 80 90] [[ 70 80 90]
[158 184 210]] [158 184 210]]
c.shape = c.shape =
(2, 3) (2, 3)
d = d =
[[ 70 80 90] [[ 70 80 90]
[158 184 210]] [158 184 210]]
d.shape = d.shape =
(2, 3) (2, 3)
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Transpose ## Transpose
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
m = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]]) m = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])
print("m = \n", m,"\nm.T = \n", m.T) print("m = \n", m,"\nm.T = \n", m.T)
# note how the transposed matrix is not a copy of the original: # note how the transposed matrix is not a copy of the original:
m_t = m.T m_t = m.T
m_t[3][1] = 200 m_t[3][1] = 200
print("m = \n", m, "\nm_t = \n", m_t) print("m = \n", m, "\nm_t = \n", m_t)
print("entries [3][1], [1][3], respectively are edited in both matrices") print("entries [3][1], [1][3], respectively are edited in both matrices")
``` ```
%% Output %% Output
m = m =
[[ 1 2 3 4] [[ 1 2 3 4]
[ 5 6 7 8] [ 5 6 7 8]
[ 9 10 11 12]] [ 9 10 11 12]]
m.T = m.T =
[[ 1 5 9] [[ 1 5 9]
[ 2 6 10] [ 2 6 10]
[ 3 7 11] [ 3 7 11]
[ 4 8 12]] [ 4 8 12]]
m = m =
[[ 1 2 3 4] [[ 1 2 3 4]
[ 5 6 7 200] [ 5 6 7 200]
[ 9 10 11 12]] [ 9 10 11 12]]
m_t = m_t =
[[ 1 5 9] [[ 1 5 9]
[ 2 6 10] [ 2 6 10]
[ 3 7 11] [ 3 7 11]
[ 4 200 12]] [ 4 200 12]]
entries [3][1], [1][3], respectively are edited in both matrices entries [3][1], [1][3], respectively are edited in both matrices
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## A real use case ## A real use case
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
inputs = np.array([[-0.27, 0.45, 0.64, 0.31]]) inputs = np.array([[-0.27, 0.45, 0.64, 0.31]])
print(inputs, inputs.shape) print(inputs, inputs.shape)
weights = np.array([[0.02, 0.001, -0.03, 0.036], weights = np.array([[0.02, 0.001, -0.03, 0.036],
[0.04, -0.003, 0.025, 0.009], [0.04, -0.003, 0.025, 0.009],
[0.012, -0.045, 0.28, -0.067]]) [0.012, -0.045, 0.28, -0.067]])
print(weights, weights.shape) print(weights, weights.shape)
print("Matrix multiplication gives:\n", np.matmul(inputs, weights.T), "\nor, equivalently:\n", np.matmul(weights, inputs.T)) print("Matrix multiplication gives:\n", np.matmul(inputs, weights.T), "\nor, equivalently:\n", np.matmul(weights, inputs.T))
``` ```
%% Output %% Output
[[-0.27 0.45 0.64 0.31]] (1, 4) [[-0.27 0.45 0.64 0.31]] (1, 4)
[[ 0.02 0.001 -0.03 0.036] [[ 0.02 0.001 -0.03 0.036]
[ 0.04 -0.003 0.025 0.009] [ 0.04 -0.003 0.025 0.009]
[ 0.012 -0.045 0.28 -0.067]] (3, 4) [ 0.012 -0.045 0.28 -0.067]] (3, 4)
Matrix multiplication gives: Matrix multiplication gives:
[[-0.01299 0.00664 0.13494]] [[-0.01299 0.00664 0.13494]]
or, equivalently: or, equivalently:
[[-0.01299] [[-0.01299]
[ 0.00664] [ 0.00664]
[ 0.13494]] [ 0.13494]]
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Some more useful Numpy methods ## Some more useful Numpy methods
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
print("\nShowing some basic math on arrays") print("\nShowing some basic math on arrays")
b = np.array([0,1,4,3,2]) b = np.array([0,1,4,3,2])
print("Max: {}".format(np.max(b))) print("Max: {}".format(np.max(b)))
print("Average: {}".format(np.average(b))) print("Average: {}".format(np.average(b)))
print("Max index: {}".format(np.argmax(b))) print("Max index: {}".format(np.argmax(b)))
print("\nUse numpy to create a [3,3] dimension array with random number") print("\nUse numpy to create a [3,3] dimension array with random number")
c = np.random.rand(3, 3) c = np.random.rand(3, 3)
print(c) print(c)
``` ```
%% Output %% Output
Showing some basic math on arrays Showing some basic math on arrays
Max: 4 Max: 4
Average: 2.0 Average: 2.0
Max index: 2 Max index: 2
Use numpy to create a [3,3] dimension array with random number Use numpy to create a [3,3] dimension array with random number
[[0.92371879 0.58999086 0.76979433] [[0.92371879 0.58999086 0.76979433]
[0.48733651 0.44698554 0.91494542] [0.48733651 0.44698554 0.91494542]
[0.59130531 0.69632003 0.32785335]] [0.59130531 0.69632003 0.32785335]]
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment