"Welcome to this warm-up tutorial! Let's take a look at some highlights of Python!\n",
"Welcome to this warm-up tutorial! Let's take a look at some highlights of Python!\n",
"\n",
"\n",
"Please execute the whole notebook now by clicking on Cell->Execute All in the menubar. In the following, cells starting with TODOs and ending with a ```?``` are tasks to be solved individually.\n",
"Please execute the whole notebook now by clicking on Execution->Execute All in the menubar. In the following, cells starting with TODOs and ending with a ```?``` are tasks to be solved individually.\n",
"\n",
"\n",
"Let's start with the usual **hello world** program:"
"Let's start with the usual **hello world** program:"
]
]
...
@@ -319,7 +319,7 @@
...
@@ -319,7 +319,7 @@
},
},
{
{
"cell_type": "markdown",
"cell_type": "markdown",
"id": "6a457a29",
"id": "db6f86f8",
"metadata": {},
"metadata": {},
"source": [
"source": [
"### Task: <a class=\"tocSkip\"> \n",
"### Task: <a class=\"tocSkip\"> \n",
...
@@ -387,7 +387,7 @@
...
@@ -387,7 +387,7 @@
},
},
{
{
"cell_type": "markdown",
"cell_type": "markdown",
"id": "6f42ae0f",
"id": "3c16d62e",
"metadata": {},
"metadata": {},
"source": [
"source": [
"These functions can be also called recursively -- for this, we can take a look at the factorial function:"
"These functions can be also called recursively -- for this, we can take a look at the factorial function:"
...
@@ -600,7 +600,7 @@
...
@@ -600,7 +600,7 @@
},
},
{
{
"cell_type": "markdown",
"cell_type": "markdown",
"id": "274853db",
"id": "78db6018",
"metadata": {},
"metadata": {},
"source": [
"source": [
"### Task: <a class=\"tocSkip\">\n",
"### Task: <a class=\"tocSkip\">\n",
...
@@ -791,7 +791,7 @@
...
@@ -791,7 +791,7 @@
{
{
"cell_type": "code",
"cell_type": "code",
"execution_count": 28,
"execution_count": 28,
"id": "739732e5",
"id": "2af74b4a",
"metadata": {},
"metadata": {},
"outputs": [
"outputs": [
{
{
...
...
%% Cell type:markdown id:897fcfcd tags:
%% Cell type:markdown id:897fcfcd tags:
# Python Tutorial
# Python Tutorial
-----------------------
-----------------------
Welcome to this warm-up tutorial! Let's take a look at some highlights of Python!
Welcome to this warm-up tutorial! Let's take a look at some highlights of Python!
Please execute the whole notebook now by clicking on Cell->Execute All in the menubar. In the following, cells starting with TODOs and ending with a ```?``` are tasks to be solved individually.
Please execute the whole notebook now by clicking on Execution->Execute All in the menubar. In the following, cells starting with TODOs and ending with a ```?``` are tasks to be solved individually.
Let's start with the usual **hello world** program:
Let's start with the usual **hello world** program:
%% Cell type:code id:c8562e26 tags:
%% Cell type:code id:c8562e26 tags:
``` python
``` python
print("Hello World!")
print("Hello World!")
```
```
%% Output
%% Output
Hello World!
Hello World!
%% Cell type:markdown id:48a13786 tags:
%% Cell type:markdown id:48a13786 tags:
You can print multiple items in a row:
You can print multiple items in a row:
%% Cell type:code id:bea4da9f tags:
%% Cell type:code id:bea4da9f tags:
``` python
``` python
print("1 + 12 =",13)
print("1 + 12 =",13)
```
```
%% Output
%% Output
1 + 12 = 13
1 + 12 = 13
%% Cell type:markdown id:5a70d15c tags:
%% Cell type:markdown id:5a70d15c tags:
## Comments
## Comments
You can also comment your code with ```#``` for a **single line** or with ```"""comment"""``` for **multiple lines**:
You can also comment your code with ```#``` for a **single line** or with ```"""comment"""``` for **multiple lines**:
%% Cell type:code id:6b5d414b tags:
%% Cell type:code id:6b5d414b tags:
``` python
``` python
# This is a comment and will be ignored upon execution
# This is a comment and will be ignored upon execution
```
```
%% Cell type:code id:d69d90e9 tags:
%% Cell type:code id:d69d90e9 tags:
``` python
``` python
print("What's that thing that spells the same backwards as forwards?")
print("What's that thing that spells the same backwards as forwards?")
"""
"""
I am a comment too!
I am a comment too!
See, this line is ignored as well!
See, this line is ignored as well!
"""
"""
print("A palindrome...?")
print("A palindrome...?")
```
```
%% Output
%% Output
What's that thing that spells the same backwards as forwards?
What's that thing that spells the same backwards as forwards?
A palindrome...?
A palindrome...?
%% Cell type:markdown id:c4c8535a tags:
%% Cell type:markdown id:c4c8535a tags:
## Variables and Data-Types
## Variables and Data-Types
Python is a **dynamically-typed** language, i.e. you don't have to define your variable types in advance:
Python is a **dynamically-typed** language, i.e. you don't have to define your variable types in advance:
%% Cell type:code id:f7179786 tags:
%% Cell type:code id:f7179786 tags:
``` python
``` python
a=13# This is an integer
a=13# This is an integer
b="This is a string"# This is a string
b="This is a string"# This is a string
c=True# A boolean
c=True# A boolean
d=14.5# This is a double-precision floating-point variable (called a 'double' in C-speak)
d=14.5# This is a double-precision floating-point variable (called a 'double' in C-speak)
e=[1,3,15,34]# This is a list, an array of objects
e=[1,3,15,34]# This is a list, an array of objects
f=("Emmental","Brie","Gouda","Danish Blue")# This is a tuple, an immutable array
f=("Emmental","Brie","Gouda","Danish Blue")# This is a tuple, an immutable array
```
```
%% Cell type:code id:d0586d1b tags:
%% Cell type:code id:d0586d1b tags:
``` python
``` python
# You can use squared brackets to access elements in an array or tuple
# You can use squared brackets to access elements in an array or tuple
print("The second element in e is:",e[2],"(should be 3)")
print("The second element in e is:",e[2],"(should be 3)")
```
```
%% Output
%% Output
The second element in e is: 15 (should be 3)
The second element in e is: 15 (should be 3)
%% Cell type:markdown id:0019db03 tags:
%% Cell type:markdown id:0019db03 tags:
## Elementary Arithmetics
## Elementary Arithmetics
You can use the usual **operators**```+```, ```-```, ```*```, ```/``` for elementary arithmetics:
You can use the usual **operators**```+```, ```-```, ```*```, ```/``` for elementary arithmetics:
%% Cell type:code id:86b8e68c tags:
%% Cell type:code id:86b8e68c tags:
``` python
``` python
print("13 x 14.5 =",a*d)
print("13 x 14.5 =",a*d)
```
```
%% Output
%% Output
13 x 14.5 = 188.5
13 x 14.5 = 188.5
%% Cell type:markdown id:32b1985e tags:
%% Cell type:markdown id:32b1985e tags:
You can use the **double star**```**```-operator to raise number to the **n-th power**:
You can use the **double star**```**```-operator to raise number to the **n-th power**:
%% Cell type:code id:8c45add3 tags:
%% Cell type:code id:8c45add3 tags:
``` python
``` python
print(1**2,2**2,3**2,4**2,32**2)
print(1**2,2**2,3**2,4**2,32**2)
```
```
%% Output
%% Output
1 4 9 16 1024
1 4 9 16 1024
%% Cell type:code id:29eac6ed tags:
%% Cell type:code id:29eac6ed tags:
``` python
``` python
# Booleans work as numbers as well. What happens if you add a and c?
# Booleans work as numbers as well. What happens if you add a and c?
print("13 + True =",13+True)
print("13 + True =",13+True)
```
```
%% Output
%% Output
13 + True = 14
13 + True = 14
%% Cell type:markdown id:f6d98d65 tags:
%% Cell type:markdown id:f6d98d65 tags:
## Comparison Opeartors
## Comparison Opeartors
You can use ```<```, ```>```, ```==```, ```<=```, ```>=``` to **compare numbers** (**and objects**), the **keywords**```and```, ```or``` to compare statements (booleans) and the keyword ```not``` to negate them.
You can use ```<```, ```>```, ```==```, ```<=```, ```>=``` to **compare numbers** (**and objects**), the **keywords**```and```, ```or``` to compare statements (booleans) and the keyword ```not``` to negate them.
%% Cell type:code id:b0a7cbe1 tags:
%% Cell type:code id:b0a7cbe1 tags:
``` python
``` python
# The output of ("a bigger than d" AND "c is True")
# The output of ("a bigger than d" AND "c is True")
print((a>=d)and(c))
print((a>=d)and(c))
```
```
%% Output
%% Output
False
False
%% Cell type:markdown id:cbba9080 tags:
%% Cell type:markdown id:cbba9080 tags:
## Control Flow Tools
## Control Flow Tools
For pre-test loops you can use ```while```. Beware that in Python indented blocks of code belong to the same parent line (similarly to ```{...}``` in C); mixing indentations raises an ```IndentationError```.
For pre-test loops you can use ```while```. Beware that in Python indented blocks of code belong to the same parent line (similarly to ```{...}``` in C); mixing indentations raises an ```IndentationError```.
%% Cell type:code id:5f42b63f tags:
%% Cell type:code id:5f42b63f tags:
``` python
``` python
# See, the while loop below is broken!
# See, the while loop below is broken!
i=0
i=0
whilei<4:
whilei<4:
print(i)# <-- The loop breaks here!
print(i)# <-- The loop breaks here!
i=i+1
i=i+1
```
```
%% Output
%% Output
Input In [11]
Input In [11]
i = i + 1
i = i + 1
^
^
IndentationError: unexpected indent
IndentationError: unexpected indent
%% Cell type:markdown id:118d8935 tags:
%% Cell type:markdown id:118d8935 tags:
Using ```for``` and the iterable ```range(n)``` a for-like loop can be created:
Using ```for``` and the iterable ```range(n)``` a for-like loop can be created:
%% Cell type:code id:7740d793 tags:
%% Cell type:code id:7740d793 tags:
``` python
``` python
# A loop adding up all the numbers from 0 to 100 and printing the result at the end:
# A loop adding up all the numbers from 0 to 100 and printing the result at the end:
sum=0
sum=0
foriinrange(5):
foriinrange(5):
sum=sum+i
sum=sum+i
print(sum)
print(sum)
```
```
%% Output
%% Output
10
10
%% Cell type:markdown id:fd2059e5 tags:
%% Cell type:markdown id:fd2059e5 tags:
For **conditional branching**, the usual keywords ```if``` and ```else``` are defined. Loops can be stopped with ```break``` and skipped with ```continue```.
For **conditional branching**, the usual keywords ```if``` and ```else``` are defined. Loops can be stopped with ```break``` and skipped with ```continue```.
%% Cell type:markdown id:6a457a29 tags:
%% Cell type:markdown id:db6f86f8 tags:
### Task: <a class="tocSkip">
### Task: <a class="tocSkip">
Write a small program checking whether i is an even or odd number for every integer i in [0, 10).
Write a small program checking whether i is an even or odd number for every integer i in [0, 10).
%% Cell type:code id:0c47c5d6 tags:
%% Cell type:code id:0c47c5d6 tags:
``` python
``` python
# TODO: With i%2, you can get the modulus of i divided by two.
# TODO: With i%2, you can get the modulus of i divided by two.
# TODO: Use 'continue' to skip 0!
# TODO: Use 'continue' to skip 0!
n=1
n=1
foriinrange(n):
foriinrange(n):
ifTrue:
ifTrue:
print(i,"is an odd/even number")
print(i,"is an odd/even number")
else:
else:
print("else block")?
print("else block")?
```
```
%% Output
%% Output
Input In [15]
Input In [15]
print("else block")?
print("else block")?
^
^
SyntaxError: invalid syntax
SyntaxError: invalid syntax
%% Cell type:markdown id:f51fc582 tags:
%% Cell type:markdown id:f51fc582 tags:
## Functions
## Functions
For repeating code, functions can be defined with the ```def``` keyword and their outputs can be returned using ```return```.
For repeating code, functions can be defined with the ```def``` keyword and their outputs can be returned using ```return```.
%% Cell type:code id:d5f33c84 tags:
%% Cell type:code id:d5f33c84 tags:
``` python
``` python
defget_greeting(name):
defget_greeting(name):
return"Hello "+name+"!"
return"Hello "+name+"!"
print(get_greeting("John Cleese"))
print(get_greeting("John Cleese"))
print(get_greeting("Graham Chapman"))
print(get_greeting("Graham Chapman"))
print(get_greeting("Eric Idle"))
print(get_greeting("Eric Idle"))
```
```
%% Output
%% Output
Hello John Cleese!
Hello John Cleese!
Hello Graham Chapman!
Hello Graham Chapman!
Hello Eric Idle!
Hello Eric Idle!
%% Cell type:markdown id:6f42ae0f tags:
%% Cell type:markdown id:3c16d62e tags:
These functions can be also called recursively -- for this, we can take a look at the factorial function:
These functions can be also called recursively -- for this, we can take a look at the factorial function:
%% Cell type:code id:04034c0e tags:
%% Cell type:code id:04034c0e tags:
``` python
``` python
# A basic implementation of the factorial operation:
# A basic implementation of the factorial operation:
deffactorial(n):
deffactorial(n):
ifn>1:
ifn>1:
returnn*factorial(n-1)
returnn*factorial(n-1)
else:
else:
return1
return1
print(factorial(6))
print(factorial(6))
```
```
%% Output
%% Output
720
720
%% Cell type:markdown id:49898002 tags:
%% Cell type:markdown id:49898002 tags:
## Classes
## Classes
**Classes** are high-level objects for **storing and managing primitives**. They are initialized with ```class class_name:``` after which the constructor ```__init__(self, args)``` is automatically called.
**Classes** are high-level objects for **storing and managing primitives**. They are initialized with ```class class_name:``` after which the constructor ```__init__(self, args)``` is automatically called.
**Data** in classes are stored using the ```self``` keyword and are **publicly accessible** by default.
**Data** in classes are stored using the ```self``` keyword and are **publicly accessible** by default.
%% Cell type:code id:dd4ae61f tags:
%% Cell type:code id:dd4ae61f tags:
``` python
``` python
classPerson:
classPerson:
def__init__(self,name,age):
def__init__(self,name,age):
self.name=name
self.name=name
self.age=age
self.age=age
defprint_info(self):
defprint_info(self):
print("name:",self.name,";","age:",self.age)
print("name:",self.name,";","age:",self.age)
alice=Person("Alice",34)
alice=Person("Alice",34)
alice.print_info()
alice.print_info()
alice.age=18
alice.age=18
alice.print_info()
alice.print_info()
```
```
%% Output
%% Output
name: Alice ; age: 34
name: Alice ; age: 34
name: Alice ; age: 18
name: Alice ; age: 18
%% Cell type:markdown id:0d914e99 tags:
%% Cell type:markdown id:0d914e99 tags:
## Class Inheritance
## Class Inheritance
A class can **inherit** the **properties of its parent** class. These properties can be freely overriden:
A class can **inherit** the **properties of its parent** class. These properties can be freely overriden:
%% Cell type:code id:caf893b1 tags:
%% Cell type:code id:caf893b1 tags:
``` python
``` python
classStudent(Person):
classStudent(Person):
defprint_info(self):
defprint_info(self):
"""
"""
Beware that the attribute name has been inherited from 'Person'
Beware that the attribute name has been inherited from 'Person'
"""
"""
print(self.name,"is a student!")
print(self.name,"is a student!")
bob=Student("Bob",20)
bob=Student("Bob",20)
bob.print_info()
bob.print_info()
```
```
%% Output
%% Output
Bob is a student!
Bob is a student!
%% Cell type:markdown id:39f231b0 tags:
%% Cell type:markdown id:39f231b0 tags:
## Numpy Basics
## Numpy Basics
Numpy is an performant, easy-to-use scientific library for numeric calculations. You will often encouter cases where numpy can perform calculations several orders of magnitudes faster due its C-backend and ability to process data in a vectorized (parallelized) form.
Numpy is an performant, easy-to-use scientific library for numeric calculations. You will often encouter cases where numpy can perform calculations several orders of magnitudes faster due its C-backend and ability to process data in a vectorized (parallelized) form.
%% Cell type:code id:dfaeae8a tags:
%% Cell type:code id:dfaeae8a tags:
``` python
``` python
importnumpyasnp# numpy is usually imported this way
importnumpyasnp# numpy is usually imported this way
```
```
%% Cell type:markdown id:935518b0 tags:
%% Cell type:markdown id:935518b0 tags:
### Numpy One Dimensional Array Operations
### Numpy One Dimensional Array Operations
```numpy``` **operates** on arrays **element-wise** thus elementary operations are performed in an intuitive way.
```numpy``` **operates** on arrays **element-wise** thus elementary operations are performed in an intuitive way.
%% Cell type:code id:2aff9b94 tags:
%% Cell type:code id:2aff9b94 tags:
``` python
``` python
zero_array = np.zeros(10) # creates an an array of 10 zeros
zero_array = np.zeros(10) # creates an an array of 10 zeros
one_array = np.ones(10) # creates an array of... guess what!
one_array = np.ones(10) # creates an array of... guess what!
two_array = np.ones(10)*2 # this one is a bit more tricky
two_array = np.ones(10)*2 # this one is a bit more tricky
three_array = one_array + two_array # arrays are added element-wise
three_array = one_array + two_array # arrays are added element-wise
print(three_array)
print(three_array)
# You can also create numpy arrays from python lists:
# You can also create numpy arrays from python lists:
For this to work however the arrays must be of the **same shape**, otherwise a ```ValueError``` will be raised. In order to avoid this error, you can always access the shape of an array using the ```array.shape``` syntax:
For this to work however the arrays must be of the **same shape**, otherwise a ```ValueError``` will be raised. In order to avoid this error, you can always access the shape of an array using the ```array.shape``` syntax:
%% Cell type:code id:1141c56f tags:
%% Cell type:code id:1141c56f tags:
``` python
``` python
array1 = np.arange(10) # [0, 1, 2, ..., 9]
array1 = np.arange(10) # [0, 1, 2, ..., 9]
print("Shape of array1", array1.shape) # shape: (10,)
print("Shape of array1", array1.shape) # shape: (10,)
array2 = np.array([10]*5) # [10, 10, 10, 10, 10 ]
array2 = np.array([10]*5) # [10, 10, 10, 10, 10 ]
print("Shape of array2", array2.shape) # shape (5,)
print("Shape of array2", array2.shape) # shape (5,)
print(np_array1/np_array2) # Voilà ValueError due to conflicting shapes
print(np_array1/np_array2) # Voilà ValueError due to conflicting shapes
4 print("Shape of array2", array2.shape) # shape (5,)
4 print("Shape of array2", array2.shape) # shape (5,)
----> 5 print(np_array1/np_array2)
----> 5 print(np_array1/np_array2)
NameError: name 'np_array1' is not defined
NameError: name 'np_array1' is not defined
%% Cell type:markdown id:d236a438 tags:
%% Cell type:markdown id:d236a438 tags:
### Numpy Arrays of Multiple Dimensions
### Numpy Arrays of Multiple Dimensions
Numpy supports the creation of n-dimensional arrays (arrays, matrices, tensors). Let's say you wish to generate 5 normally distributed samples of size 1000 with means 0, 10, 20, 30 and 40 and standard deviation 1. For this, you can first generate 5\*1000 samples around 0, put them into a marix of shape (5, 1000) and shift each distribution to their respective means.
Numpy supports the creation of n-dimensional arrays (arrays, matrices, tensors). Let's say you wish to generate 5 normally distributed samples of size 1000 with means 0, 10, 20, 30 and 40 and standard deviation 1. For this, you can first generate 5\*1000 samples around 0, put them into a marix of shape (5, 1000) and shift each distribution to their respective means.
%% Cell type:markdown id:274853db tags:
%% Cell type:markdown id:78db6018 tags:
### Task: <a class="tocSkip">
### Task: <a class="tocSkip">
Implement the algirithm from above. Use ```array.reshape``` to reshape the dataset and create a vector of (5, 1) (eventually by using ```vector = vector[:, np.newaxis]```) which can be added to the dataset to perform the shift.
Implement the algirithm from above. Use ```array.reshape``` to reshape the dataset and create a vector of (5, 1) (eventually by using ```vector = vector[:, np.newaxis]```) which can be added to the dataset to perform the shift.
You can see the result of the expected distributions below.
You can see the result of the expected distributions below.
%% Cell type:code id:f0177d95 tags:
%% Cell type:code id:f0177d95 tags:
``` python
``` python
# TODO: Create the dataset of shape (5*1000) and reshape it to (5, 1000).
# TODO: Create the dataset of shape (5*1000) and reshape it to (5, 1000).
# TODO: Create the shift vector and reshape it to (5, 1)
# TODO: Create the shift vector and reshape it to (5, 1)
# TODO: Perform the shift and plot the result using the code below.
# TODO: Perform the shift and plot the result using the code below.
# By the way, always check the docs before inventing something "new"!
# By the way, always check the docs before inventing something "new"!
```
```
%% Output
%% Output
%% Cell type:markdown id:43f66264 tags:
%% Cell type:markdown id:43f66264 tags:
### Numpy Matrix Operations
### Numpy Matrix Operations
By default, numpy performs element-wise multiplication using the star-operator ```*```. For matrix-matrix, matrix-vector multiplications the ```@``` can be used:
By default, numpy performs element-wise multiplication using the star-operator ```*```. For matrix-matrix, matrix-vector multiplications the ```@``` can be used:
Numpy supports a powerful way of accessing entries of an array. For this purpose, ranges using ```:```, numpy arrays of integers and numpy arrays of booleans can be used:
Numpy supports a powerful way of accessing entries of an array. For this purpose, ranges using ```:```, numpy arrays of integers and numpy arrays of booleans can be used:
%% Cell type:code id:e15a8939 tags:
%% Cell type:code id:e15a8939 tags:
``` python
``` python
array_to_be_masked = np.arange(100)
array_to_be_masked = np.arange(100)
# Let's select the entries between index 20 and 30:
# Let's select the entries between index 20 and 30:
print(array_to_be_masked[20:30])
print(array_to_be_masked[20:30])
# First 10 entries:
# First 10 entries:
print(array_to_be_masked[:10])
print(array_to_be_masked[:10])
# Print the last 5 elements:
# Print the last 5 elements:
print(array_to_be_masked[-5:])
print(array_to_be_masked[-5:])
# Print the 10th, 13th and 21st elements:
# Print the 10th, 13th and 21st elements:
print(array_to_be_masked[np.array([10, 13, 21])])
print(array_to_be_masked[np.array([10, 13, 21])])
```
```
%% Output
%% Output
[20 21 22 23 24 25 26 27 28 29]
[20 21 22 23 24 25 26 27 28 29]
[0 1 2 3 4 5 6 7 8 9]
[0 1 2 3 4 5 6 7 8 9]
[95 96 97 98 99]
[95 96 97 98 99]
[10 13 21]
[10 13 21]
%% Cell type:code id:739732e5 tags:
%% Cell type:code id:2af74b4a tags:
``` python
``` python
# Let's shuffle the elements and reshape the array to make things more complicated!
# Let's shuffle the elements and reshape the array to make things more complicated!
np.random.shuffle(array_to_be_masked)
np.random.shuffle(array_to_be_masked)
array_to_be_masked = array_to_be_masked.reshape((25, -1)) # "-1" means "do whatever needed to get the right shape"
array_to_be_masked = array_to_be_masked.reshape((25, -1)) # "-1" means "do whatever needed to get the right shape"
"**Conversion** from and to ```numpy``` is also supported in an intuitive way:"
"**Conversion** from and to ```numpy``` is also supported in an intuitive way:"
...
@@ -123,7 +123,7 @@
...
@@ -123,7 +123,7 @@
{
{
"cell_type": "code",
"cell_type": "code",
"execution_count": 5,
"execution_count": 5,
"id": "4ff55ee1",
"id": "c285066e",
"metadata": {},
"metadata": {},
"outputs": [
"outputs": [
{
{
...
@@ -157,7 +157,7 @@
...
@@ -157,7 +157,7 @@
{
{
"cell_type": "code",
"cell_type": "code",
"execution_count": 6,
"execution_count": 6,
"id": "b41c3f17",
"id": "bf9b99ed",
"metadata": {},
"metadata": {},
"outputs": [
"outputs": [
{
{
...
@@ -198,7 +198,7 @@
...
@@ -198,7 +198,7 @@
},
},
{
{
"cell_type": "markdown",
"cell_type": "markdown",
"id": "c7392c21",
"id": "4f283cd2",
"metadata": {},
"metadata": {},
"source": [
"source": [
" A key **difference in syntax** however is that ```pytorch``` knows the ```axis``` keyword as ```dim```:"
" A key **difference in syntax** however is that ```pytorch``` knows the ```axis``` keyword as ```dim```:"
...
@@ -207,7 +207,7 @@
...
@@ -207,7 +207,7 @@
{
{
"cell_type": "code",
"cell_type": "code",
"execution_count": 7,
"execution_count": 7,
"id": "ae7c557f",
"id": "3fe72fbc",
"metadata": {},
"metadata": {},
"outputs": [
"outputs": [
{
{
...
@@ -233,18 +233,18 @@
...
@@ -233,18 +233,18 @@
},
},
{
{
"cell_type": "markdown",
"cell_type": "markdown",
"id": "cd7f9110",
"id": "f01db24d",
"metadata": {},
"metadata": {},
"source": [
"source": [
"### Task <a class=\"tocSkip\">\n",
"### Task <a class=\"tocSkip\">\n",
"Implement the mean-square difference function in pytorch:\n",
"Implement the mean-square difference function in pytorch:\n",
" $$ L(x, y) = \\sum_i \\frac{(x_i-y_i)^2}{N}$$"
"$ L(x, y) = \\sum_i \\frac{(x_i-y_i)^2}{N}$"
]
]
},
},
{
{
"cell_type": "code",
"cell_type": "code",
"execution_count": 8,
"execution_count": 8,
"id": "8e87425d",
"id": "d674de00",
"metadata": {},
"metadata": {},
"outputs": [
"outputs": [
{
{
...
...
%% Cell type:markdown id:3881ec5d tags:
%% Cell type:markdown id:3881ec5d tags:
# PyTorch Tutorial
# PyTorch Tutorial
---------------
---------------
Welcome to the pytorch tutorial! Here we will go through some of the basics of pytorch.
Welcome to the pytorch tutorial! Here we will go through some of the basics of pytorch.
The library can be imported the as ```torch```:
The library can be imported the as ```torch```:
%% Cell type:code id:e812c4c3 tags:
%% Cell type:code id:e812c4c3 tags:
``` python
``` python
importtorch
importtorch
```
```
%% Cell type:markdown id:232eb87a tags:
%% Cell type:markdown id:232eb87a tags:
## Tensors
## Tensors
Even if the name ```pytorch``` is not as telling as ```tensorflow```, ```pytorch``` supports the creation of tensors too:
Even if the name ```pytorch``` is not as telling as ```tensorflow```, ```pytorch``` supports the creation of tensors too:
%% Cell type:code id:da356762 tags:
%% Cell type:code id:da356762 tags:
``` python
``` python
tensor=torch.tensor([1.,5.,9.,15.,-24.,-13.])
tensor=torch.tensor([1.,5.,9.,15.,-24.,-13.])
print(tensor)
print(tensor)
```
```
%% Output
%% Output
tensor([ 1., 5., 9., 15., -24., -13.])
tensor([ 1., 5., 9., 15., -24., -13.])
%% Cell type:markdown id:5ab59c06 tags:
%% Cell type:markdown id:5ab59c06 tags:
These objects can both **store data and model parameters** (recall that in tensorflow ```tf.Variable``` is a child class of ```tf.Tensor``` and used for storing weights). To check whether a tensor is storing gradients, one can use the ```requires_grad``` attribute:
These objects can both **store data and model parameters** (recall that in tensorflow ```tf.Variable``` is a child class of ```tf.Tensor``` and used for storing weights). To check whether a tensor is storing gradients, one can use the ```requires_grad``` attribute:
%% Cell type:code id:0e83bc87 tags:
%% Cell type:code id:0e83bc87 tags:
``` python
``` python
print(tensor.requires_grad)
print(tensor.requires_grad)
```
```
%% Output
%% Output
False
False
%% Cell type:markdown id:318a84d9 tags:
%% Cell type:markdown id:318a84d9 tags:
To initialize a **tensor with gradients** one can use the ```requires_grad``` keyword during initialization; this creates the rough equivalent of a ```tf.Variable```. To obtain the gradients, ```.backward()``` has to be called on the output object:
To initialize a **tensor with gradients** one can use the ```requires_grad``` keyword during initialization; this creates the rough equivalent of a ```tf.Variable```. To obtain the gradients, ```.backward()``` has to be called on the output object:
"Implement the mean-square difference function in tensorflow:\n",
"Implement the mean-square difference function in tensorflow:\n",
" $$ L(x, y) = \\sum_i \\frac{(x_i-y_i)^2}{N}$$"
"$ L(x, y) = \\sum_i \\frac{(x_i-y_i)^2}{N}$"
]
]
},
},
{
{
"cell_type": "code",
"cell_type": "code",
"execution_count": 8,
"execution_count": 8,
"id": "7aec09c9",
"id": "d925efd7",
"metadata": {},
"metadata": {},
"outputs": [
"outputs": [
{
{
...
...
%% Cell type:markdown id:269d507c tags:
%% Cell type:markdown id:269d507c tags:
# Tensorflow Tutorial
# Tensorflow Tutorial
---------------------------------
---------------------------------
Welcome to the Tesorflow tutorial! Here we are going to go through the most fundamental functions and the syntax of the library.
Welcome to the Tesorflow tutorial! Here we are going to go through the most fundamental functions and the syntax of the library.
Usually, tensorflow is imported as ``` tf```:
Usually, tensorflow is imported as ``` tf```:
%% Cell type:code id:fb7e3964 tags:
%% Cell type:code id:fb7e3964 tags:
``` python
``` python
importtensorflowastf
importtensorflowastf
```
```
%% Cell type:markdown id:ffc59cef tags:
%% Cell type:markdown id:ffc59cef tags:
## Tensors
## Tensors
One can create tensors in tensorflow using a **syntax similar to** that of **numpy**. These objects are considered to be constants by the library and hence **cannot be modified**; each operation on these objects returns a new tensor object.
One can create tensors in tensorflow using a **syntax similar to** that of **numpy**. These objects are considered to be constants by the library and hence **cannot be modified**; each operation on these objects returns a new tensor object.
You can find some examples of tensor creation below:
You can find some examples of tensor creation below:
%% Cell type:code id:e776d989 tags:
%% Cell type:code id:e776d989 tags:
``` python
``` python
t1=tf.zeros([5])# Zeros of length 5 (note the necessary squared brackets)
t1=tf.zeros([5])# Zeros of length 5 (note the necessary squared brackets)
t2=tf.ones([3,2])# Array of ones of shape (3, 2)
t2=tf.ones([3,2])# Array of ones of shape (3, 2)
t3=tf.random.uniform([2,3])# Random sampling from the interval [0, 1) as a shape (2, 3)
t3=tf.random.uniform([2,3])# Random sampling from the interval [0, 1) as a shape (2, 3)
t4=tf.linspace(1,7,4)# Create a tensor of linear spacing from 1 to 7 with 4 entries
t4=tf.linspace(1,7,4)# Create a tensor of linear spacing from 1 to 7 with 4 entries
2022-08-02 16:29:05.625051: I tensorflow/compiler/jit/xla_cpu_device.cc:41] Not creating XLA devices, tf_xla_enable_xla_devices not set
2022-08-02 16:29:05.625051: I tensorflow/compiler/jit/xla_cpu_device.cc:41] Not creating XLA devices, tf_xla_enable_xla_devices not set
2022-08-02 16:29:05.626364: I tensorflow/core/platform/cpu_feature_guard.cc:142] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN) to use the following CPU instructions in performance-critical operations: SSE4.1 SSE4.2 AVX
2022-08-02 16:29:05.626364: I tensorflow/core/platform/cpu_feature_guard.cc:142] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN) to use the following CPU instructions in performance-critical operations: SSE4.1 SSE4.2 AVX
To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.
To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.
2022-08-02 16:29:05.629373: I tensorflow/core/common_runtime/process_util.cc:146] Creating new thread pool with default inter op setting: 2. Tune using inter_op_parallelism_threads for best performance.
2022-08-02 16:29:05.629373: I tensorflow/core/common_runtime/process_util.cc:146] Creating new thread pool with default inter op setting: 2. Tune using inter_op_parallelism_threads for best performance.
%% Cell type:markdown id:33a5ef69 tags:
%% Cell type:markdown id:33a5ef69 tags:
You can **transform** a tensor **to a numpy array** using ```tensor.numpy()```:
You can **transform** a tensor **to a numpy array** using ```tensor.numpy()```:
%% Cell type:code id:0b576f35 tags:
%% Cell type:code id:0b576f35 tags:
``` python
``` python
print(t3.numpy())# Conversion to numpy
print(t3.numpy())# Conversion to numpy
print(type(t3.numpy()))# Printing the type of the converted array
print(type(t3.numpy()))# Printing the type of the converted array
```
```
%% Output
%% Output
[[0.6397505 0.4475379 0.7460896 ]
[[0.6397505 0.4475379 0.7460896 ]
[0.40134668 0.6757213 0.14884555]]
[0.40134668 0.6757213 0.14884555]]
<class 'numpy.ndarray'>
<class 'numpy.ndarray'>
%% Cell type:markdown id:f904ef1e tags:
%% Cell type:markdown id:f904ef1e tags:
## Variables
## Variables
On the other hand, ```Variables``` (based on tensors) are objects which are **updated during training** through backpropagation. Each tensorflow variable has to be initialized and their values can be changed using ```variable.assign(new_values)```:
On the other hand, ```Variables``` (based on tensors) are objects which are **updated during training** through backpropagation. Each tensorflow variable has to be initialized and their values can be changed using ```variable.assign(new_values)```:
%% Cell type:code id:a70aa763 tags:
%% Cell type:code id:a70aa763 tags:
``` python
``` python
w=tf.Variable(tf.zeros([3,2]))# Create an empty variable w
w=tf.Variable(tf.zeros([3,2]))# Create an empty variable w
print("w = %s"%w)# ...which has zeros only by default
print("w = %s"%w)# ...which has zeros only by default
w.assign(tf.ones([3,2]))# Assign new values to w
w.assign(tf.ones([3,2]))# Assign new values to w
print("w = %s"%w)# ... and retrieve them
print("w = %s"%w)# ... and retrieve them
```
```
%% Output
%% Output
w = <tf.Variable 'Variable:0' shape=(3, 2) dtype=float32, numpy=
w = <tf.Variable 'Variable:0' shape=(3, 2) dtype=float32, numpy=
array([[0., 0.],
array([[0., 0.],
[0., 0.],
[0., 0.],
[0., 0.]], dtype=float32)>
[0., 0.]], dtype=float32)>
w = <tf.Variable 'Variable:0' shape=(3, 2) dtype=float32, numpy=
w = <tf.Variable 'Variable:0' shape=(3, 2) dtype=float32, numpy=
array([[1., 1.],
array([[1., 1.],
[1., 1.],
[1., 1.],
[1., 1.]], dtype=float32)>
[1., 1.]], dtype=float32)>
%% Cell type:markdown id:11af2105 tags:
%% Cell type:markdown id:11af2105 tags:
## Fundamental Mathematical Operations
## Fundamental Mathematical Operations
Tensorflow supports several basic maths functions out of the box. Compared to numpy, **some operations run by the name**```reduce_operation(*args)``` like ```reduce_sum``` and ```reduce_mean```.
Tensorflow supports several basic maths functions out of the box. Compared to numpy, **some operations run by the name**```reduce_operation(*args)``` like ```reduce_sum``` and ```reduce_mean```.
You can find an incomplete list of some basic calls:
You can find an incomplete list of some basic calls:
%% Cell type:code id:367e4ba0 tags:
%% Cell type:code id:367e4ba0 tags:
``` python
``` python
x=tf.linspace(0.,4.,5)# Create a tensor array
x=tf.linspace(0.,4.,5)# Create a tensor array
print("x =",x)
print("x =",x)
print("(x+1)**2 - 2) =",(x+1.)**2-2.)
print("(x+1)**2 - 2) =",(x+1.)**2-2.)
print("sin(x)",tf.sin(x))
print("sin(x)",tf.sin(x))
print("sum(x)",tf.reduce_sum(x))
print("sum(x)",tf.reduce_sum(x))
print("mean(x)",tf.reduce_mean(x))
print("mean(x)",tf.reduce_mean(x))
```
```
%% Output
%% Output
x = tf.Tensor([0. 1. 2. 3. 4.], shape=(5,), dtype=float32)
x = tf.Tensor([0. 1. 2. 3. 4.], shape=(5,), dtype=float32)