Skip to content
GitLab
Menu
Projects
Groups
Snippets
Help
Help
Support
Community forum
Keyboard shortcuts
?
Submit feedback
Contribute to GitLab
Sign in
Toggle navigation
Menu
Open sidebar
Remo Kälin
HSLU deep Learning
Commits
48a2f685
Commit
48a2f685
authored
Sep 16, 2022
by
Mirko Birbaumer
Browse files
Adapted Numpy Pandas Intro Notebook
parent
bd4db564
Changes
1
Hide whitespace changes
Inline
Side-by-side
notebooks/Block_0/Examples script/Preliminaries_Numpy_Pandas.ipynb
0 → 100644
View file @
48a2f685
%% Cell type:markdown id: tags:
## 3.2 Funktions, Conditionals, and Iteration in Python
Let us create a Python function, and call it from a loop.
%% Cell type:code id: tags:
```
python
def
HelloWorldXY
(
x
,
y
):
if
(
x
<
10
):
print
(
"Hello World, x was < 10"
)
elif
(
x
<
20
):
print
(
"Hello World, x was >= 10 but < 20"
)
else
:
print
(
"Hello World, x was >= 20"
)
return
x
+
y
print
(
HelloWorldXY
(
1
,
2
))
```
%% Cell type:markdown id: tags:
Now let us call the function
`HelloWorldXY()`
from a loop:
%% Cell type:code id: tags:
```
python
for
i
in
range
(
8
,
25
,
5
):
# i=8, 13, 18, 23 (start, stop, step)
print
(
"
\n
--- Now running with i: {}"
.
format
(
i
))
r
=
HelloWorldXY
(
i
,
i
)
print
(
"Result from HelloWorld: {}"
.
format
(
r
))
```
%%%% Output: stream
--- Now running with i: 8
%%%% Output: error
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-1-7ea2350df544> in <module>
1 for i in range(8, 25, 5): # i=8, 13, 18, 23 (start, stop, step)
2 print("\n--- Now running with i: {}".format(i))
----> 3 r = HelloWorldXY(i,i)
4 print("Result from HelloWorld: {}".format(r))
NameError: name 'HelloWorldXY' is not defined
%% Cell type:markdown id: tags:
If you want a loop starting at 0 to 2 (exclusive) you could do any of the following:
%% Cell type:code id: tags:
```
python
print
(
"Iterate over the items. `range(2)` is like a list [0,1]."
)
for
i
in
range
(
2
):
print
(
i
)
print
(
"Iterate over an actual list."
)
for
i
in
[
0
,
1
]:
print
(
i
)
print
(
"While works"
)
i
=
0
while
i
<
2
:
print
(
i
)
i
+=
1
print
(
"Python supports standard key words like continue and break"
)
while
True
:
print
(
"Entered while"
)
break
print
(
"while broken"
)
```
%%%% Output: stream
Iterate over the items. `range(2)` is like a list [0,1].
0
1
Iterate over an actual list.
0
1
While works
0
1
Python supports standard key words like continue and break
Entered while
while broken
%% Cell type:markdown id: tags:
## 3.3 Data in Numpy
%% Cell type:code id: tags:
```
python
import
numpy
as
np
# Scalar
s
=
np
.
array
(
5
)
# Vector
v
=
np
.
array
([
1
,
2
,
10
])
# Matrix
m
=
np
.
array
([[
1
,
2
,
3
],
[
4
,
5
,
6
],
[
7
,
8
,
9
]])
# Tensor:
t
=
np
.
array
([[[[
1
],[
2
]],
[[
3
],[
4
]],
[[
5
],[
6
]]],
[[[
7
],[
8
]],
[[
9
],[
10
]],
[[
11
],[
12
]]],
[[[
13
],[
14
]],
[[
15
],[
16
]],
[[
17
],[
17
]]]])
# Shape
print
(
"Shape scaler"
,
s
.
shape
,
"
\n
Shape vector"
,
v
.
shape
,
"
\n
Shape matrix"
,
m
.
shape
,
"
\n
Shape tensor"
,
t
.
shape
)
# Type
print
(
"Type scalar or array"
,
type
(
s
),
"
\n
Type after addition with integer"
,
type
(
s
+
3
))
# Slicing
print
(
"v[1:] = "
,
v
[
1
:],
"
\n
m[1:][2:] =
\n
"
,
m
[
1
:,
1
:])
# Reshape arrays
x
=
v
.
reshape
(
1
,
3
)
y
=
v
[
None
,
:]
print
(
v
,
x
,
y
)
print
(
v
.
shape
,
x
.
shape
,
y
.
shape
)
```
%%%% Output: stream
Shape scaler ()
Shape vector (3,)
Shape matrix (3, 3)
Shape tensor (3, 3, 2, 1)
Type scalar or array <class 'numpy.ndarray'>
Type after addition with integer <class 'numpy.int64'>
v[1:] = [ 2 10]
m[1:][2:] =
[[5 6]
[8 9]]
[ 1 2 10] [[ 1 2 10]] [[ 1 2 10]]
(3,) (1, 3) (1, 3)
%% Cell type:markdown id: tags:
## 3.4 Element-wise Operations
%% Cell type:code id: tags:
```
python
# The Python way:
values
=
[
1
,
2
,
3
,
4
,
5
]
for
i
in
range
(
len
(
values
)):
values
[
i
]
+=
5
print
(
values
)
# The Numpy way:
values
=
np
.
array
([
1
,
2
,
3
,
4
,
5
])
values
+=
5
print
(
values
)
# Multiplication
x
=
np
.
multiply
(
values
,
5
)
y
=
values
*
5
print
(
x
,
"
\n
"
,
y
,
"
\n
"
)
# Element wise matrix operations
a
=
np
.
array
([[
1
,
3
],[
5
,
7
]])
b
=
np
.
array
([[
2
,
4
],[
6
,
8
]])
print
(
"a =
\n
"
,
a
,
"
\n
b =
\n
"
,
b
)
print
(
"a + b =
\n
"
,
a
+
b
)
print
(
"a * b =
\n
"
,
a
*
b
)
# Shape mismatch:
print
(
"a * values =
\n
"
,
a
*
values
)
```
%%%% Output: stream
[6, 7, 8, 9, 10]
[ 6 7 8 9 10]
[30 35 40 45 50]
[30 35 40 45 50]
a =
[[1 3]
[5 7]]
b =
[[2 4]
[6 8]]
a + b =
[[ 3 7]
[11 15]]
a * b =
[[ 2 12]
[30 56]]
%%%% Output: error
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-4-7ddd6b5f4e75> in <module>
24 print("a * b =\n", a * b)
25 # Shape mismatch:
---> 26 print("a * values =\n", a * values)
ValueError: operands could not be broadcast together with shapes (2,2) (5,)
%% Cell type:markdown id: tags:
## Numpy Matrix Multiplication
Recap element-wise multiplication:
%% Cell type:code id: tags:
```
python
# Elementwise recap:
m
=
np
.
array
([[
1
,
2
,
3
],[
4
,
5
,
6
]])
# Scalar multiplication
n
=
m
*
0.25
# Python Elementwise matrix multiplication
x
=
m
*
n
# Numpy Elementwise matrix multiplication
y
=
np
.
multiply
(
m
,
n
)
print
(
"m =
\n
"
,
m
,
"
\n
n =
\n
"
,
n
)
print
(
"x =
\n
"
,
x
,
"
\n
y =
\n
"
,
y
)
```
%%%% Output: stream
m =
[[1 2 3]
[4 5 6]]
n =
[[0.25 0.5 0.75]
[1. 1.25 1.5 ]]
x =
[[0.25 1. 2.25]
[4. 6.25 9. ]]
y =
[[0.25 1. 2.25]
[4. 6.25 9. ]]
%% Cell type:markdown id: tags:
Matrix Product:
%% Cell type:code id: tags:
```
python
""" Using np.matmul """
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
]])
print
(
"a =
\n
"
,
a
,
"
\n
a.shape =
\n
"
,
a
.
shape
,
"
\n
b =
\n
"
,
b
,
"
\n
b.shape =
\n
"
,
b
.
shape
)
# Matrix product
c
=
np
.
matmul
(
a
,
b
)
print
(
"c =
\n
"
,
c
,
"
\n
c.shape =
\n
"
,
c
.
shape
)
# Dimension mismatch:
# print(np.matmul(b, a))
""" Using np.dot """
d
=
np
.
dot
(
a
,
b
)
print
(
"d =
\n
"
,
d
,
"
\n
d.shape =
\n
"
,
d
.
shape
)
```
%%%% Output: stream
a =
[[1 2 3 4]
[5 6 7 8]]
a.shape =
(2, 4)
b =
[[ 1 2 3]
[ 4 5 6]
[ 7 8 9]
[10 11 12]]
b.shape =
(4, 3)
c =
[[ 70 80 90]
[158 184 210]]
c.shape =
(2, 3)
d =
[[ 70 80 90]
[158 184 210]]
d.shape =
(2, 3)
%% Cell type:markdown id: tags:
## Transpose
%% Cell type:code id: tags:
```
python
m
=
np
.
array
([[
1
,
2
,
3
,
4
],
[
5
,
6
,
7
,
8
],
[
9
,
10
,
11
,
12
]])
print
(
"m =
\n
"
,
m
,
"
\n
m.T =
\n
"
,
m
.
T
)
# note how the transposed matrix is not a copy of the original:
m_t
=
m
.
T
m_t
[
3
][
1
]
=
200
print
(
"m =
\n
"
,
m
,
"
\n
m_t =
\n
"
,
m_t
)
print
(
"entries [3][1], [1][3], respectively are edited in both matrices"
)
```
%%%% Output: stream
m =
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
m.T =
[[ 1 5 9]
[ 2 6 10]
[ 3 7 11]
[ 4 8 12]]
m =
[[ 1 2 3 4]
[ 5 6 7 200]
[ 9 10 11 12]]
m_t =
[[ 1 5 9]
[ 2 6 10]
[ 3 7 11]
[ 4 200 12]]
entries [3][1], [1][3], respectively are edited in both matrices
%% Cell type:markdown id: tags:
## A real use case
%% Cell type:code id: tags:
```
python
inputs
=
np
.
array
([[
-
0.27
,
0.45
,
0.64
,
0.31
]])
print
(
inputs
,
inputs
.
shape
)
weights
=
np
.
array
([[
0.02
,
0.001
,
-
0.03
,
0.036
],
[
0.04
,
-
0.003
,
0.025
,
0.009
],
[
0.012
,
-
0.045
,
0.28
,
-
0.067
]])
print
(
weights
,
weights
.
shape
)
print
(
"Matrix multiplication gives:
\n
"
,
np
.
matmul
(
inputs
,
weights
.
T
),
"
\n
or, equivalently:
\n
"
,
np
.
matmul
(
weights
,
inputs
.
T
))
```
%%%% Output: stream
[[-0.27 0.45 0.64 0.31]] (1, 4)
[[ 0.02 0.001 -0.03 0.036]
[ 0.04 -0.003 0.025 0.009]
[ 0.012 -0.045 0.28 -0.067]] (3, 4)
Matrix multiplication gives:
[[-0.01299 0.00664 0.13494]]
or, equivalently:
[[-0.01299]
[ 0.00664]
[ 0.13494]]
%% Cell type:markdown id: tags:
## Some more useful Numpy methods
%% Cell type:code id: tags:
```
python
print
(
"
\n
Showing some basic math on arrays"
)
b
=
np
.
array
([
0
,
1
,
4
,
3
,
2
])
print
(
"Max: {}"
.
format
(
np
.
max
(
b
)))
print
(
"Average: {}"
.
format
(
np
.
average
(
b
)))
print
(
"Max index: {}"
.
format
(
np
.
argmax
(
b
)))
print
(
"
\n
Use numpy to create a [3,3] dimension array with random number"
)
c
=
np
.
random
.
rand
(
3
,
3
)
print
(
c
)
```
%%%% Output: stream
Showing some basic math on arrays
Max: 4
Average: 2.0
Max index: 2
Use numpy to create a [3,3] dimension array with random number
[[0.92371879 0.58999086 0.76979433]
[0.48733651 0.44698554 0.91494542]
[0.59130531 0.69632003 0.32785335]]
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
.
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment