├── .coveragerc ├── .editorconfig ├── .gitignore ├── .pre-commit-config.yaml ├── .travis.yml ├── LICENSE ├── MANIFEST.in ├── PACKAGE.rst ├── Pipfile ├── Pipfile.lock ├── README.md ├── datasets_example.py ├── deeplearning2020 ├── __init__.py ├── datasets.py ├── helpers.py └── submission.py ├── example.py ├── setup.cfg ├── setup.py ├── tasks.py ├── tests └── test_deeplearning2020.py ├── tox.ini ├── woche1 ├── README.md ├── bonus │ ├── bonus.md │ ├── solution_backpropagation.png │ └── solution_feed_forward.png └── installation │ ├── README.md │ ├── linux.md │ ├── mac.md │ └── windows.md ├── woche2 ├── README.md ├── assignment │ ├── Fashion_MNIST_simple_solution.ipynb │ └── README.md └── notebooks │ ├── exploring-mnist │ ├── README.md │ └── exploring-mnist.ipynb │ ├── first-mnist-net │ ├── README.md │ ├── mnist-commented-solution.ipynb │ └── mnist-state-of-the-art.ipynb │ ├── intro-matplotlib │ ├── README.md │ └── intro-matplotlib.ipynb │ ├── intro-numpy │ ├── README.md │ └── intro-numpy.ipynb │ ├── intro-tensorflow-keras │ ├── README.md │ └── intro-tensorflow-keras.ipynb │ └── mnist-activation-functions │ ├── README.md │ └── mnist-activation-functions.ipynb ├── woche3 ├── README.md ├── assignment │ ├── additional │ │ └── README.md │ └── exercise2 │ │ ├── Exercise_2_solution_transfer_learning.ipynb │ │ ├── Exercise_2_solution_week_3.ipynb │ │ ├── Exercise_2_solution_week_3_with_less_parameter.ipynb │ │ └── README.md ├── notebooks │ ├── complex-layer-structure │ │ ├── README.md │ │ └── complex-layer-structure.ipynb │ ├── hyperparameter │ │ ├── README.md │ │ ├── hyperparameter-network-depth.ipynb │ │ └── hyperparameter.ipynb │ ├── loss-functions │ │ ├── README.md │ │ ├── loss-functions-imagenette.ipynb │ │ └── loss-functions.ipynb │ └── optimizer │ │ ├── README.md │ │ ├── optimizer-imagenette.ipynb │ │ └── optimizer.ipynb └── scratch-net │ ├── README.md │ ├── scratchNet_full_commented_solution.ipynb │ ├── scratchNet_full_uncommented_solution.ipynb │ └── scratchNet_partial_commented_solution.ipynb └── woche4 ├── README.md ├── assignment ├── additional │ └── README.md └── exercise2 │ ├── Exercise_2_solution_transfer_learning.ipynb │ ├── Exercise_2_solution_week_3.ipynb │ ├── Exercise_2_solution_week_3_with_less_parameter.ipynb │ └── README.md ├── gan ├── README.md └── exkurs-gan.ipynb └── notebooks ├── automated-machine-learning ├── README.md └── automated-machine-learning.ipynb ├── batch-normalization ├── README.md └── batch-normalization.ipynb ├── dropout ├── README.md └── dropout.ipynb ├── hyperparameter-optimization ├── README.md └── hyperparameter-optimization.ipynb ├── regularization-techniques ├── README.md ├── data-augmentation.ipynb └── summary-regularization-techniques.ipynb └── transfer-learning ├── README.md └── transfer-learning.ipynb /.coveragerc: -------------------------------------------------------------------------------- 1 | [run] 2 | source = deeplearning2020 3 | omit = 4 | .tox 5 | tests 6 | tasks.py 7 | setup.py 8 | deeplearning2020/helpers.py 9 | deeplearning2020/datasets.py 10 | 11 | [report] 12 | exclude_lines = 13 | # Have to re-enable the standard pragma 14 | pragma: no cover 15 | 16 | # Don't complain about missing debug-only code: 17 | def __repr__ 18 | if self\.debug 19 | 20 | # Don't complain if tests don't hit defensive assertion code: 21 | raise AssertionError 22 | raise NotImplementedError 23 | 24 | # Don't complain if non-runnable code isn't run: 25 | if 0: 26 | if __name__ == .__main__.: 27 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | # http://editorconfig.org 2 | 3 | root = true 4 | 5 | [*] 6 | indent_style = space 7 | indent_size = 4 8 | trim_trailing_whitespace = true 9 | insert_final_newline = true 10 | charset = utf-8 11 | end_of_line = lf 12 | 13 | [*.bat] 14 | indent_style = tab 15 | end_of_line = crlf 16 | 17 | [LICENSE] 18 | insert_final_newline = false 19 | 20 | [Makefile] 21 | indent_style = tab 22 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | .idea/ 3 | .vscode/ 4 | 5 | # Byte-compiled / optimized / DLL files 6 | __pycache__/ 7 | *.py[cod] 8 | *$py.class 9 | 10 | # C extensions 11 | *.so 12 | 13 | # Distribution / packaging 14 | .Python 15 | env/ 16 | build/ 17 | develop-eggs/ 18 | dist/ 19 | downloads/ 20 | eggs/ 21 | .eggs/ 22 | lib/ 23 | lib64/ 24 | parts/ 25 | sdist/ 26 | var/ 27 | wheels/ 28 | *.egg-info/ 29 | .installed.cfg 30 | *.egg 31 | 32 | # PyInstaller 33 | # Usually these files are written by a python script from a template 34 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 35 | *.manifest 36 | *.spec 37 | 38 | # Installer logs 39 | pip-log.txt 40 | pip-delete-this-directory.txt 41 | 42 | # Unit test / coverage reports 43 | htmlcov/ 44 | .tox/ 45 | .coverage 46 | .coverage.* 47 | .cache 48 | nosetests.xml 49 | coverage.xml 50 | *.cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | 62 | # Flask stuff: 63 | instance/ 64 | .webassets-cache 65 | 66 | # Scrapy stuff: 67 | .scrapy 68 | 69 | # Sphinx documentation 70 | docs/_build/ 71 | 72 | # PyBuilder 73 | target/ 74 | 75 | # Jupyter Notebook 76 | .ipynb_checkpoints 77 | 78 | # pyenv 79 | .python-version 80 | 81 | # celery beat schedule file 82 | celerybeat-schedule 83 | 84 | # SageMath parsed files 85 | *.sage.py 86 | 87 | # dotenv 88 | .env 89 | 90 | # virtualenv 91 | .venv 92 | venv/ 93 | ENV/ 94 | 95 | # Spyder project settings 96 | .spyderproject 97 | .spyproject 98 | 99 | # Rope project settings 100 | .ropeproject 101 | 102 | # mkdocs documentation 103 | /site 104 | 105 | # mypy 106 | .mypy_cache/ 107 | -------------------------------------------------------------------------------- /.pre-commit-config.yaml: -------------------------------------------------------------------------------- 1 | # See https://pre-commit.com/ for usage and config 2 | repos: 3 | - repo: local 4 | hooks: 5 | - id: format 6 | name: format 7 | stages: [commit] 8 | language: system 9 | entry: pipenv run invoke format 10 | pass_filenames: false 11 | types: [python] 12 | 13 | - id: lint 14 | name: lint 15 | stages: [commit] 16 | language: system 17 | entry: pipenv run invoke lint 18 | pass_filenames: false 19 | types: [python] 20 | 21 | - id: type-check 22 | name: type-check 23 | stages: [commit] 24 | language: system 25 | entry: pipenv run invoke type-check 26 | pass_filenames: false 27 | types: [python] 28 | 29 | - id: test 30 | name: test 31 | stages: [commit] 32 | language: system 33 | entry: pipenv run invoke test --min-coverage=80 34 | pass_filenames: false 35 | types: [python] 36 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: python 2 | os: linux 3 | install: pip install --no-cache-dir -U tox-travis 4 | script: tox 5 | python: 6 | - 3.7 7 | - 3.6 8 | jobs: 9 | include: 10 | - stage: test 11 | name: Measure code coverage 12 | install: pip install --no-cache-dir -U tox-travis 13 | script: tox -e codecov 14 | python: 3.6 15 | - stage: deploy 16 | name: Deploy to PyPI 17 | script: pip install --no-cache-dir -e . 18 | python: 3.6 19 | deploy: 20 | provider: pypi 21 | username: __token__ 22 | skip_cleanup: true 23 | password: 24 | secure: uRDrcszYXEcMu0rESk38WGQ1x/gZo1IUxVUJwUUErT++v8bw99F8g7ZZQtLgUms6MVVlBJi0HSuPSWyfTfSh+uNwIzBs+d5Msxj81h4qJsJuZX8+ncv8Mhi4/PuWQK++mNi5ONBMdUVAcpfaT2oCTgvJ18klR3xIiWeYZaMQAw4O07NBMORlTQp4RVQyJMIeduGCeftEa5nCED0b7NrgEBpX/GF4QLSz3G5ubc7DSLgAf/sobxLscaYDx9FcL2mr/Lwns5jAAwNgLmEXz/8nldRA65s0baAa5kW/EV8vZcxyiWUDZtZcjEL2F61KZ0b8eGF5VG73KHWwf/929YZY7O0saA1qxAD4/YKVQ4bVUb3KYDHVrZu0WsvtyceFqcuBSeT+JoLnK9aOuBQ+kfMUdYqv5ww0DpNzeD8JB3aJNvXhWTad0C96nLzZZ+dC8hh5c4ehy67sc2tANsWAL+6IEgdNZzKhpzKU925947x0GtZbl+M7xf9kvulyg6/YEfKHxKVdd5GY/c++XS+w+5E53Dl/I/t2BhLFqIG6D0P1agtiQb79xngXH1/7j4Ss1mos7j+3nk2fQ9mH4ODtLUBrAqPd6pJxPv5TV//6V/VJghHTYBIdxz5oyr59BOX+GHLomn+k9T9SK8klcNyZozJVCkHcJ+wO7LHx8xjr67JxlLI= 25 | on: 26 | tags: true 27 | python: 3.6 28 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020, into-ai 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include LICENSE 2 | include PACKAGE.rst 3 | 4 | recursive-include tests * 5 | recursive-exclude * __pycache__ 6 | recursive-exclude * *.py[co] 7 | 8 | recursive-include docs *.rst conf.py *.jpg *.png *.gif 9 | -------------------------------------------------------------------------------- /PACKAGE.rst: -------------------------------------------------------------------------------- 1 | =============================== 2 | deeplearning2020 3 | =============================== 4 | 5 | .. image:: https://travis-ci.com/into-ai/deeplearning2020.svg?branch=master 6 | :target: https://travis-ci.com/into-ai/deeplearning2020 7 | :alt: Build Status 8 | 9 | .. image:: https://img.shields.io/pypi/v/deeplearning2020.svg 10 | :target: https://pypi.python.org/pypi/deeplearning2020 11 | :alt: PyPI version 12 | 13 | .. image:: https://img.shields.io/github/license/into-ai/deeplearning2020 14 | :target: https://github.com/into-ai/deeplearning2020 15 | :alt: License 16 | 17 | .. image:: https://codecov.io/gh/into-ai/deeplearning2020/branch/master/graph/badge.svg 18 | :target: https://codecov.io/gh/into-ai/deeplearning2020 19 | :alt: Test Coverage 20 | 21 | """""""" 22 | 23 | Begleitendes Python Package zum Kurs `Eine praktische Einführung in Deep Learning für Computer Vision `_ auf `OpenHPI `_. 24 | 25 | .. code-block:: console 26 | 27 | $ pip install --upgrade deeplearning2020 28 | 29 | In einem ``jupyter notebook`` wie Google Colab geht das mit 30 | 31 | .. code-block:: python 32 | 33 | !pip install --upgrade deeplearning2020 34 | 35 | Das Package enthält einige von uns bereitgestellte Hilfsfunktionen und erlaubt es euch, eure für die Übungen trainierten `keras` Modelle zur Bewertung abzugeben. 36 | 37 | Nutzung der Hilfsfunktionen 38 | ------------------------------ 39 | 40 | .. code-block:: python 41 | 42 | from deeplearning2020 import helpers 43 | helpers.plot_predictions(...) # Beispiel 44 | 45 | Nutzung zur Übungsabgabe 46 | ------------------------------ 47 | 48 | .. code-block:: python 49 | 50 | from deeplearning2020 import Submission 51 | Submission('', '', model).submit() 52 | 53 | Der ```` und die ```` wird dir für die Abgabe mitgeteilt. -------------------------------------------------------------------------------- /Pipfile: -------------------------------------------------------------------------------- 1 | [[source]] 2 | url = "https://pypi.org/simple" 3 | verify_ssl = true 4 | name = "pypi" 5 | 6 | [dev-packages] 7 | # Formatting 8 | flake8 = "*" 9 | black = "==19.10b0" 10 | isort = "*" 11 | # Testing 12 | tox = "*" 13 | pytest = "*" 14 | pytest-cov = "*" 15 | pytest-xdist = "*" 16 | pytest-sugar = "*" 17 | pyfakefs = "*" 18 | mypy = "*" 19 | # Coverage 20 | coverage = "*" 21 | codecov = "*" 22 | # Tools 23 | pre-commit = "*" 24 | invoke = "*" 25 | "ruamel.yaml" = "*" 26 | twine = "*" 27 | bump2version = "*" 28 | keras = "*" 29 | tensorflow = "*" 30 | 31 | [packages] 32 | deeplearning2020 = {path = ".",editable = true} 33 | kerasltisubmission = ">=0.4.9" 34 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## OpenHPI Deeplearning 2020 2 | 3 | [![Build Status](https://travis-ci.com/into-ai/deeplearning2020.svg?branch=master)](https://travis-ci.com/into-ai/deeplearning2020) 4 | [![PyPI version](https://img.shields.io/pypi/v/deeplearning2020.svg)](https://pypi.python.org/pypi/deeplearning2020) 5 | 6 | ------------------------------ 7 | 8 | Materialien zum Kurs [Eine praktische Einführung in Deep Learning für Computer Vision](https://open.hpi.de/courses/neuralnets2020) auf [OpenHPI](https://open.hpi.de/). 9 | 10 | ### Inhaltsverzeichnis 11 | 12 | - [Wie nutze ich das GitHub Repository?](#wie-nutze-ich-dieses-github-repository) 13 | - Woche 1 14 | - [Bonusaufgabe: Backpropagation selber nachvollziehen](woche1/bonus.md) 15 | - [Exkurs: Lokale Installation ](woche1/installation/) 16 | - [Linux](woche1/installation/linux.md) 17 | - [macOS](woche1/installation/mac.md) 18 | - [Windows](woche1/installation/windows.md) 19 | - Woche 2 20 | - [Notebooks](woche2/notebooks/) 21 | - [Einführung in Numpy](woche2/notebooks/intro-numpy/) 22 | - [Einführung in Matplotlib](woche2/notebooks/intro-matplotlib/) 23 | - [Laden und Bearbeiten des MNIST Datensatz](woche2/notebooks/exploring-mnist) 24 | - [MNIST Vergleich Aktivierungsfunktionen](woche2/notebooks/mnist-activation-functions/) 25 | - [Einführung in Tensorflow / Keras](woche2/notebooks/intro-tensorflow-keras/) 26 | - [Beispiel: Trainieren eines Netzes für MNIST](woche2/notebooks/first-mnist-net/) 27 | - [Praktische Übung](woche2/assignment/) 28 | - Woche 3 29 | - [Notebooks](woche3/notebooks/) 30 | - [Komplexe Layerstruktur](woche3/notebooks/complex-layer-structure/) 31 | - [Loss Functions](woche3/notebooks/loss-functions/) 32 | - [Optimizer](woche3/notebooks/optimizer/) 33 | - [Hyperparameter](woche3/notebooks/hyperparameter/) 34 | - [Exkurs: Neuronale Netze von Scratch](woche3/scratch-net) 35 | - [Praktische Übung](woche3/assignment/) 36 | - [Bewertete Übung](woche3/assignment/week3&4/) 37 | - [Zusätzliche Übung](woche3/assignment/additional/) 38 | - Woche 4 39 | - [Notebooks](woche4/notebooks/) 40 | - [Optimierung Hyperparameter](woche4/notebooks/hyperparameter-optimization/) 41 | - [Dropout](woche4/notebooks/dropout/) 42 | - [Batch Normalization](woche4/notebooks/batch-normalization/) 43 | - [Regularisierungstechniken (wie Data Augmentation)](woche4/notebooks/regularization-techniques/) 44 | - [Transfer Learning](woche4/notebooks/transfer-learning/) 45 | - [Automated Machine Learning](woche4/notebooks/automated-machine-learning/) 46 | - [Exkurs GAN](woche4/gan/) 47 | 48 | ### Wie nutze ich dieses GitHub Repository? 49 | 50 | Dieses Repository dient als Ort für Materialien zu diesem Kurs. Du benötigst kein GitHub Account und musst das Repository auch nicht verwenden, da sich die wichtigen Materialien auch auf [OpenHPI](https://open.hpi.de/) finden lassen. 51 | 52 | Du kannst das Repository auf zwei verschiedene Arten verwenden: 53 | 1. Du kannst dir die Materialien, die du oben im Inhaltsverzeichnis findest online anschauen, daraus kopieren oder Dateien herunterladen. Du kannst auch das gesamte Repository als ZIP herunterladen. Falls du `.ipynb`-Notebooks herunterlädst kannst du diese dann mit deinem `jupyter notebook` Server öffnen, indem du im Browserfenster des Server zu dieser Datei navigierst und sie öffnest. 54 | 55 | 2. Du kannst das Repository mit 56 | ```bash 57 | git clone https://github.com/into-ai/deeplearning2020.git 58 | ``` 59 | *klonen*. Damit hast du das Repository ebenfalls lokal, aber kannst es außerdem mit 60 | ```bash 61 | git pull origin master 62 | ``` 63 | aktualisieren, sobald neue Inhalte verfügbar werden. Das Öffnen von Notebooks funktioniert genauso wie in Variante 1. Wir empfehlen diesen Workflow aber nur denjenigen, die sich bereits ein bisschen mit `git` auskennen oder sich [hier](https://git-scm.com/doc) einlesen wollen. 64 | -------------------------------------------------------------------------------- /datasets_example.py: -------------------------------------------------------------------------------- 1 | from deeplearning2020.datasets import ImageWoof 2 | 3 | train_data, test_data, classes = ImageWoof.load_data() 4 | 5 | print(f"Classes: ", classes) 6 | 7 | for sample in train_data.take(1): # Only take a single example 8 | image, label = sample 9 | print(image, label) 10 | -------------------------------------------------------------------------------- /deeplearning2020/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | """Top-level package for deeplearning2020.""" 4 | 5 | __author__ = """into-ai""" 6 | __email__ = "introintoai@gmail.com" 7 | __version__ = "0.4.21" 8 | 9 | from deeplearning2020.submission import Submission as _Submission 10 | 11 | Submission = _Submission 12 | -------------------------------------------------------------------------------- /deeplearning2020/datasets.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import, division, print_function, unicode_literals 2 | 3 | import os 4 | import pathlib 5 | import typing 6 | from typing import TYPE_CHECKING 7 | 8 | import numpy as np 9 | 10 | if TYPE_CHECKING: # pragma: no cover 11 | import tensorflow as _tf 12 | 13 | try: 14 | import tensorflow as tf 15 | 16 | assert tf.__version__[:2] == "2." 17 | except ImportError: 18 | raise ImportError( 19 | 'Das Dataset erfordert tensorflow 2! Lokal geht das mit "conda install tensorflow>=2.0.0" oder "pip install tensorflow>=2.0.0"' 20 | ) 21 | except AssertionError: 22 | raise ImportError( 23 | 'Das Dataset erfordert tensorflow 2! In Colab kannst du dies mit dem "%tensorflow_version 2.x" Befehl erzwingen. Anschliessend musst du die Runtime restarten. Schaue dir dazu am Besten nochmal die Beispiel Notebooks aus dieser Woche an!' 24 | ) 25 | 26 | AUTOTUNE = tf.data.experimental.AUTOTUNE 27 | 28 | """ 29 | The imagewoof dataset is provided by FastAI 30 | 31 | author = "Jeremy Howard", 32 | title = "imagenette", 33 | url = "https://github.com/fastai/imagenette/" 34 | """ 35 | 36 | 37 | ImageWoofType = typing.TypeVar("ImageWoofType", bound="ImageWoof") 38 | 39 | 40 | class ImageWoof: 41 | BATCH_SIZE: int = 32 42 | CLASS_NAMES: np.ndarray = None 43 | data_dir: pathlib.Path 44 | image_count: int = 0 45 | list_ds: "_tf.data.Dataset" = None 46 | 47 | def __init__(self, dataset: str) -> None: 48 | if dataset not in ["train", "val"]: 49 | raise ValueError("Dataset not found") 50 | 51 | file_path = tf.keras.utils.get_file( 52 | origin="https://s3.amazonaws.com/fast-ai-imageclas/imagewoof2-320.tgz", 53 | fname="imagewoof", 54 | untar=True, 55 | ) 56 | self.data_dir = pathlib.Path(file_path + "2-320/" + dataset) 57 | print(self.data_dir) 58 | self.image_count = len(list(self.data_dir.glob("*/*.JPEG"))) 59 | print(f"Loaded {self.image_count} images") 60 | 61 | self.raw_class_names = [ 62 | item.name for item in self.data_dir.glob("*") if item.name != "LICENSE.txt" 63 | ] 64 | self.raw_class_names.sort() 65 | 66 | self.class_name_mapping = dict( 67 | n02096294="Australian terrier", 68 | n02093754="Border terrier", 69 | n02111889="Samoyed", 70 | n02088364="Beagle", 71 | n02086240="Shih-Tzu", 72 | n02089973="English foxhound", 73 | n02087394="Rhodesian ridgeback", 74 | n02115641="Dingo", 75 | n02099601="Golden retriever", 76 | n02105641="Old English sheepdog", 77 | ) 78 | 79 | self.CLASS_NAMES = np.array([self.map_class(c) for c in self.raw_class_names]) 80 | self.list_ds = tf.data.Dataset.list_files(str(self.data_dir / "*/*")) 81 | 82 | @classmethod 83 | def train(cls: typing.Type[ImageWoofType]) -> ImageWoofType: 84 | return cls("train") 85 | 86 | @classmethod 87 | def validation(cls: typing.Type[ImageWoofType]) -> ImageWoofType: 88 | return cls("val") 89 | 90 | def map_class(self, raw_cls: str) -> str: 91 | return self.class_name_mapping[raw_cls] 92 | 93 | def get_label(self, file_path: str) -> "_tf.Tensor": 94 | # convert the path to a list of path components 95 | parts = tf.strings.split(file_path, os.path.sep) 96 | # The second to last is the class-directory 97 | label = parts[-2] == self.raw_class_names 98 | label = tf.reduce_sum(tf.where(label)) 99 | return label 100 | 101 | def decode_img(self, img: "_tf.Tensor") -> "_tf.Tensor": 102 | # convert the compressed string to a 3D uint8 tensor 103 | img = tf.image.decode_jpeg(img, channels=3) 104 | # Use `convert_image_dtype` to convert to floats in the [0,1] range. 105 | return tf.image.convert_image_dtype(img, tf.float32) 106 | 107 | def process_path(self, file_path: str) -> typing.Tuple["_tf.Tensor", str]: 108 | label = self.get_label(file_path) 109 | # load the raw data from the file as a string 110 | img: "_tf.Tensor" = tf.io.read_file(file_path) 111 | img = self.decode_img(img) 112 | return img, label 113 | 114 | def wrapped_load_data(self) -> "_tf.data.Dataset": 115 | return self.list_ds.map(self.process_path, num_parallel_calls=AUTOTUNE) 116 | 117 | @classmethod 118 | def load_data( 119 | cls: typing.Type[ImageWoofType], 120 | ) -> typing.Tuple["_tf.data.Dataset", "_tf.data.Dataset", np.ndarray]: 121 | train_ds = cls.train() 122 | return ( 123 | train_ds.wrapped_load_data(), 124 | cls.validation().wrapped_load_data(), 125 | train_ds.CLASS_NAMES, 126 | ) 127 | -------------------------------------------------------------------------------- /deeplearning2020/helpers.py: -------------------------------------------------------------------------------- 1 | import typing 2 | from typing import TYPE_CHECKING 3 | 4 | import matplotlib.pyplot as plt 5 | import numpy as np 6 | 7 | if TYPE_CHECKING: # pragma: no cover 8 | import keras.models 9 | import tensorflow as tf 10 | from tensorflow.keras.callbacks import History 11 | from tensorflow.python.data.ops.dataset_ops import DatasetV1Adapter 12 | 13 | 14 | def plot_woof_predictions( 15 | mdl: "keras.models.Model", 16 | take_ds: "tf.data.Dataset", 17 | classes: typing.Optional[typing.List[int]] = None, 18 | max_cols: int = 3, 19 | figsize: typing.Tuple[int, int] = (6, 4), 20 | ) -> None: 21 | images, labels = [], [] 22 | for image, label in take_ds: 23 | images.append(image.numpy()) 24 | labels.append(label.numpy()) 25 | plot_predictions( 26 | mdl, 27 | np.array(images), 28 | np.array(labels), 29 | classes=classes, 30 | sparse=True, 31 | max_cols=max_cols, 32 | figsize=figsize, 33 | ) 34 | 35 | 36 | def plot_predictions( 37 | mdl: "keras.models.Model", 38 | inputs: np.ndarray, 39 | labels: typing.Optional[np.ndarray] = None, 40 | classes: typing.Optional[typing.List[int]] = None, 41 | images: typing.Optional[np.ndarray] = None, 42 | max_cols: int = 3, 43 | figsize: typing.Tuple[int, int] = (3, 2), 44 | sparse: bool = False, 45 | ) -> None: 46 | assert len(inputs) > 0, "Need at least one input" 47 | assert len(inputs) <= 100, "Wont plot more than 100 images" 48 | if labels is not None: 49 | assert len(inputs) == len(labels), "Need as many labels as inputs!" 50 | num_cols = min(len(inputs), max_cols) 51 | num_rows = int(len(inputs) / num_cols) 52 | fig, plots = plt.subplots( 53 | num_rows, num_cols, figsize=(figsize[0] * num_cols, figsize[1] * num_rows) 54 | ) 55 | model_predictions = mdl.predict(inputs) 56 | if classes is None: 57 | classes = list(range(len(model_predictions[0]))) 58 | if images is None: 59 | images = inputs 60 | else: 61 | assert len(classes) == len( 62 | model_predictions[0] 63 | ), "Need as many class names as there are output neurons" 64 | for r in range(num_rows): 65 | for c in range(num_cols): 66 | i = r * num_cols + c 67 | if not i < len(inputs): 68 | continue 69 | predicted_label = np.argmax(model_predictions[i]) 70 | title = str(classes[predicted_label]) 71 | if labels is None: 72 | color, weight = ("blue", "normal") 73 | else: 74 | expected_label = labels[i] if sparse else np.argmax(labels[i]) 75 | prediction_correct = predicted_label == expected_label 76 | if not prediction_correct: 77 | title += f" (should be {classes[expected_label]})" 78 | color, weight = ( 79 | ("green", "light") if prediction_correct else ("red", "bold") 80 | ) 81 | plots[r][c].tick_params(top=False, bottom=False, left=False, right=False) 82 | plots[r][c].imshow(images[i], cmap=plt.cm.binary) 83 | plots[r][c].axis("off") 84 | plots[r][c].set_title(title, color=color, weight=weight) 85 | 86 | 87 | def plot_worst( 88 | mdl: "keras.models.Model", 89 | imgs: np.ndarray, 90 | labels: np.ndarray, 91 | classes: typing.Optional[typing.List[int]] = None, 92 | num: int = 9, 93 | max_cols: int = 3, 94 | figsize: typing.Tuple[int, int] = (3, 2), 95 | ) -> None: 96 | assert len(imgs) > 0, "Need at least one input" 97 | assert len(imgs) == len(labels), "Need as many labels as inputs!" 98 | max_imgs = min(num + 1, len(imgs)) 99 | pred = mdl.predict(imgs) 100 | i = 0 101 | wrong_imgs = np.expand_dims(np.ndarray(shape=imgs[0].shape), axis=0) 102 | wrong_labels = np.expand_dims(np.ndarray(shape=labels[0].shape), axis=0) 103 | while len(wrong_imgs) < max_imgs and i < len(imgs): 104 | if np.argmax(pred[i]) != np.argmax(labels[i]): 105 | wrong_imgs = np.append(wrong_imgs, np.expand_dims(imgs[i], axis=0), axis=0) 106 | wrong_labels = np.append( 107 | wrong_labels, np.expand_dims(labels[i], axis=0), axis=0 108 | ) 109 | i += 1 110 | plot_predictions( 111 | mdl, 112 | wrong_imgs[1:], 113 | wrong_labels[1:], 114 | classes=classes, 115 | max_cols=max_cols, 116 | figsize=figsize, 117 | ) 118 | 119 | 120 | def plot_learning_curve( 121 | title: str, x: int, y: int, y_test: int, ylim: float = 0.6 122 | ) -> None: 123 | plt.figure() 124 | plt.title(title) 125 | axes = plt.gca() 126 | axes.set_ylim([ylim, 1]) 127 | plt.xlabel("Epoch") 128 | plt.ylabel("Accuracy") 129 | train_sizes = x 130 | train_scores = y 131 | test_scores = y_test 132 | 133 | plt.grid() 134 | 135 | plt.plot( 136 | train_sizes, 137 | train_scores, 138 | "o-", 139 | color=(177 / 255, 6 / 255, 58 / 255), 140 | label="Training accuracy", 141 | ) 142 | plt.plot( 143 | train_sizes, 144 | test_scores, 145 | "o-", 146 | color=(246 / 255, 168 / 255, 0), 147 | label="Validation accuracy", 148 | ) 149 | 150 | plt.legend(loc="best") 151 | 152 | 153 | def plot_history(title: str, history: "History", ylim: float = 0.6) -> None: 154 | y = history.history["accuracy"] 155 | y_test = history.history["val_accuracy"] 156 | plot_learning_curve(title, np.arange(1, 1 + len(y)), y, y_test, ylim) 157 | 158 | 159 | def plot_two_histories(history: "History", history_finetune: "History") -> None: 160 | y = history.history["accuracy"] + history_finetune.history["accuracy"] 161 | y_test = history.history["val_accuracy"] + history_finetune.history["val_accuracy"] 162 | plot_learning_curve("Transfer Learning", np.arange(1, 1 + len(y)), y, y_test, 0) 163 | 164 | 165 | def plot_images(images: "DatasetV1Adapter", class_names: typing.List[str]) -> None: 166 | plt.figure(figsize=(12, 10)) 167 | index = 0 168 | for image, label in images: 169 | index += 1 170 | plt.subplot(3, 3, index) 171 | plt.imshow(image) 172 | plt.title("Class: {}".format(class_names[label])) 173 | plt.axis("off") 174 | 175 | 176 | def plot_images_with_labels( 177 | images: typing.List[int], labels: np.ndarray, class_names: typing.List[str] 178 | ) -> None: 179 | if len(images) != 9: 180 | images = images[:9] 181 | labels = labels[:9] 182 | labels = labels.astype("int") 183 | 184 | plt.figure(figsize=(12, 10)) 185 | index = 0 186 | for image, label in zip(images, labels): 187 | index += 1 188 | plt.subplot(3, 3, index) 189 | plt.imshow(image) 190 | plt.title("Class: {}".format(class_names[label])) 191 | plt.axis("off") 192 | 193 | 194 | def preprocess( 195 | image: typing.Any, label: typing.Any 196 | ) -> typing.Tuple[typing.Any, typing.Any]: 197 | """ resize the images to a uniform size """ 198 | import tensorflow as tf # tensorflow is just expected to be installed 199 | 200 | resized_image = tf.image.resize(image, [224, 224]) 201 | # run Xceptions preprocessing function 202 | preprocessed_image = tf.keras.applications.xception.preprocess_input(resized_image) 203 | return preprocessed_image, label 204 | 205 | 206 | def dataset_to_ndarray( 207 | train_data: "DatasetV1Adapter", test_data: "DatasetV1Adapter" 208 | ) -> typing.Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: 209 | # convert tf.Dataset in np.ndarray, because ImageDataGenerators for 210 | # data augmentation don't work with tf.Datasets 211 | preprocessed_train_data = train_data.map(preprocess).batch(2950) 212 | preprocessed_test_data = test_data.map(preprocess).batch(720) 213 | 214 | x = np.array([]) 215 | y = np.array([]) 216 | for elem in preprocessed_train_data: 217 | x = np.append(x, elem[0].numpy()) 218 | y = np.append(y, elem[1].numpy()) 219 | 220 | x_test = np.array([]) 221 | y_test = np.array([]) 222 | for elem in preprocessed_test_data: 223 | x_test = np.append(x_test, elem[0].numpy()) 224 | y_test = np.append(y_test, elem[1].numpy()) 225 | 226 | # X was flat before 227 | x = x.reshape(len(x) // (224 * 224 * 3), 224, 224, 3) 228 | x_test = x_test.reshape(len(x_test) // (224 * 224 * 3), 224, 224, 3) 229 | return x, y, x_test, y_test 230 | -------------------------------------------------------------------------------- /deeplearning2020/submission.py: -------------------------------------------------------------------------------- 1 | from typing import TYPE_CHECKING 2 | 3 | import kerasltisubmission as klti 4 | from kerasltisubmission.exceptions import KerasLTISubmissionBadResponseException 5 | 6 | if TYPE_CHECKING: # pragma: no cover 7 | import keras.models 8 | 9 | 10 | class Submission: 11 | def __init__( 12 | self, 13 | user_token: klti.AnyIDType, 14 | assignment_id: klti.AnyIDType, 15 | model: "keras.models.Model", 16 | ): 17 | self.user_token = user_token 18 | self.assignment_id = assignment_id 19 | self.model = model 20 | 21 | def submit(self, verbose: bool = True, strict: bool = False) -> None: 22 | provider = klti.LTIProvider( 23 | input_api_endpoint="https://neuralnet.xopic.de/ltiprovider", 24 | submission_api_endpoint="https://neuralnet.xopic.de/ltiprovider/submit", 25 | user_token=self.user_token, 26 | ) 27 | 28 | submission = klti.Submission(assignment_id=self.assignment_id, model=self.model) 29 | 30 | try: 31 | print(f"Model wird validiert...") 32 | results = provider.submit(submission, verbose=verbose, strict=strict) 33 | for assignment_id, result in results.items(): 34 | print(f"Assignment {assignment_id} erfolgreich abgegeben!") 35 | print( 36 | f"Dein Model hat eine Accuracy von {round(result.get('accuracy') * 100, ndigits=1)}% auf unseren Validierungsdaten." 37 | ) 38 | print( 39 | f"Du erhältst {round(result.get('grade') * 100, ndigits=1)}% der Punkte auf dieses Assignment." 40 | ) 41 | print( 42 | f"Falls du bereits eine Abgabe mit höherer Bewertung abgegeben hast, wird automatisch das bessere Ergebnis gewählt." 43 | ) 44 | except KerasLTISubmissionBadResponseException as e: 45 | print(e.message) 46 | except Exception as e: 47 | print(str(e)) 48 | -------------------------------------------------------------------------------- /example.py: -------------------------------------------------------------------------------- 1 | from tensorflow import keras 2 | from deeplearning2020 import Submission 3 | 4 | data = keras.datasets.mnist 5 | (train_images, train_labels), (test_images, test_labels) = data.load_data() 6 | 7 | train_images = train_images / 255.0 8 | test_images = test_images / 255.0 9 | 10 | total_classes = 10 11 | train_vec_labels = keras.utils.to_categorical(train_labels, total_classes) 12 | test_vec_labels = keras.utils.to_categorical(test_labels, total_classes) 13 | 14 | model = keras.Sequential( 15 | [ 16 | keras.layers.Flatten(input_shape=(28, 28)), 17 | keras.layers.Dense(128, activation="sigmoid"), 18 | keras.layers.Dense(10, activation="sigmoid"), 19 | ] 20 | ) 21 | 22 | model.compile(optimizer="sgd", loss="mean_squared_error", metrics=["accuracy"]) 23 | 24 | model.fit(train_images, train_vec_labels, epochs=2, verbose=True) 25 | 26 | eval_loss, eval_accuracy = model.evaluate(test_images, test_vec_labels, verbose=False) 27 | print("Model accuracy: %.2f" % eval_accuracy) 28 | 29 | Submission( 30 | user_token="", assignment_id=2, model=model 31 | ).submit() 32 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [bumpversion] 2 | current_version = 0.4.21 3 | commit = True 4 | tag = True 5 | 6 | [bumpversion:file:setup.py] 7 | search = version \= "{current_version}" 8 | replace = {new_version} 9 | 10 | [bumpversion:file:deeplearning2020/__init__.py] 11 | search = __version__ \= "{current_version}" 12 | replace = {new_version} 13 | 14 | [bdist_wheel] 15 | universal = 1 16 | 17 | [metadata] 18 | description-file = PACKAGE.rst 19 | 20 | [flake8] 21 | exclude = docs 22 | ignore = E203, E266, E501, W503 23 | max-line-length = 88 24 | max-complexity = 18 25 | select = B,C,E,F,W,T4 26 | 27 | [isort] 28 | multi_line_output = 3 29 | include_trailing_comma = True 30 | force_grid_wrap = 0 31 | use_parentheses = True 32 | line_length = 88 33 | 34 | [mypy] 35 | files = deeplearning2020,tests 36 | ignore_missing_imports = true 37 | disallow_subclassing_any = true 38 | disallow_any_generics = true 39 | disallow_untyped_calls = true 40 | disallow_untyped_defs = true 41 | disallow_incomplete_defs = true 42 | check_untyped_defs = true 43 | no_implicit_optional = true 44 | warn_redundant_casts = true 45 | warn_return_any = true 46 | warn_unused_ignores = true 47 | no_warn_unused_configs = true 48 | warn_unused_configs = true 49 | disallow_untyped_decorators = true 50 | 51 | [tool:pytest] 52 | collect_ignore = ['setup.py'] 53 | addopts = -n auto 54 | testpaths = tests/ 55 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | """The setup script.""" 5 | 6 | from setuptools import find_packages, setup 7 | from pathlib import Path 8 | 9 | short_description = "No description has been added so far." 10 | 11 | version = "0.4.21" 12 | 13 | if (Path().parent / "PACKAGE.rst").is_file(): 14 | with open(str(Path().parent / "PACKAGE.rst")) as readme_file: 15 | long_description = readme_file.read() 16 | 17 | requirements = ["kerasltisubmission>=0.4.9"] 18 | test_requirements = [ 19 | "tox", 20 | "pytest", 21 | "pytest-cov", 22 | "pytest-xdist", 23 | "pytest-sugar", 24 | "mypy", 25 | "pyfakefs", 26 | ] 27 | coverage_requirements = ["coverage", "codecov"] 28 | docs_requirements = [] 29 | formatting_requirements = ["flake8", "black==19.10b0", "isort"] 30 | tool_requirements = [ 31 | "twine", 32 | "invoke", 33 | "ruamel.yaml", 34 | "pre-commit", 35 | "cookiecutter", 36 | "bump2version", 37 | ] 38 | dev_requirements = ( 39 | requirements 40 | + test_requirements 41 | + coverage_requirements 42 | + docs_requirements 43 | + formatting_requirements 44 | + tool_requirements 45 | ) 46 | 47 | setup( 48 | author="into-ai", 49 | author_email="introintoai@gmail.com", 50 | classifiers=[ 51 | "Development Status :: 2 - Pre-Alpha", 52 | "Intended Audience :: Developers", 53 | "License :: OSI Approved :: MIT License", 54 | "Environment :: Console", 55 | "Operating System :: OS Independent", 56 | "Natural Language :: English", 57 | "Programming Language :: Python", 58 | "Programming Language :: Python :: 3 :: Only", 59 | "Programming Language :: Python :: 3.5", 60 | "Programming Language :: Python :: 3.6", 61 | "Programming Language :: Python :: 3.7", 62 | "Programming Language :: Python :: 3.8", 63 | ], 64 | python_requires=">=3.6", 65 | install_requires=requirements, 66 | setup_requires=tool_requirements, 67 | tests_require=test_requirements, 68 | extras_require=dict( 69 | dev=dev_requirements, docs=docs_requirements, test=test_requirements 70 | ), 71 | license="MIT", 72 | description=short_description, 73 | long_description=long_description, 74 | include_package_data=True, 75 | package_data={"deeplearning2020": []}, 76 | keywords="deeplearning2020", 77 | name="deeplearning2020", 78 | packages=find_packages(include=["deeplearning2020"]), 79 | test_suite="tests", 80 | url="https://github.com/into-ai/deeplearning2020", 81 | version=version, 82 | zip_safe=False, 83 | ) 84 | -------------------------------------------------------------------------------- /tasks.py: -------------------------------------------------------------------------------- 1 | """ 2 | Tasks for maintaining the project. 3 | 4 | Execute 'invoke --list' for guidance on using Invoke 5 | """ 6 | import shutil 7 | from ruamel.yaml import YAML 8 | import pprint 9 | 10 | from invoke import task 11 | import webbrowser 12 | from pathlib import Path 13 | 14 | Path().expanduser() 15 | yaml = YAML() 16 | 17 | ROOT_DIR = Path(__file__).parent 18 | SETUP_FILE = ROOT_DIR.joinpath("setup.py") 19 | TEST_DIR = ROOT_DIR.joinpath("tests") 20 | SOURCE_DIR = ROOT_DIR.joinpath("deeplearning2020") 21 | TOX_DIR = ROOT_DIR.joinpath(".tox") 22 | TRAVIS_CONFIG_FILE = ROOT_DIR.joinpath(".travis.yml") 23 | COVERAGE_FILE = ROOT_DIR.joinpath(".coverage") 24 | COVERAGE_DIR = ROOT_DIR.joinpath("htmlcov") 25 | COVERAGE_REPORT = COVERAGE_DIR.joinpath("index.html") 26 | PYTHON_DIRS = [str(d) for d in [SOURCE_DIR, TEST_DIR]] 27 | 28 | 29 | def _delete_file(file): 30 | try: 31 | file.unlink(missing_ok=True) 32 | except TypeError: 33 | # missing_ok argument added in 3.8 34 | try: 35 | file.unlink() 36 | except FileNotFoundError: 37 | pass 38 | 39 | 40 | @task(help={"check": "Checks if source is formatted without applying changes"}) 41 | def format(c, check=False): 42 | """Format code 43 | """ 44 | python_dirs_string = " ".join(PYTHON_DIRS) 45 | black_options = "--diff" if check else "" 46 | c.run("pipenv run black {} {}".format(black_options, python_dirs_string)) 47 | isort_options = "--recursive {}".format("--check-only" if check else "") 48 | c.run("pipenv run isort {} {}".format(isort_options, python_dirs_string)) 49 | 50 | 51 | @task 52 | def lint(c): 53 | """Lint code 54 | """ 55 | c.run("pipenv run flake8 {}".format(SOURCE_DIR)) 56 | 57 | 58 | @task 59 | def test(c, min_coverage=None): 60 | """Run tests 61 | """ 62 | pytest_options = "--cov-fail-under={}".format(min_coverage) if min_coverage else "" 63 | c.run("pipenv run pytest --cov={} {}".format(SOURCE_DIR, pytest_options)) 64 | 65 | 66 | @task 67 | def type_check(c): 68 | """Check types 69 | """ 70 | c.run("pipenv run mypy") 71 | 72 | 73 | def _create(d, *keys): 74 | current = d 75 | for key in keys: 76 | try: 77 | current = current[key] 78 | except (TypeError, KeyError): 79 | current[key] = dict() 80 | current = current[key] 81 | 82 | 83 | def _fix_token(config_file=None, force=False, verify=True): 84 | config_file = config_file or TRAVIS_CONFIG_FILE 85 | with open(config_file, "r") as _file: 86 | try: 87 | travis_config = yaml.load(_file) 88 | except Exception: 89 | raise ValueError( 90 | "Failed to parse the travis configuration. " 91 | "Make sure the config only contains valid YAML and keys as specified by travis." 92 | ) 93 | 94 | # Get the generated token from the top level deploy config added by the travis cli 95 | try: 96 | real_token = travis_config["deploy"]["password"]["secure"] 97 | except (TypeError, KeyError): 98 | raise AssertionError("Can't find any top level deployment tokens") 99 | 100 | try: 101 | # Find the build stage that deploys to PyPI 102 | pypy_stages = [ 103 | stage 104 | for stage in travis_config["jobs"]["include"] 105 | if stage.get("deploy", dict()).get("provider") == "pypi" 106 | ] 107 | assert ( 108 | len(pypy_stages) > 0 109 | ), "Can't set the new token because there are no stages deploying to PyPI" 110 | assert ( 111 | len(pypy_stages) < 2 112 | ), "Can't set the new token because there are multiple stages deploying to PyPI" 113 | except (TypeError, KeyError): 114 | raise AssertionError("Can't set the new token because there no build stages") 115 | 116 | try: 117 | is_mock_token = pypy_stages[0]["deploy"]["password"]["secure"] == "REPLACE_ME" 118 | is_same_token = pypy_stages[0]["deploy"]["password"]["secure"] == real_token 119 | 120 | unmodified = is_mock_token or is_same_token 121 | except (TypeError, KeyError): 122 | unmodified = False 123 | 124 | # Set the new generated token as the stages deploy token 125 | _create(pypy_stages[0], "deploy", "password", "secure") 126 | pypy_stages[0]["deploy"]["password"]["secure"] = real_token 127 | 128 | # Make sure it is fine to overwrite the config file 129 | assert unmodified or force, ( 130 | 'The secure token in the "{}" stage has already been changed. ' 131 | "Retry with --force if you are sure about replacing it.".format( 132 | pypy_stages[0].get("stage", "PyPI deployment") 133 | ) 134 | ) 135 | 136 | # Remove the top level deploy config added by the travis cli 137 | travis_config.pop("deploy") 138 | 139 | if not unmodified and verify: 140 | pprint.pprint(travis_config) 141 | if ( 142 | not input("Do you want to save this configuration? (y/n) ") 143 | .strip() 144 | .lower() 145 | == "y" 146 | ): 147 | return 148 | 149 | # Save the new travis config 150 | assert travis_config 151 | with open(config_file, "w") as _file: 152 | yaml.dump(travis_config, _file) 153 | print("Fixed!") 154 | 155 | 156 | @task(help=dict( 157 | force="Force overriding the current travis configuration", 158 | verify="Verify config changes by asking for the user's approval" 159 | )) 160 | def fix_token(c, force=False, verify=True): 161 | """ 162 | Add the token generated by the travis cli script to the correct entry 163 | """ 164 | _fix_token(force=force, verify=verify) 165 | 166 | 167 | @task 168 | def install_hooks(c): 169 | """Install pre-commit hooks 170 | """ 171 | c.run("pipenv run pre-commit install -t pre-commit") 172 | c.run("pipenv run pre-commit install -t pre-push") 173 | 174 | 175 | @task 176 | def pre_commit(c): 177 | """Run all pre-commit checks 178 | """ 179 | c.run("pipenv run pre-commit run --all-files") 180 | 181 | 182 | @task( 183 | pre=[test], 184 | help=dict( 185 | publish="Publish the result (default False)", 186 | provider="The provider to publish (default codecov)", 187 | ), 188 | ) 189 | def coverage(c, publish=False, provider="codecov"): 190 | """Create coverage report 191 | """ 192 | if publish: 193 | # Publish the results via provider (e.g. codecov or coveralls) 194 | c.run("pipenv run {}".format(provider)) 195 | else: 196 | # Build a local report 197 | c.run("pipenv run coverage html -d {}".format(COVERAGE_DIR)) 198 | webbrowser.open(COVERAGE_REPORT.as_uri()) 199 | 200 | 201 | @task 202 | def clean_build(c): 203 | """Clean up files from package building 204 | """ 205 | c.run("rm -fr build/") 206 | c.run("rm -fr dist/") 207 | c.run("rm -fr .eggs/") 208 | c.run("find . -name '*.egg-info' -exec rm -fr {} +") 209 | c.run("find . -name '*.egg' -exec rm -f {} +") 210 | 211 | 212 | @task 213 | def clean_python(c): 214 | """Clean up python file artifacts 215 | """ 216 | c.run("find . -name '*.pyc' -exec rm -f {} +") 217 | c.run("find . -name '*.pyo' -exec rm -f {} +") 218 | c.run("find . -name '*~' -exec rm -f {} +") 219 | c.run("find . -name '__pycache__' -exec rm -fr {} +") 220 | 221 | 222 | @task 223 | def clean_tests(c): 224 | """Clean up files from testing 225 | """ 226 | _delete_file(COVERAGE_FILE) 227 | shutil.rmtree(TOX_DIR, ignore_errors=True) 228 | shutil.rmtree(COVERAGE_DIR, ignore_errors=True) 229 | 230 | 231 | @task(pre=[clean_build, clean_python, clean_tests]) 232 | def clean(c): 233 | """Runs all clean sub-tasks 234 | """ 235 | pass 236 | 237 | 238 | @task(clean) 239 | def dist(c): 240 | """Build source and wheel packages 241 | """ 242 | c.run("python setup.py sdist") 243 | c.run("python setup.py bdist_wheel") 244 | 245 | 246 | @task(pre=[clean, dist]) 247 | def release(c): 248 | """Make a release of the python package to pypi 249 | """ 250 | c.run("twine upload dist/*") 251 | -------------------------------------------------------------------------------- /tests/test_deeplearning2020.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | """Tests for `deeplearning2020` package.""" 5 | 6 | import unittest.mock 7 | 8 | import keras 9 | 10 | from deeplearning2020 import Submission 11 | 12 | 13 | def test_construction() -> None: 14 | with unittest.mock.patch( 15 | "kerasltisubmission.LTIProvider", autospec=True 16 | ) as mocked_provider: 17 | mock_provider = unittest.mock.MagicMock() 18 | mock_submit = unittest.mock.MagicMock() 19 | mock_provider.submit = mock_submit 20 | 21 | mocked_provider.return_value = mock_provider 22 | 23 | model = unittest.mock.MagicMock(spec=keras.Model) 24 | Submission(user_token="12", assignment_id=2, model=model).submit() 25 | 26 | mocked_provider.assert_called_with( 27 | input_api_endpoint="https://neuralnet.xopic.de/ltiprovider", 28 | submission_api_endpoint="https://neuralnet.xopic.de/ltiprovider/submit", 29 | user_token="12", 30 | ) 31 | 32 | assert len(mock_submit.call_args_list) == 1 33 | args, kwargs = mock_submit.call_args_list[0] 34 | assert args[0].assignment_id == 2 35 | assert args[0].model == model 36 | 37 | 38 | def test_ignores_exceptions() -> None: 39 | with unittest.mock.patch( 40 | "kerasltisubmission.LTIProvider.submit", autospec=True 41 | ) as mocked_submit: 42 | mocked_submit.side_effect = ValueError("Something went wrong") 43 | model = unittest.mock.MagicMock(spec=keras.Model) 44 | Submission(user_token="12", assignment_id=2, model=model).submit() 45 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [tox] 2 | envlist = py36, py37, lint, format, typecheck 3 | 4 | [travis] 5 | python = 6 | 3.7: py37 7 | 3.6: py36 8 | 9 | [testenv:lint] 10 | basepython = python 11 | commands = pipenv run invoke lint 12 | 13 | [testenv:format] 14 | basepython = python 15 | commands = pipenv run invoke format --check 16 | 17 | [testenv:typecheck] 18 | basepython = python 19 | commands = pipenv run invoke type-check 20 | 21 | [testenv:codecov] 22 | passenv = CI TRAVIS TRAVIS_* CODECOV_TOKEN 23 | basepython = python 24 | deps = 25 | pip>=19.2 26 | setuptools>=41.0.0 27 | pipenv 28 | codecov 29 | commands_post = pipenv run codecov 30 | 31 | [testenv] 32 | setenv = 33 | PYTHONPATH = {toxinidir} 34 | deps = 35 | setuptools>=41.0.0 36 | pip>=19.2 37 | pipenv 38 | commands_pre = 39 | pip install --quiet tensorflow 40 | pipenv install --clear --dev 41 | commands = pipenv run invoke test 42 | 43 | 44 | -------------------------------------------------------------------------------- /woche1/README.md: -------------------------------------------------------------------------------- 1 | #### Woche 1 2 | 3 | ##### Inhalt 4 | - [Installation](./notebooks/) 5 | - [Linux](./installation/linux.md/) 6 | - [Mac OS](./installation/mac.md/) 7 | - [Windows](./installation/windows.md/) 8 | - [Freiwillige Übung](./bonus/) 9 | -------------------------------------------------------------------------------- /woche1/bonus/bonus.md: -------------------------------------------------------------------------------- 1 | #### Bonusaufgabe: Backpropagations selber nachvollziehen 2 | 3 | In dieser Woche gibt es eine freiwillige Bonusaufgabe, in der der im Kurs vorgestellte Backpropagation Algorithmus einmal selbst angewandt werden kann, um in einem (kleinen und einfachen) künstlichen neuronalen Netz die Gradienten zu berechnen und damit das Netz zu verbessern. 4 | 5 | Die Übung ist absolut freiwillig und bei erfolgreicher Bearbeitung kann ein **Bonuspunkt erworben werden**. :wink: 6 | 7 | #### Aufbau der Übung 8 | 9 | Wir stellen euch für diese Übung eine Webapplikation zur Verfügung, in welcher ihr den Backpropagation Schritt selber nachvollziehen könnt. Die Bewertung eurer Lösung passiert automatisch und wird euch bei korrekter Bearbeitung die richtige Antwort auf das folgende Bonusquiz verraten. Dieses Quiz kann man nur einmal bearbeiten und dient nur dazu euch Bonuspunkte gutschreiben zu können. 10 | 11 | ![Screenshot](https://github.com/into-ai/vue-backpropagation-exercise/raw/master/screenshot.png) 12 | 13 | Zunächst sollt ihr auf der Webseite den **Feed Forward Schritt** durchführen, also die Ausgabe des Netzes berechnen. Anschließend könnt ihr mit diesen Werten den **Backpropagation Schritt** durchführen. Dabei seht ihr ebenso den aktuellen Fehler des Netzes. Diesen werden wir am Ende durch die Veränderung eines Gewichtes ändern können, um zu sehen wie alle Neuronen einen Einfluss auf die Veränderung des Fehlers haben. 14 | Weitere Instruktionen findet ihr dann auf der Seite. 15 | 16 | [Hier geht's zur Bonusaufgabe](https://neuralnet.xopic.de/backpropexercise/start). 17 | 18 | Wir wünschen euch viel Spaß bei der Bearbeitung! 19 | -------------------------------------------------------------------------------- /woche1/bonus/solution_backpropagation.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/into-ai/deeplearning2020/4446c046982430d5e063919cf9511c8a174c76c2/woche1/bonus/solution_backpropagation.png -------------------------------------------------------------------------------- /woche1/bonus/solution_feed_forward.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/into-ai/deeplearning2020/4446c046982430d5e063919cf9511c8a174c76c2/woche1/bonus/solution_feed_forward.png -------------------------------------------------------------------------------- /woche1/installation/README.md: -------------------------------------------------------------------------------- 1 | ## Exkurs: Lokale Installation 2 | 3 | Wir nutzen für den Kurs primär [Google Colab](https://colab.research.google.com/). Google bietet jeder Person mit einem Google Account die Möglichkeit im Browser sogennante Jupyter Notebooks auszuführen, welche es erlauben interaktiv Python Code und Text in Zellen zu schreiben. Dieser Workflow eignet sich sehr gut für Machine Learning Anwendungen, wo viel iterativ und interaktiv ausprobiert werden muss. 4 | 5 | Die Basistechnologien die uns durch Google Colab zur Verfügung gestellt werden ((`tensorflow`, `keras`, `matplotlib`, `numpy`, `jupyter notebook` etc.) sind alle Open Source und können auf allen Plattformen auch lokal installiert werden. 6 | 7 | Wir haben dazu folgende Anleitungen als Hilfestellung verfasst: 8 | 9 | - [Installation unter Linux](linux.md) 10 | - [Installation unter macOS](mac.md) 11 | - [Installation unter Windows](windows.md) 12 | -------------------------------------------------------------------------------- /woche1/installation/linux.md: -------------------------------------------------------------------------------- 1 | #### Lokale Installation unter Linux 2 | 3 | 1. Download des Installationsskriptes unter [anaconda.com/distribution](https://www.anaconda.com/distribution/). Als Download sollte unter dem Reiter **Linux** die Version für **Python 3.7** und **64-Bit (x86)** (außer es handelt sich um einen Computer mit Power8/9 Architektur) gewählt werden. 4 | 5 | 2. Ausführen des Installationsskriptes im Terminal: 6 | ```bash 7 | bash ~/Downloads/Anaconda3-2019.10-Linux-x86_64.sh 8 | ``` 9 | Bestätigen der Installation mit *ENTER*. Anschließend Akzeptieren der Lizenzbedingungen mit *yes*. Der Installationsort kann beliebig gewählt werden. Am Ende noch einmal die Bestätigung von `conda init` ebenfalls mit *yes*. 10 | 11 | 3. Terminal schließen und neu öffnen, damit die änderungen aktiv werden. 12 | 13 | 4. Überprüfen der Installation mit `conda list`. 14 | 15 | 5. Erstellen eines neuen *conda environment* mit 16 | ```bash 17 | conda create -n deeplearning2020 python=3.7 tensorflow keras nb_conda numpy matplotlib notebook 18 | ``` 19 | Die Frage, ob die Transaktion durchgeführt werden soll mit *yes* bestätigen. 20 | 21 | 6. Aktivieren des conda environments mit 22 | ```bash 23 | conda activate deeplearning2020 24 | ``` 25 | 26 | 7. Starten eines lokalen `jupyter notebook` server mit 27 | ```bash 28 | jupyter notebook 29 | ``` 30 | Dies sollte automatisch einen neuen Browser Tab mit dem notebook *dashboard* öffnen. Falls das nicht passiert findet ihr eine URL mit einem Token in der Ausgabe auf der Kommandozeile. 31 | 32 | 8. Erstellen eines neuen `jupyter notebook` in einem beliebigen Ordner durch Klick auf **New** im Dashboard oben rechts und dann auf **[conda env:deeplearning2020]**. 33 | 34 | 9. Testen ob alle Pakete fehlerfrei importiert und benutzt werden können, indem eine Codezelle des notebooks mit folgendem Code ausgeführt wird (**Run**): 35 | ```python 36 | import tensorflow as tf 37 | from tensorflow import keras 38 | import numpy as np 39 | import matplotlib.pyplot as plt 40 | print(tf.__version__) 41 | ``` 42 | 43 | 10. Speichern des notebooks durch Klick auf **File>Save** oder den *Save* Button links oben. Wenn das Speichern erfolgreich war sollte ein neuer Checkpoint erstellt worden sein. 44 | 45 | 11. (Optional) Nach dem Speichern kann die Seite mit dem **Logout** Button oben rechts verlassen werden und der `jupyter notebook` Server mit `Ctrl-C` gestoppt werden. Zum erneuten Starten siehe Schritt 7. 46 | 47 | 12. (Optional) Conda erlaubt es beliebig viele environments zu erstellen. Mit `conda deactivate` kann das `deeplearning2020` environment deaktiviert werden und weitere environments erstellt und aktiviert werden falls gewünscht. Für die erneute Aktivierung des `deeplearning2020` environments siehe Schritt 6. 48 | -------------------------------------------------------------------------------- /woche1/installation/mac.md: -------------------------------------------------------------------------------- 1 | #### Lokale Installation unter MacOS 2 | 3 | ##### Grafisches Installationsprogramm 4 | 1. Zuallererst müsst ihr euch das grafische Installationsprogramm von [Anaconda][1] herunter laden. Hierbei wollen wir die neuere Python Version und wählen somit Python 3.7. 5 | 6 | 2. Dieses Installationsprogramm muss anschließend ausgeführt werden, um die Installation von Anaconda abzuschließen. 7 | 8 | ##### Homebrew Packet Manager 9 | 10 | 1. Solltet ihr kein Homebrew auf eurem Rechner installiert haben, müsst ihr dies als aller Erstes tun. Geht hierfür auf die [offizielle Webseite][2] und kopiert den Befehl zu "Install Homebrew" in euer Terminal und führt ihn aus. 11 | 12 | 2. `brew cask install anaconda` installiert euch die aktuelle Anaconda Version mit dem Homebrew Packet Manager. 13 | 14 | **Im Terminal:** 15 | 16 | 3. `conda` verrät uns, ob wir den Befehl conda überall im Terminal verwenden können 17 | 18 | 4. **Grafisches Installationsprogramm:** 19 | `echo 'export PATH=“/Users//anaconda3/bin:$PATH"' >> ` **Homebrew:** 20 | `echo 'export PATH="/usr/local/anaconda3/bin:$PATH"' >> ` schreibt den Pfad zu dem conda Befehl in eure Konfigurationsdatei. 21 | Bei mir handelt es sich bei der Shell Konfigurationsdatei um `.zshrc`, da ich die zsh Shell verwende. Ihr habt höchstwahrscheinlich die bash Shell und somit die Konfigurationsdatei `.bash_profile`. Wenn ihr euch sicher sein wollt, erfahrt ihr den Namen eurer Shell unter dem Befehl: `echo “$SHELL”`. Der USER_NAME muss ebenfalls in dem Pfad zur Installation mit dem grafischen Installationsprogramm angepasst werden. Mit welchem User ihr angemeldet seid, könnt ihr mit dem Befehl: `echo “$USER”` herausfinden. 22 | 23 | 5. `source ` führt die Konfigurationsdatei aus, sodass der Pfad nicht nur in die Datei geschrieben, sondern ebenfalls exportiert wird, um conda anschließend überall im Terminal ausführen zu können. 24 | 25 | 6. `conda` sollte jetzt den Hilfstext mit einer Liste der verfügbaren Befehle ausgeben. 26 | 27 | 7. `conda create -n neuralnets2020` erstellt eine Anaconda (virtuelle) Umgebung mit dem Namen neuralnets2020. In diesem können wir jetzt alle notwedigen Pakete installieren ohne andere Umgebungen zu beeinflussen und das Projekt somit von allen anderen Projekten und deren Abhängigkeiten zu isolieren. 28 | 29 | 8. `conda init ` initialisiert die Shell, um anschließend Anaconda Umgebungen zu aktivieren (z.B.: `conda init zsh` oder `conda init bash`). 30 | 31 | 9. `conda activate neuralnets2020` aktiviert die virtuelle Umgebung (befinden uns anschließend in dieser), was durch das Kürzel vor dem User erkennbar ist. 32 | 33 | 10. `conda install tensorflow nb_conda` installiert alle benötigten Pakete in der aktiven Umgebung. 34 | 35 | 11. `jupyter notebook` startet einen Notebook Server, sodass ihr lokal in eurem Browser Jupyter Notebooks erstellen könnt und die gleiche Funktionalitäten habt, wie sonst in Google Colab (kann mit CTRL-C beendet werden). 36 | 37 | 12. `conda deactivate` deaktiviert die aktuell aktive, virtuelle Umgebung, um z.B. eine andere Umgebung zu öffnen. 38 | 39 | 13. `conda activate neuralnets2020` aktiviert erneut eine erstellte virtuelle Umgebung, um die Arbeit an dem Projekt fortzusetzen. 40 | 41 | 42 | 43 | [1]: https://www.anaconda.com/distribution/ 44 | [2]: https://brew.sh/ 45 | -------------------------------------------------------------------------------- /woche1/installation/windows.md: -------------------------------------------------------------------------------- 1 | 2 | #### Lokale Installation unter Windows 3 | 4 | 1. Download des Installationsskriptes unter [anaconda.com/distribution](https://www.anaconda.com/distribution/). Als Download sollte unter dem Reiter **Windows** die Version für **Python 3.7** und **64-Bit** (außer es handelt sich um einen alten Computer mit 32bit) gewählt werden. 5 | 6 | 2. Ausführen des grafischen Installers durch Doppelklicken auf das heruntergeladene Installationsprogramm `Anaconda3-2019.10-Windows-x86_64.exe`. Anschließend können beim Setup alle Standardwerte übernommen werden. Per Default wird `python3.7` aus der `anaconda` Installation die neue Standardversion, was in den meisten Fällen erwünscht ist. Falls ihr jedoch auch nicht den `Anaconda Kommandozeilen-Prompt` jedes mal starten möchtet, könnt ihr auch den Haken bei *Add Anaconda to my PATH environment variable* setzen. 7 | 8 | 3. Suchen und Starten von **Anaconda Prompt** (zum Beispiel mit der Windows Suche). Der Kommandozeilen-Prompt sollte mit `(base)` beginnen. 9 | 10 | 4. Überprüfen der Installation mit `conda list`. 11 | 12 | 5. Erstellen eines neuen *conda environment* mit 13 | ```bash 14 | conda create -n deeplearning2020 python=3.7 tensorflow keras nb_conda numpy matplotlib notebook 15 | ``` 16 | Die Frage, ob die Transaktion durchgeführt werden soll mit *yes* bestätigen. 17 | 18 | 6. Aktivieren des conda environments mit 19 | ```bash 20 | conda activate deeplearning2020 21 | ``` 22 | 23 | 7. Starten eines lokalen `jupyter notebook` server mit 24 | ```bash 25 | jupyter notebook 26 | ``` 27 | Dies sollte automatisch einen neuen Browser Tab mit dem notebook *dashboard* öffnen. Falls das nicht passiert findet ihr eine URL mit einem Token in der Ausgabe auf der Kommandozeile. 28 | 29 | 8. Erstellen eines neuen `jupyter notebook` in einem beliebigen Ordner durch Klick auf **New** im Dashboard oben rechts und dann auf **[conda env:deeplearning2020]**. 30 | 31 | 9. Testen ob alle Pakete fehlerfrei importiert und benutzt werden können, indem eine Codezelle des notebooks mit folgendem Code ausgeführt wird (**Run**): 32 | ```python 33 | import tensorflow as tf 34 | from tensorflow import keras 35 | import numpy as np 36 | import matplotlib.pyplot as plt 37 | print(tf.__version__) 38 | ``` 39 | 40 | 10. Speichern des notebooks durch Klick auf **File>Save** oder den *Save* Button links oben. Wenn das Speichern erfolgreich war sollte ein neuer Checkpoint erstellt worden sein. 41 | 42 | 11. (Optional) Nach dem Speichern kann die Seite mit dem **Logout** Button oben rechts verlassen werden und der `jupyter notebook` Server mit `Ctrl-C` gestoppt werden. Zum erneuten Starten siehe Schritt 7. 43 | 44 | 12. (Optional) Conda erlaubt es beliebig viele environments zu erstellen. Mit `conda deactivate` kann das `deeplearning2020` environment deaktiviert werden und weitere environments erstellt und aktiviert werden falls gewünscht. Für die erneute Aktivierung des `deeplearning2020` environments siehe Schritt 6. 45 | -------------------------------------------------------------------------------- /woche2/README.md: -------------------------------------------------------------------------------- 1 | #### Woche 2 2 | 3 | In der zweiten Woche geht es, neben weiteren Techniken und dem Aufbau von Verständnis vor allem darum, die State-of-the-Art Tools kennenzulernen, welche heutzutage von den meisten WissenschaftlerInnen, Unternehmen und PrivatanwenderInnen in diesem Gebiet gleichermaßen verwendet werden. 4 | 5 | ##### Inhalt 6 | - [Notebooks](./notebooks/) 7 | - [Einführung in Numpy](./notebooks/intro-numpy/) 8 | - [Einführung in Matplotlib](./notebooks/intro-matplotlib/) 9 | - [Laden und Bearbeiten des MNIST Datensatz](./notebooks/exploring-mnist) 10 | - [Einführung in Tensorflow / Keras](./notebooks/intro-tensorflow-keras/) 11 | - [MNIST Vergleich Aktivierungsfunktionen](./notebooks/mnist-activation-functions/) 12 | - [Beispiel: Trainieren eines Netzes für MNIST](./notebooks/first-mnist-net/) 13 | - [Praktische Übung](./assignment/) 14 | -------------------------------------------------------------------------------- /woche2/assignment/Fashion_MNIST_simple_solution.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "nbformat": 4, 3 | "nbformat_minor": 0, 4 | "metadata": { 5 | "colab": { 6 | "name": "Fashion MNIST - simple solution.ipynb", 7 | "provenance": [], 8 | "collapsed_sections": [] 9 | }, 10 | "kernelspec": { 11 | "name": "python3", 12 | "display_name": "Python 3" 13 | } 14 | }, 15 | "cells": [ 16 | { 17 | "cell_type": "code", 18 | "metadata": { 19 | "id": "NIBPydt50FD0", 20 | "colab_type": "code", 21 | "outputId": "f47dee9c-6a1e-4916-8aad-811f23374ad5", 22 | "colab": { 23 | "base_uri": "https://localhost:8080/", 24 | "height": 64 25 | } 26 | }, 27 | "source": [ 28 | "import tensorflow as tf\n", 29 | "from tensorflow import keras\n", 30 | "import numpy as np\n", 31 | "import matplotlib.pyplot as plt" 32 | ], 33 | "execution_count": 0, 34 | "outputs": [ 35 | { 36 | "output_type": "display_data", 37 | "data": { 38 | "text/html": [ 39 | "

\n", 40 | "The default version of TensorFlow in Colab will soon switch to TensorFlow 2.x.
\n", 41 | "We recommend you upgrade now \n", 42 | "or ensure your notebook will continue to use TensorFlow 1.x via the %tensorflow_version 1.x magic:\n", 43 | "more info.

\n" 44 | ], 45 | "text/plain": [ 46 | "" 47 | ] 48 | }, 49 | "metadata": { 50 | "tags": [] 51 | } 52 | } 53 | ] 54 | }, 55 | { 56 | "cell_type": "code", 57 | "metadata": { 58 | "id": "wxeA-jpb0Hir", 59 | "colab_type": "code", 60 | "outputId": "ae4e028d-da8c-4dcc-bc95-96e28ea80c11", 61 | "colab": { 62 | "base_uri": "https://localhost:8080/", 63 | "height": 159 64 | } 65 | }, 66 | "source": [ 67 | "fashion_mnist = keras.datasets.fashion_mnist\n", 68 | "\n", 69 | "(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()\n", 70 | "\n", 71 | "class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',\n", 72 | " 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']\n", 73 | "\n", 74 | "train_images = train_images / 255.0\n", 75 | "test_images = test_images / 255.0\n", 76 | "train_vector_labels = keras.utils.to_categorical(train_labels, len(class_names))\n", 77 | "test_vector_labels = keras.utils.to_categorical(test_labels, len(class_names))" 78 | ], 79 | "execution_count": 0, 80 | "outputs": [ 81 | { 82 | "output_type": "stream", 83 | "text": [ 84 | "Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/train-labels-idx1-ubyte.gz\n", 85 | "32768/29515 [=================================] - 0s 0us/step\n", 86 | "Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/train-images-idx3-ubyte.gz\n", 87 | "26427392/26421880 [==============================] - 0s 0us/step\n", 88 | "Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/t10k-labels-idx1-ubyte.gz\n", 89 | "8192/5148 [===============================================] - 0s 0us/step\n", 90 | "Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/t10k-images-idx3-ubyte.gz\n", 91 | "4423680/4422102 [==============================] - 0s 0us/step\n" 92 | ], 93 | "name": "stdout" 94 | } 95 | ] 96 | }, 97 | { 98 | "cell_type": "code", 99 | "metadata": { 100 | "id": "soy8oIyt0KY0", 101 | "colab_type": "code", 102 | "outputId": "fedf55e8-85b7-4db6-9d05-bd0434366fe2", 103 | "colab": { 104 | "base_uri": "https://localhost:8080/", 105 | "height": 90 106 | } 107 | }, 108 | "source": [ 109 | "model = keras.Sequential([\n", 110 | " keras.layers.Flatten(input_shape=(28, 28)),\n", 111 | " keras.layers.Dense(128, activation=\"relu\"), # oder sigmoid\n", 112 | " keras.layers.Dense(10, activation=\"softmax\") \n", 113 | "])" 114 | ], 115 | "execution_count": 0, 116 | "outputs": [ 117 | { 118 | "output_type": "stream", 119 | "text": [ 120 | "WARNING:tensorflow:From /tensorflow-1.15.0/python3.6/tensorflow_core/python/ops/resource_variable_ops.py:1630: calling BaseResourceVariable.__init__ (from tensorflow.python.ops.resource_variable_ops) with constraint is deprecated and will be removed in a future version.\n", 121 | "Instructions for updating:\n", 122 | "If using Keras pass *_constraint arguments to layers.\n" 123 | ], 124 | "name": "stdout" 125 | } 126 | ] 127 | }, 128 | { 129 | "cell_type": "code", 130 | "metadata": { 131 | "id": "MYrwdf340MKE", 132 | "colab_type": "code", 133 | "colab": {} 134 | }, 135 | "source": [ 136 | "model.compile(optimizer='sgd', # oder adam\n", 137 | " loss='mean_squared_error', # oder sparse_categorical_crossentropy\n", 138 | " metrics=['accuracy'])" 139 | ], 140 | "execution_count": 0, 141 | "outputs": [] 142 | }, 143 | { 144 | "cell_type": "code", 145 | "metadata": { 146 | "id": "IuenZI2I0N6M", 147 | "colab_type": "code", 148 | "outputId": "791286ea-de29-4280-9b9c-2f4f6b871533", 149 | "colab": { 150 | "base_uri": "https://localhost:8080/", 151 | "height": 1000 152 | } 153 | }, 154 | "source": [ 155 | "model.fit(train_images, train_vector_labels, epochs=40)" 156 | ], 157 | "execution_count": 0, 158 | "outputs": [ 159 | { 160 | "output_type": "stream", 161 | "text": [ 162 | "Train on 60000 samples\n", 163 | "Epoch 1/40\n", 164 | "60000/60000 [==============================] - 4s 70us/sample - loss: 0.0828 - acc: 0.3432\n", 165 | "Epoch 2/40\n", 166 | "60000/60000 [==============================] - 4s 66us/sample - loss: 0.0609 - acc: 0.6065\n", 167 | "Epoch 3/40\n", 168 | "60000/60000 [==============================] - 4s 62us/sample - loss: 0.0498 - acc: 0.6657\n", 169 | "Epoch 4/40\n", 170 | "60000/60000 [==============================] - 4s 63us/sample - loss: 0.0448 - acc: 0.6871\n", 171 | "Epoch 5/40\n", 172 | "60000/60000 [==============================] - 4s 61us/sample - loss: 0.0416 - acc: 0.7139\n", 173 | "Epoch 6/40\n", 174 | "60000/60000 [==============================] - 4s 62us/sample - loss: 0.0392 - acc: 0.7397\n", 175 | "Epoch 7/40\n", 176 | "60000/60000 [==============================] - 4s 63us/sample - loss: 0.0372 - acc: 0.7611\n", 177 | "Epoch 8/40\n", 178 | "60000/60000 [==============================] - 4s 62us/sample - loss: 0.0356 - acc: 0.7737\n", 179 | "Epoch 9/40\n", 180 | "60000/60000 [==============================] - 4s 61us/sample - loss: 0.0342 - acc: 0.7832\n", 181 | "Epoch 10/40\n", 182 | "60000/60000 [==============================] - 4s 62us/sample - loss: 0.0331 - acc: 0.7899\n", 183 | "Epoch 11/40\n", 184 | "60000/60000 [==============================] - 4s 63us/sample - loss: 0.0321 - acc: 0.7950\n", 185 | "Epoch 12/40\n", 186 | "60000/60000 [==============================] - 4s 64us/sample - loss: 0.0313 - acc: 0.7995\n", 187 | "Epoch 13/40\n", 188 | "60000/60000 [==============================] - 4s 65us/sample - loss: 0.0306 - acc: 0.8031\n", 189 | "Epoch 14/40\n", 190 | "60000/60000 [==============================] - 4s 62us/sample - loss: 0.0300 - acc: 0.8061\n", 191 | "Epoch 15/40\n", 192 | "60000/60000 [==============================] - 4s 63us/sample - loss: 0.0294 - acc: 0.8091\n", 193 | "Epoch 16/40\n", 194 | "60000/60000 [==============================] - 4s 66us/sample - loss: 0.0289 - acc: 0.8120\n", 195 | "Epoch 17/40\n", 196 | "60000/60000 [==============================] - 4s 63us/sample - loss: 0.0285 - acc: 0.8152\n", 197 | "Epoch 18/40\n", 198 | "60000/60000 [==============================] - 4s 62us/sample - loss: 0.0281 - acc: 0.8168\n", 199 | "Epoch 19/40\n", 200 | "60000/60000 [==============================] - 4s 62us/sample - loss: 0.0277 - acc: 0.8191\n", 201 | "Epoch 20/40\n", 202 | "60000/60000 [==============================] - 4s 61us/sample - loss: 0.0274 - acc: 0.8208\n", 203 | "Epoch 21/40\n", 204 | "60000/60000 [==============================] - 4s 64us/sample - loss: 0.0271 - acc: 0.8228\n", 205 | "Epoch 22/40\n", 206 | "60000/60000 [==============================] - 4s 64us/sample - loss: 0.0268 - acc: 0.8244\n", 207 | "Epoch 23/40\n", 208 | "60000/60000 [==============================] - 4s 63us/sample - loss: 0.0265 - acc: 0.8257\n", 209 | "Epoch 24/40\n", 210 | "60000/60000 [==============================] - 4s 64us/sample - loss: 0.0263 - acc: 0.8275\n", 211 | "Epoch 25/40\n", 212 | "60000/60000 [==============================] - 4s 62us/sample - loss: 0.0260 - acc: 0.8286\n", 213 | "Epoch 26/40\n", 214 | "60000/60000 [==============================] - 4s 60us/sample - loss: 0.0258 - acc: 0.8305\n", 215 | "Epoch 27/40\n", 216 | "60000/60000 [==============================] - 4s 61us/sample - loss: 0.0256 - acc: 0.8318\n", 217 | "Epoch 28/40\n", 218 | "60000/60000 [==============================] - 4s 62us/sample - loss: 0.0254 - acc: 0.8326\n", 219 | "Epoch 29/40\n", 220 | "60000/60000 [==============================] - 4s 63us/sample - loss: 0.0252 - acc: 0.8339\n", 221 | "Epoch 30/40\n", 222 | "60000/60000 [==============================] - 4s 63us/sample - loss: 0.0250 - acc: 0.8347\n", 223 | "Epoch 31/40\n", 224 | "60000/60000 [==============================] - 4s 64us/sample - loss: 0.0248 - acc: 0.8357\n", 225 | "Epoch 32/40\n", 226 | "60000/60000 [==============================] - 4s 63us/sample - loss: 0.0247 - acc: 0.8364\n", 227 | "Epoch 33/40\n", 228 | "60000/60000 [==============================] - 4s 64us/sample - loss: 0.0245 - acc: 0.8376\n", 229 | "Epoch 34/40\n", 230 | "60000/60000 [==============================] - 4s 64us/sample - loss: 0.0244 - acc: 0.8382\n", 231 | "Epoch 35/40\n", 232 | "60000/60000 [==============================] - 4s 60us/sample - loss: 0.0242 - acc: 0.8396\n", 233 | "Epoch 36/40\n", 234 | "60000/60000 [==============================] - 4s 65us/sample - loss: 0.0241 - acc: 0.8405\n", 235 | "Epoch 37/40\n", 236 | "60000/60000 [==============================] - 4s 63us/sample - loss: 0.0240 - acc: 0.8408\n", 237 | "Epoch 38/40\n", 238 | "60000/60000 [==============================] - 4s 67us/sample - loss: 0.0238 - acc: 0.8419\n", 239 | "Epoch 39/40\n", 240 | "60000/60000 [==============================] - 4s 61us/sample - loss: 0.0237 - acc: 0.8429\n", 241 | "Epoch 40/40\n", 242 | "60000/60000 [==============================] - 4s 61us/sample - loss: 0.0236 - acc: 0.8429\n" 243 | ], 244 | "name": "stdout" 245 | }, 246 | { 247 | "output_type": "execute_result", 248 | "data": { 249 | "text/plain": [ 250 | "" 251 | ] 252 | }, 253 | "metadata": { 254 | "tags": [] 255 | }, 256 | "execution_count": 5 257 | } 258 | ] 259 | }, 260 | { 261 | "cell_type": "code", 262 | "metadata": { 263 | "id": "KVFiTpIE0Qes", 264 | "colab_type": "code", 265 | "outputId": "017ddac5-8f56-4bb6-8069-b5f3370d4996", 266 | "colab": { 267 | "base_uri": "https://localhost:8080/", 268 | "height": 53 269 | } 270 | }, 271 | "source": [ 272 | "test_loss, test_acc = model.evaluate(test_images, test_vector_labels, verbose=2)\n", 273 | "print(\"Test accuracy:\", test_acc)" 274 | ], 275 | "execution_count": 0, 276 | "outputs": [ 277 | { 278 | "output_type": "stream", 279 | "text": [ 280 | "10000/10000 - 0s - loss: 0.0250 - acc: 0.8303\n", 281 | "Test accuracy: 0.8303\n" 282 | ], 283 | "name": "stdout" 284 | } 285 | ] 286 | } 287 | ] 288 | } -------------------------------------------------------------------------------- /woche2/assignment/README.md: -------------------------------------------------------------------------------- 1 | #### Assignment Woche 2 2 | 3 | EDIT: Die Lösung befindet sich unter diesem [Link](https://colab.research.google.com/drive/1LoKnlSpvVNF0NbVMHt58Ci45uBwjmu_o) 4 | 5 | ![Fashion MNIST](https://github.com/zalandoresearch/fashion-mnist/raw/master/doc/img/embedding.gif) 6 | 7 | **Errinnerung**: Durch die Bearbeitung der Übungen können insgesamt bis zu **40%** Prozent der Kurspunkte erhalten werden. Diese Summe setzt sich aus der Übung in dieser Woche (15%) und der Übung in der nächsten Woche (25%) zusammen. 8 | 9 | #### Was sollt ihr in dieser Übung lernen? 10 | 11 | Ihr habt in dieser Woche die wichtigsten Tools für das Trainieren von neuronalen Netzen kennegelernt und sollt nun einmal selbst ein Netz trainieren! Dabei ist es egal, ob ihr [Google Colab](https://colab.research.google.com/) oder eine lokale Installation verwendet. 12 | 13 | Ziel ist es, ein Netz für den im folgenden vorgestellten Datensatz zu trainieren, das dessen Bilder so zuverlässig wie möglich klassifiziert. 14 | 15 | #### Welchen Datensatz sollt ihr benutzen? 16 | 17 | ![Fashion MNIST](https://s3-eu-central-1.amazonaws.com/zalando-wp-zalando-research-production/2017/08/fashion-mnist-sprite.png) 18 | 19 | Ein einfacher Datensatz, welcher sich ebenso gut für den Einstieg eignet, ist der [Fashion MNIST](https://research.zalando.com/welcome/mission/research-projects/fashion-mnist/) Datensatz von Zalando Research (ja genau, der Onlineshop :wink:), welcher aus Bildern des Modesortiments eben jenes Onlineshops besteht. Im Bild sehr ihr eine Auswahl der Trainingsbilder. 20 | 21 | Der Datensatz besteht aus **60.000 Trainings-** und **10.000 Testdaten**. Genauso wie auch bei MNIST haben die Bildmatrizen eine Größe von **28x28**, wobei jeder Eintrag der Matrix einem Graustufen-Pixelwert entspricht. 22 | Jedes Bild ist mit einer aus **10 Klassen** (*Trouser, Pullover, Dress, Coat....*) gelabeled, die genaue Liste an Klassen findet ihr [hier](https://github.com/zalandoresearch/fashion-mnist#labels). 23 | 24 | Euer Netz soll also lernen, zwischen verschiedenen Kleidungsstücken zu unterscheiden. 25 | 26 | Wie man unschwer erkennen kann, wurde dieser Datensatz von Zalando als modernere und etwas anspruchsvollere Alternative zum MNIST Datensatz entwickelt. Spielt an dieser Stelle gerne selbst einmal mit dem Datensatz herum, schaut euch die Bilder an und nutzt die Tools und Techniken die wir in dieser Woche vorgestellt haben. 27 | 28 | #### Wie bekommt ihr den Datensatz? 29 | 30 | Den Datensatz könnt ihr genau wie den MNIST Datensatz über Keras herunterladen und direkt loslegen: 31 | 32 | ```python 33 | from tensorflow import keras 34 | 35 | fashion_mnist = keras.datasets.fashion_mnist 36 | 37 | (train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data() 38 | ``` 39 | 40 | #### Ich weiß nicht wie ich anfangen soll? 41 | 42 | Falls du nicht weißt wie du am Besten anfangen solltest, schau dir am Besten noch einmal das Video zum Laden und Bearbeiten des MNIST Datensatzes aus dieser Woche an und lies das [kommentierte Notebook zum Video](../notebooks/first-mnist-net/mnist-commented-solution.ipynb). *Spoiler*: Die praktische Übung *kann* sehr ähnlich gelöst werden. 43 | 44 | Seid gerne ermutigt neue Techniken auszuprobieren und an Parametern zu schrauben! 45 | 46 | #### Wie reicht ihr eure Lösung ein? 47 | 48 | Nachdem ihr euer Keras Netz trainiert habt, könnt ihr es ganz einfach hochladen: 49 | 50 | 1. Gehe dazu auf [open.hpi.de](https://open.hpi.de/) auf die Übungsaufgabe und klicke auf *Aufgabe starten*. 51 | 2. Es sollte sich ein neuer Tab öffnen, welcher dir den Python Code anzeigt, den du zur Abgabe deines Keras Models benötigst. Alle benötigten Informationen findest du dort auch in der Beschreibung. Trotzdem an dieser Stelle noch einmal: 52 | 1. Falls noch nicht getan, installiere das Python Package zu diesem Kurs mit `pip`: 53 | ```bash 54 | pip install --upgrade deeplearning2020 55 | ``` 56 | In einem Jupyter Notebook (Google Colab oder lokal) geht das mit: 57 | ```bash 58 | !pip install --upgrade deeplearning2020 59 | ``` 60 | 2. Importieren des Package 61 | ```python 62 | from deeplearning2020 import Submission 63 | ``` 64 | 3. Submitte dein Model, wobei du den Token und die Assignment ID von der Webseite kopieren musst: 65 | ```python 66 | Submission('', '', model).submit() 67 | ``` 68 | Falls du für dein Model einen anderen Variablennamen als `model` verwendest, musst du diese Variable entsprechend verwenden. 69 | 70 | 3. Mit dem Ausführen sollte das Model von uns validiert werden und du erhaeltst abschließend eine Accuracy und Benotung. **Unserer Accuracy kann sich von euer Accuracy unterscheiden, da wir euer Model mit Werten testen, die es eventuell noch nie gesehen hat. Das gilt aber gleichermaßen für alle Teilnehmer.** 71 | 72 | **Ihr könnt euer trainiertes Model beliebig oft submitten und es wird automatisch das beste Ergebnis gewählt, ohne dass ihr etwas machen müsst.** 73 | 74 | #### Wie werden wir eure Lösungen bewerten? 75 | 76 | Uns geht es hauptsächlich darum, dass ihr selbst einmal praktisch arbeitet und mit den Tools vertraut werdet. Die Übung sollte für alle Teilnehmer gut zu meistern sein. 77 | 78 | Wir haben uns daher für folgende Bewertungsgrundlage entschieden: 79 | 80 | - Bei einer **Accuracy >= 0.8** (80%) gibt es volle Punktzahl 81 | - Bei einer **Accuracy = 0.0** (0%) gibt es 0 Punkte 82 | - Alles dazwischen wird entsprechend linear interpoliert 83 | 84 | Wir wünschen euch viel Spaß und Erfolg bei der ersten Übung! 85 | -------------------------------------------------------------------------------- /woche2/notebooks/exploring-mnist/README.md: -------------------------------------------------------------------------------- 1 | #### Laden und Bearbeiten von MNIST 2 | 3 | Notebooks 4 | - [Laden und Bearbeiten des MNIST Dataset](./exploring-mnist.ipynb) 5 | 6 | In Google Colab ist dieses Notebook unter [diesem Link](https://colab.research.google.com/drive/1U2UHDwEi_847s7lPM6vM7anw_0BaaiwV) erreichbar. 7 | -------------------------------------------------------------------------------- /woche2/notebooks/first-mnist-net/README.md: -------------------------------------------------------------------------------- 1 | #### Erstes Netz in Keras für MNIST 2 | 3 | Notebooks 4 | - [Kommentiertes Netz für MNIST](./mnist-commented-solution.ipynb) 5 | - [State-of-the-art MNIST (Ausblick)](./mnist-state-of-the-art.ipynb) 6 | 7 | In Google Colab ist die kommentierte Lösung unter [diesem Link](https://colab.research.google.com/drive/1nHF8G4cOJN1nZMBViJhWp2RRyb_wXrQi) erreichbar und der Ausblick [hier](https://colab.research.google.com/drive/1vNWbyq4rID5C4tbnA32qqNa9T5zdLdR4). 8 | -------------------------------------------------------------------------------- /woche2/notebooks/first-mnist-net/mnist-state-of-the-art.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "nbformat": 4, 3 | "nbformat_minor": 0, 4 | "metadata": { 5 | "colab": { 6 | "name": "MNIST_better_solution.ipynb", 7 | "provenance": [], 8 | "collapsed_sections": [] 9 | }, 10 | "kernelspec": { 11 | "name": "python3", 12 | "display_name": "Python 3" 13 | } 14 | }, 15 | "cells": [ 16 | { 17 | "cell_type": "markdown", 18 | "metadata": { 19 | "id": "1SX5oNyuYbhq", 20 | "colab_type": "text" 21 | }, 22 | "source": [ 23 | "# Lösung zum MNIST Datensatz mit 99.25% Genauigkeit " 24 | ] 25 | }, 26 | { 27 | "cell_type": "markdown", 28 | "metadata": { 29 | "id": "b0LtRcCeYt5v", 30 | "colab_type": "text" 31 | }, 32 | "source": [ 33 | "**HINWEIS:** Keine Angst, ihr müsst nicht verstehen was/wie in diesem Notebook gemacht wird. Wir werden euch noch die kommenden Wochen genauer erklären, was die einzelnen Netzeigenschaften sind und wofür sie gut sind. \n", 34 | "Wir wollten euch diese Lösung nur mitgeben, um zu zeigen, dass wir auch eine weitaus bessere Genauigkeit, als in dem Video zu der MNIST Lösung in Woche 2, erreichen können.\n", 35 | "\n", 36 | "Seht es somit als Motivation, was wir in dem Kurs alles noch lernen und wie stark wir uns damit verbessern werden." 37 | ] 38 | }, 39 | { 40 | "cell_type": "markdown", 41 | "metadata": { 42 | "id": "PwgcVJf2XqiJ", 43 | "colab_type": "text" 44 | }, 45 | "source": [ 46 | "In diesem Notebook wird ein \"Convolutional Neural Network\" (was Convolutional bedeutet erfahrt ihr in Woche 3) mit dem MNIST Datensatz verwendet. \n", 47 | "\n", 48 | "Dieses Netz erreicht bis zu 99.25% Genauigkeit bei den Testdaten nach 12 Epochen. Hierbei kann eventuell noch eine höhere Genauigkeit erreicht werden, wenn man an den Parametern herum schraubt. Solltet ihr daran interesse haben und generell sehen wollen, wie Veränderungen der Parameter eventuell die Genauigkeit beeinflussen, dann spielt damit doch einmal herum. " 49 | ] 50 | }, 51 | { 52 | "cell_type": "code", 53 | "metadata": { 54 | "id": "lIBLDTxm7qDA", 55 | "colab_type": "code", 56 | "outputId": "015e7264-22d4-4007-efe4-30fa9cff71ba", 57 | "colab": { 58 | "base_uri": "https://localhost:8080/", 59 | "height": 1000 60 | } 61 | }, 62 | "source": [ 63 | "from __future__ import print_function\n", 64 | "import keras\n", 65 | "from keras.datasets import mnist\n", 66 | "from keras.models import Sequential\n", 67 | "from keras.layers import Dense # Diese Art von Schicht kennen wir bereits\n", 68 | "from keras.layers import Conv2D, MaxPooling2D, Dropout, Flatten # Diese Schichten lernen wir in Woche 3 und 4 näher kennen\n", 69 | "from keras import backend as K\n", 70 | "\n", 71 | "batch_size = 128 # Batch Größe\n", 72 | "num_classes = 10 # Anzahl der Klassen (Ausgabeneuronen - Zahlen zwischen 0 und 9)\n", 73 | "epochs = 12 # Anzahl der Epochen\n", 74 | "img_rows, img_cols = 28, 28 # Dimension der Eingabedaten\n", 75 | "\n", 76 | "(x_train, y_train), (x_test, y_test) = mnist.load_data() # Laden der Daten und aufteilen in Trainings- und Testdaten\n", 77 | "\n", 78 | "# Notwendige Umformungen der Daten für die anschließende Verwendung in dem \"Convolutional Neural Network\"\n", 79 | "if K.image_data_format() == 'channels_first':\n", 80 | " x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols)\n", 81 | " x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols)\n", 82 | " input_shape = (1, img_rows, img_cols)\n", 83 | "else:\n", 84 | " x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1)\n", 85 | " x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1)\n", 86 | " input_shape = (img_rows, img_cols, 1)\n", 87 | "\n", 88 | "x_train = x_train.astype('float32') # notwendige Datentypkonvertierung\n", 89 | "x_test = x_test.astype('float32') # notwendige Datentypkonvertierung\n", 90 | "x_train /= 255 # Normalisierung der Trainingsdaten\n", 91 | "x_test /= 255 # Normalisierung der Testdaten\n", 92 | "\n", 93 | "# Wie bereits bekannt, erwarten wir die Labels als Vektor (z.b. 5 als [0,0,0,0,0,1,0,0,0,0])\n", 94 | "y_train = keras.utils.to_categorical(y_train, num_classes) # Umformung der Trainingslabel\n", 95 | "y_test = keras.utils.to_categorical(y_test, num_classes) # Umformung der Testlabel\n", 96 | "\n", 97 | "model = Sequential([\n", 98 | " Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=input_shape), # Werden wir in Woche 3 kennenlernen!\n", 99 | " Conv2D(64, (3, 3), activation='relu'), # Werden wir in Woche 3 kennenlernen!\n", 100 | " MaxPooling2D(pool_size=(2, 2)), # Werden wir in Woche 3 kennenlernen!\n", 101 | " Dropout(0.25), # Werden wir in Woche 4 kennenlernen!\n", 102 | " Flatten(), # Werden wir in Woche 3 kennenlernen!\n", 103 | " Dense(128, activation='relu'), # Kennen wir bereits!\n", 104 | " Dropout(0.5), # Werden wir in Woche 4 kennenlernen!\n", 105 | " Dense(num_classes, activation='softmax'), # Die Aktivierungsfunktion Softmax werden wir in Woche 3 kennenlernen!\n", 106 | "])\n", 107 | "\n", 108 | "model.compile(loss=keras.losses.categorical_crossentropy, # Die Kostenfunktion categorical_crossentropy werden wir in Woche 3 kennenlernen!\n", 109 | " optimizer=keras.optimizers.Adadelta(), # Den Optimizer Adadelta werden wir in Woche 3 kennenlernen!\n", 110 | " metrics=['accuracy'])\n", 111 | "\n", 112 | "model.fit(x_train, y_train,\n", 113 | " batch_size=batch_size, # Kennen wir bereits!\n", 114 | " epochs=epochs, # Kennen wir bereits!\n", 115 | " verbose=1,\n", 116 | " validation_data=(x_test, y_test)) # Wir validieren nach jeder Epoche, wie hoch die derzeitige Genauigkeit ist und übergeben hierfür die gesamten Testdaten (mit diesen wird nicht trainiert).\n", 117 | "\n", 118 | "score = model.evaluate(x_test, y_test, verbose=0) # Wir berechnen die Genauigkeit des Netzes, um sie nachfolgend ordentlich anzugeben\n", 119 | "\n", 120 | "print('Fehler auf den Testdaten:', score[0]) # Ausgabe der Ergebnisse\n", 121 | "print('Accuracy auf den Testdaten:', score[1])" 122 | ], 123 | "execution_count": 0, 124 | "outputs": [ 125 | { 126 | "output_type": "stream", 127 | "text": [ 128 | "Using TensorFlow backend.\n" 129 | ], 130 | "name": "stderr" 131 | }, 132 | { 133 | "output_type": "display_data", 134 | "data": { 135 | "text/html": [ 136 | "

\n", 137 | "The default version of TensorFlow in Colab will soon switch to TensorFlow 2.x.
\n", 138 | "We recommend you upgrade now \n", 139 | "or ensure your notebook will continue to use TensorFlow 1.x via the %tensorflow_version 1.x magic:\n", 140 | "more info.

\n" 141 | ], 142 | "text/plain": [ 143 | "" 144 | ] 145 | }, 146 | "metadata": { 147 | "tags": [] 148 | } 149 | }, 150 | { 151 | "output_type": "stream", 152 | "text": [ 153 | "Downloading data from https://s3.amazonaws.com/img-datasets/mnist.npz\n", 154 | "11493376/11490434 [==============================] - 0s 0us/step\n", 155 | "WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/keras/backend/tensorflow_backend.py:66: The name tf.get_default_graph is deprecated. Please use tf.compat.v1.get_default_graph instead.\n", 156 | "\n", 157 | "WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/keras/backend/tensorflow_backend.py:541: The name tf.placeholder is deprecated. Please use tf.compat.v1.placeholder instead.\n", 158 | "\n", 159 | "WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/keras/backend/tensorflow_backend.py:4432: The name tf.random_uniform is deprecated. Please use tf.random.uniform instead.\n", 160 | "\n", 161 | "WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/keras/backend/tensorflow_backend.py:4267: The name tf.nn.max_pool is deprecated. Please use tf.nn.max_pool2d instead.\n", 162 | "\n", 163 | "WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/keras/backend/tensorflow_backend.py:148: The name tf.placeholder_with_default is deprecated. Please use tf.compat.v1.placeholder_with_default instead.\n", 164 | "\n", 165 | "WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/keras/backend/tensorflow_backend.py:3733: calling dropout (from tensorflow.python.ops.nn_ops) with keep_prob is deprecated and will be removed in a future version.\n", 166 | "Instructions for updating:\n", 167 | "Please use `rate` instead of `keep_prob`. Rate should be set to `rate = 1 - keep_prob`.\n", 168 | "WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/keras/optimizers.py:793: The name tf.train.Optimizer is deprecated. Please use tf.compat.v1.train.Optimizer instead.\n", 169 | "\n", 170 | "WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/keras/backend/tensorflow_backend.py:3576: The name tf.log is deprecated. Please use tf.math.log instead.\n", 171 | "\n", 172 | "WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensorflow_core/python/ops/math_grad.py:1424: where (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.\n", 173 | "Instructions for updating:\n", 174 | "Use tf.where in 2.0, which has the same broadcast rule as np.where\n", 175 | "WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/keras/backend/tensorflow_backend.py:1033: The name tf.assign_add is deprecated. Please use tf.compat.v1.assign_add instead.\n", 176 | "\n", 177 | "WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/keras/backend/tensorflow_backend.py:1020: The name tf.assign is deprecated. Please use tf.compat.v1.assign instead.\n", 178 | "\n", 179 | "WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/keras/backend/tensorflow_backend.py:3005: The name tf.Session is deprecated. Please use tf.compat.v1.Session instead.\n", 180 | "\n", 181 | "Train on 60000 samples, validate on 10000 samples\n", 182 | "Epoch 1/12\n", 183 | "WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/keras/backend/tensorflow_backend.py:190: The name tf.get_default_session is deprecated. Please use tf.compat.v1.get_default_session instead.\n", 184 | "\n", 185 | "WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/keras/backend/tensorflow_backend.py:197: The name tf.ConfigProto is deprecated. Please use tf.compat.v1.ConfigProto instead.\n", 186 | "\n", 187 | "WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/keras/backend/tensorflow_backend.py:207: The name tf.global_variables is deprecated. Please use tf.compat.v1.global_variables instead.\n", 188 | "\n", 189 | "WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/keras/backend/tensorflow_backend.py:216: The name tf.is_variable_initialized is deprecated. Please use tf.compat.v1.is_variable_initialized instead.\n", 190 | "\n", 191 | "WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/keras/backend/tensorflow_backend.py:223: The name tf.variables_initializer is deprecated. Please use tf.compat.v1.variables_initializer instead.\n", 192 | "\n", 193 | "60000/60000 [==============================] - 151s 3ms/step - loss: 0.2701 - acc: 0.9168 - val_loss: 0.0646 - val_acc: 0.9796\n", 194 | "Epoch 2/12\n", 195 | "60000/60000 [==============================] - 150s 2ms/step - loss: 0.0893 - acc: 0.9740 - val_loss: 0.0395 - val_acc: 0.9869\n", 196 | "Epoch 3/12\n", 197 | "60000/60000 [==============================] - 150s 3ms/step - loss: 0.0669 - acc: 0.9803 - val_loss: 0.0383 - val_acc: 0.9875\n", 198 | "Epoch 4/12\n", 199 | "60000/60000 [==============================] - 150s 3ms/step - loss: 0.0534 - acc: 0.9842 - val_loss: 0.0352 - val_acc: 0.9891\n", 200 | "Epoch 5/12\n", 201 | "60000/60000 [==============================] - 150s 2ms/step - loss: 0.0468 - acc: 0.9863 - val_loss: 0.0280 - val_acc: 0.9902\n", 202 | "Epoch 6/12\n", 203 | "60000/60000 [==============================] - 150s 3ms/step - loss: 0.0415 - acc: 0.9880 - val_loss: 0.0272 - val_acc: 0.9912\n", 204 | "Epoch 7/12\n", 205 | "60000/60000 [==============================] - 149s 2ms/step - loss: 0.0380 - acc: 0.9889 - val_loss: 0.0320 - val_acc: 0.9883\n", 206 | "Epoch 8/12\n", 207 | "60000/60000 [==============================] - 150s 2ms/step - loss: 0.0341 - acc: 0.9897 - val_loss: 0.0293 - val_acc: 0.9909\n", 208 | "Epoch 9/12\n", 209 | "60000/60000 [==============================] - 150s 2ms/step - loss: 0.0296 - acc: 0.9909 - val_loss: 0.0255 - val_acc: 0.9912\n", 210 | "Epoch 10/12\n", 211 | "60000/60000 [==============================] - 150s 2ms/step - loss: 0.0291 - acc: 0.9910 - val_loss: 0.0280 - val_acc: 0.9912\n", 212 | "Epoch 11/12\n", 213 | "60000/60000 [==============================] - 149s 2ms/step - loss: 0.0257 - acc: 0.9921 - val_loss: 0.0346 - val_acc: 0.9900\n", 214 | "Epoch 12/12\n", 215 | "60000/60000 [==============================] - 149s 2ms/step - loss: 0.0257 - acc: 0.9919 - val_loss: 0.0281 - val_acc: 0.9924\n", 216 | "Fehler auf den Testdaten: 0.02806703284695959\n", 217 | "Accuracy auf den Testdaten: 0.9924\n" 218 | ], 219 | "name": "stdout" 220 | } 221 | ] 222 | } 223 | ] 224 | } -------------------------------------------------------------------------------- /woche2/notebooks/intro-matplotlib/README.md: -------------------------------------------------------------------------------- 1 | #### Einführung in `matplotlib` 2 | 3 | Notebooks 4 | - [Einführung in `matplotlib`](./intro-matplotlib.ipynb) 5 | 6 | In Google Colab ist dieses Notebook unter [diesem Link](https://colab.research.google.com/drive/1wLMmknNlbV0auXZv1-NuI7WJuE0gKoez) erreichbar. 7 | -------------------------------------------------------------------------------- /woche2/notebooks/intro-numpy/README.md: -------------------------------------------------------------------------------- 1 | #### Einführung in `numpy` 2 | 3 | Notebooks 4 | - [Einführung in `numpy`](./intro-numpy.ipynb) 5 | 6 | In Google Colab ist dieses Notebook unter [diesem Link](https://colab.research.google.com/drive/1jF16dEsdK_CoXuHc-oWgtD_0xha6Ocoo) erreichbar. 7 | -------------------------------------------------------------------------------- /woche2/notebooks/intro-tensorflow-keras/README.md: -------------------------------------------------------------------------------- 1 | #### Einführung in `tensorflow` und `keras` 2 | 3 | Notebooks 4 | - [Einführung in `tensorflow` und `keras`](./intro-tensorflow-keras.ipynb) 5 | 6 | In Google Colab ist dieses Notebook unter [diesem Link](https://colab.research.google.com/drive/1f6NU11i6G4tG7MRvozpFDUdBC8pI8iyK) erreichbar. 7 | -------------------------------------------------------------------------------- /woche2/notebooks/intro-tensorflow-keras/intro-tensorflow-keras.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "nbformat": 4, 3 | "nbformat_minor": 0, 4 | "metadata": { 5 | "colab": { 6 | "name": "intro-tensorflow-keras.ipynb", 7 | "provenance": [], 8 | "collapsed_sections": [] 9 | }, 10 | "kernelspec": { 11 | "name": "python3", 12 | "display_name": "Python 3" 13 | }, 14 | "pycharm": { 15 | "stem_cell": { 16 | "cell_type": "raw", 17 | "source": [], 18 | "metadata": { 19 | "collapsed": false 20 | } 21 | } 22 | } 23 | }, 24 | "cells": [ 25 | { 26 | "cell_type": "markdown", 27 | "metadata": { 28 | "id": "6ZBGfn2537Vd", 29 | "colab_type": "text" 30 | }, 31 | "source": [ 32 | "# Einführung Tensorflow/Keras" 33 | ] 34 | }, 35 | { 36 | "cell_type": "markdown", 37 | "metadata": { 38 | "id": "pgqbFDDM4Ifh", 39 | "colab_type": "text" 40 | }, 41 | "source": [ 42 | "## Keras sequential model API" 43 | ] 44 | }, 45 | { 46 | "cell_type": "markdown", 47 | "metadata": { 48 | "id": "yxOOgazUG2LS", 49 | "colab_type": "text" 50 | }, 51 | "source": [ 52 | "Das sequentielle Model ist **ein linearer Stapel** von Schichten (von Neuronen).\n", 53 | "\n", 54 | "**Import**\n", 55 | "```python\n", 56 | "from keras.models import Sequential\n", 57 | "from keras.layers import Dense, Activation\n", 58 | "```\n", 59 | "\n", 60 | "Man kann ein sequentielles Model erstellen, indem man an den Konstruktor eine **Liste der Schichten** übergibt, die man nutzen will:\n", 61 | "```python\n", 62 | "model = Sequential([\n", 63 | " Dense(32, input_dim=784), \n", 64 | " Activation('linear'),\n", 65 | "])\n", 66 | "```\n", 67 | "\n", 68 | "* `Dense()` ist eine \"dichte\" Schicht, jedes Neuron ist mit jedem Neuron der folgenden Schicht verbunden\n", 69 | " * `Dense(32)` bedeutet, dass diese Schicht aus 32 Neuronen besteht\n", 70 | " * `input_dim=784` ist die Spezifizierung der Eingabeform\n", 71 | " * bedeutet, die Eingabe soll ein 784-dimensionaler Vektor sein\n", 72 | "* `Activation()` ist die Angabe der Aktivierungsfunktion der Neuronen (Erinnerung an die Treppenfunktion)\n", 73 | " * `Activation('linear')` ist die lineare Aktivierungsfunktion" 74 | ] 75 | }, 76 | { 77 | "cell_type": "markdown", 78 | "metadata": { 79 | "id": "wLAUv2rhLeTe", 80 | "colab_type": "text" 81 | }, 82 | "source": [ 83 | "### Alternative Schreibweise (add-Funktion)\n", 84 | "Wir können das Gleiche erreichen durch die `.add()` - Funktion:\n", 85 | "```python\n", 86 | "model = Sequential()\n", 87 | "model.add(Dense(32, input_dim=784))\n", 88 | "model.add(Activation('linear'))\n", 89 | "```" 90 | ] 91 | }, 92 | { 93 | "cell_type": "markdown", 94 | "metadata": { 95 | "id": "QeGvCO8hN9nc", 96 | "colab_type": "text" 97 | }, 98 | "source": [ 99 | "### Model konfigurieren und kompilieren\n", 100 | "\n", 101 | "**`compile` - Funktion:**\n", 102 | "* Konfiguration des Models\n", 103 | " * Wir **müssen** einen **Optimizer** angeben (sonst kann das Netz nicht lernen).\n", 104 | " * auch eine Fehlerfunktion und eine Metrik (Messen der Genauigkeit) können wir angeben\n", 105 | " * *Die weiteren Parameter brauchen wir an dieser Stelle nicht.*\n", 106 | " * *Fortgeschrittene Teilnehmer finden deren Definition hier:* [Keras Dokumentation](https://keras.io/models/model/#compile)\n", 107 | "\n", 108 | "```python\n", 109 | "model.compile(optimizer, loss=None, metrics=None, loss_weights=None, sample_weight_mode=None, weighted_metrics=None, target_tensors=None)\n", 110 | "```" 111 | ] 112 | }, 113 | { 114 | "cell_type": "markdown", 115 | "metadata": { 116 | "id": "9PEfQwJEOBni", 117 | "colab_type": "text" 118 | }, 119 | "source": [ 120 | "### Model trainieren\n", 121 | "\n", 122 | "**`fit` - Funktion:**\n", 123 | "* Training des Models\n", 124 | " * Wir übergeben \n", 125 | " * die **Eingabedaten** (Array oder Liste)\n", 126 | " * die **Ziel-Daten** (gewünschtes Ergebnis pro Eintrag)\n", 127 | " * Die *Batch-Größe* beschreibt wie viele Einträge druch das Netz gefüttert werden, bevor der Gradient für die nächste Anpassung berechnet wird.\n", 128 | " * Eine *Epoche* ist eine vollständige Iteration über den gesamten Datensatz (alle Batches). Wir geben an, wie viele davon durchgeführt werden sollen.\n", 129 | "\n", 130 | "```python\n", 131 | "model.fit(x=None, y=None, batch_size=None, epochs=1, verbose=1, callbacks=None, validation_split=0.0, validation_data=None, shuffle=True, class_weight=None, sample_weight=None, initial_epoch=0, steps_per_epoch=None, validation_steps=None, validation_freq=1, max_queue_size=10, workers=1, use_multiprocessing=False)\n", 132 | "```\n" 133 | ] 134 | }, 135 | { 136 | "cell_type": "markdown", 137 | "metadata": { 138 | "id": "Abip37MZOGJ-", 139 | "colab_type": "text" 140 | }, 141 | "source": [ 142 | "### Model evaluieren\n", 143 | "\n", 144 | "**`evaluate` - Funktion:**\n", 145 | "* Evaluierung des Models\n", 146 | " * Gibt die Fehler- und Genauigkeitsmetriken des Models zurück\n", 147 | " * Berechnung jeweils pro Batch\n", 148 | " * Wir übergeben (wie in der `fit` Funktion)\n", 149 | " * die **Eingabedaten** (in diesem Falle die Trainingsdaten als Array oder Liste)\n", 150 | " * die **Ziel-Daten** (gewünschtes Ergebnis pro Eintrag)\n", 151 | "\n", 152 | "```python\n", 153 | "model.evaluate(x=None, y=None, batch_size=None, verbose=1, sample_weight=None, steps=None, callbacks=None, max_queue_size=10, workers=1, use_multiprocessing=False)\n", 154 | "```\n" 155 | ] 156 | }, 157 | { 158 | "cell_type": "markdown", 159 | "metadata": { 160 | "id": "qVEFcmb02ulZ", 161 | "colab_type": "text" 162 | }, 163 | "source": [ 164 | "### Model trifft Vorhersagen\n", 165 | "\n", 166 | "**`predict` - Funktion:**\n", 167 | "* Vorhersagungen des Models\n", 168 | " * Vorhersage der Labels der Testdaten (noch nicht gesehene Daten)\n", 169 | " * Berechnung erfolgt wieder auf Batches (deren Größe wir angeben sollten).\n", 170 | "\n", 171 | "```python\n", 172 | "model.predict(x, batch_size=None, verbose=0, steps=None, callbacks=None, max_queue_size=10, workers=1, use_multiprocessing=False)\n", 173 | "```" 174 | ] 175 | }, 176 | { 177 | "cell_type": "markdown", 178 | "metadata": { 179 | "id": "gN9RmOcm4Qqc", 180 | "colab_type": "text" 181 | }, 182 | "source": [ 183 | "## Keras functional model API" 184 | ] 185 | }, 186 | { 187 | "cell_type": "markdown", 188 | "metadata": { 189 | "id": "kMvn6CeGN1_Z", 190 | "colab_type": "text" 191 | }, 192 | "source": [ 193 | "Die Keras functional API bietet mehr Freiheiten in der **Definition komplexer neuronaler Netze**.\n", 194 | "\n", 195 | "Die functional API wird in der Praxis häufiger genutzt als die sequential model API, da diese mehr für einfache Netze geeignet ist." 196 | ] 197 | }, 198 | { 199 | "cell_type": "markdown", 200 | "metadata": { 201 | "id": "myN8aocVVaKv", 202 | "colab_type": "text" 203 | }, 204 | "source": [ 205 | "### Beispiel an einem vollständig verbundenem Netzwerk\n", 206 | "\n", 207 | "*Eigentlich wäre für dieses einfache Netz die Sequential model API vollkommen ausreichend, aber an so einem Beispiel kann man die API besser verstehen.*\n", 208 | "\n", 209 | "Eine `layer`-Instanz ist aufrufbar auf einem `tensor`. Die Rückgabe ist ein Eingabetensor und ein Ausgabetensor. Das kann genutzt werden, um ein Modell zu definieren, genau wie in der *sequentiall model API*.\n", 210 | "\n", 211 | "**Import:**\n", 212 | "```python\n", 213 | "from keras.layers import Input, Dense\n", 214 | "from keras.models import Model\n", 215 | "```\n", 216 | "**Eingabe definieren:**\n", 217 | "```python\n", 218 | "# gibt Tensor zurück\n", 219 | "inputs = Input(shape=(784,))\n", 220 | "```\n", 221 | "**`layer` Instanzen aufrufen**:\n", 222 | "* können hier beliebige Schichten kombinieren\n", 223 | "\n", 224 | "```python\n", 225 | "# eine Schicht ist aufrufbar auf einem tensor und gibt einen tensor zurück\n", 226 | "output_1 = Dense(64, activation='linear')(inputs)\n", 227 | "output_2 = Dense(64, activation='linear')(output_1)\n", 228 | "predictions = Dense(10, activation='linear')(output_2)\n", 229 | "```\n", 230 | "**Model erstellen:**\n", 231 | "```python\n", 232 | "# Erstellt ein Model mit einer Eingabeschicht und drei \"Dense\" Schichten\n", 233 | "model = Model(inputs=inputs, outputs=predictions)\n", 234 | "```\n", 235 | "**Model konfigurieren**:\n", 236 | "```python\n", 237 | "model.compile(optimizer='', loss='', metrics=[''])\n", 238 | "```\n", 239 | "**Model trainieren**:\n", 240 | "\n", 241 | "```python\n", 242 | "model.fit(data, labels) # beginnt Training\n", 243 | "```\n" 244 | ] 245 | }, 246 | { 247 | "cell_type": "markdown", 248 | "metadata": { 249 | "id": "Sd8JoU1LZFZE", 250 | "colab_type": "text" 251 | }, 252 | "source": [ 253 | "### Wiederverwendung von Models\n", 254 | "Alle `model` sind aufrufbar, genau wie `layer`\n", 255 | "\n", 256 | "Dadurch ist es mit der functional API sehr einfach möglich Modele wiederzuverwenden:\n", 257 | "* ein `model` kann wie eine `layer` behandelt werden und auf einem `tensor` aufgerufen werden\n", 258 | "\n", 259 | "**Merke:** Man verwendet nicht nur den Aufbau des Models, sondern auch die Gewichte!\n", 260 | "\n", 261 | "```python\n", 262 | "x = Input(shape=(784,))\n", 263 | "y = model(x)\n", 264 | "```\n", 265 | "\n", 266 | "**Vorteil:** Man kann sehr schnell Modelle bauen, die verschiedene Eingaben entgegennehmen." 267 | ] 268 | } 269 | ] 270 | } -------------------------------------------------------------------------------- /woche2/notebooks/mnist-activation-functions/README.md: -------------------------------------------------------------------------------- 1 | #### MNIST Lösung mit verschiedenen Aktivierungsfunktionen 2 | 3 | Notebooks 4 | - [MNIST Lösung mit verschiedenen Aktivierungsfunktionen](./mnist-activation-functions.ipynb) 5 | 6 | In Google Colab ist dieses Notebook unter [diesem Link](https://colab.research.google.com/drive/13AamhvJLedv7t9sDWbw7mYcqdunKldC3) erreichbar. 7 | -------------------------------------------------------------------------------- /woche3/README.md: -------------------------------------------------------------------------------- 1 | #### Woche 3 2 | 3 | In der dritten Woche geht es vor allem darum komplexere Layerstrukturen kennenzulernen, um effizient komplexe Datensätze zum Training eines neuronalen Netzes zu verwenden. Diese Datensätze bestehen aus hochauflösenden Bilder, im Vergleich zum MNIST Datensatz. Ebenso lernen wir in der dritten Woche weitere Parameter kennen und wie mit diesen das Netz optimiert werden kann. 4 | 5 | ##### Inhalt 6 | - [Notebooks](./notebooks/) 7 | - [Komplexe Layerstruktur](./notebooks/complex-layer-structure/) 8 | - [Loss Functions](./notebooks/loss-functions/) 9 | - [Optimizer](./notebooks/optimizer/) 10 | - [Hyperparameter](./notebooks/hyperparameter/) 11 | - [Exkurs: Neuronale Netze von Scratch](./scratch-net) 12 | - [Praktische Übungen](./assignment/) 13 | - [Bewertete Übung](./assignment/exercise2/) 14 | - [Zusätzliche Übung](./assignment/additional/) 15 | -------------------------------------------------------------------------------- /woche3/assignment/additional/README.md: -------------------------------------------------------------------------------- 1 | ## Informationen zu weiteren Übungsmöglichkeiten 2 | 3 | Im Internet und vor allem direkt in [Tensorflow](https://www.tensorflow.org/datasets/catalog/overview) gibt es einige Datensätze mit denen das erlernte Wissen ganz einfach auf die Probe gestellt werden kann. Seid also neugierig und spielt gerne so viel ihr wollt mit diesen Datensätzen herum. Solange ihr es während der Kurslaufzeit tut, können eventuell aufkommende Fragen noch im Forum geklärt werden. 4 | 5 | Da ihr in der aktuellen Übung in dieser Woche noch keine optimalen Ergebnisse erzielen werdet und durch die Inhalte der nächsten Woche euer Netz stark verbessern könnt, wollten wir euch an dieser Stelle nochmal speziell die Möglichkeit geben, eine bessere Genauigkeit mit den bis jetzt erlernten Methoden zu erzielen. 6 | 7 | Der Datensatz, den wir euch hierfür vorstellen wollen, nennt sich `deep_weeds` und enthält Bilder von 9 verschiedenen Gräsern. Ebenso steht er ganz unkompliziert unter den Tensorflow Datasätzen zur Verfügbar. Weitere Informationen findet ihr [hier](https://www.tensorflow.org/datasets/catalog/deep_weeds). 8 | 9 | Diese weitere Übungsmöglichkeit ist **komplett freiwillig** und es wird somit **keine Punkte** geben. 10 | 11 | ### Einbindung des Datensatzes 12 | 13 | Über folgenden Befehl kann der Datensatz genauso wie der in Woche 3 behandelte Datensatz eingebunden werden: 14 | 15 | ```python 16 | train_data_weed = tfds.load( 17 | 'deep_weeds', 18 | split='train[:80%]', 19 | as_supervised=True, 20 | with_info=True 21 | ) 22 | 23 | test_data_weed = tfds.load( 24 | 'deep_weeds', 25 | split='train[80%:]', 26 | as_supervised=True, 27 | with_info=True 28 | ) 29 | ``` 30 | 31 | Viel Erfolg bei der Bearbeitung. 32 | -------------------------------------------------------------------------------- /woche3/assignment/exercise2/Exercise_2_solution_week_3.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "nbformat": 4, 3 | "nbformat_minor": 0, 4 | "metadata": { 5 | "accelerator": "GPU", 6 | "colab": { 7 | "name": "Exercise 2 - solution week 3", 8 | "provenance": [], 9 | "collapsed_sections": [], 10 | "machine_shape": "hm" 11 | }, 12 | "kernelspec": { 13 | "display_name": "Python [conda env:MOOC] *", 14 | "language": "python", 15 | "name": "conda-env-MOOC-py" 16 | }, 17 | "language_info": { 18 | "codemirror_mode": { 19 | "name": "ipython", 20 | "version": 3 21 | }, 22 | "file_extension": ".py", 23 | "mimetype": "text/x-python", 24 | "name": "python", 25 | "nbconvert_exporter": "python", 26 | "pygments_lexer": "ipython3", 27 | "version": "3.6.9" 28 | } 29 | }, 30 | "cells": [ 31 | { 32 | "cell_type": "markdown", 33 | "metadata": { 34 | "id": "ntOuL-4wHtZ9", 35 | "colab_type": "text" 36 | }, 37 | "source": [ 38 | "# Lösung Übung 2 - Woche 3 und 4\n", 39 | "\n", 40 | "Mit dem Wissen aus Woche 3 konnte man noch keine sehr zufriedenstellenden Ergebnisse erzielen. Das Problem hierbei war das schnelle Overfitting auf die Daten, da Dropout noch nicht bekannt war und auch Batch Normalization erst in Woche 4 vorgestellt wurde.\n", 41 | "\n", 42 | "Da alle Bilder Hunde zeigen, die sich nicht so einfach voneinander unterscheiden lassen wie die Klassen im ImageNette Datensatz, war hier eine Genauigkeit von 40-50% zu erreichen.\n", 43 | "\n", 44 | "Dieses Notebook stellt keine optimale Lösung dar, soll euch aber zeigen, welches grobe Netz gewählt werden kann.\n" 45 | ] 46 | }, 47 | { 48 | "cell_type": "code", 49 | "metadata": { 50 | "id": "BlNuB2X7JSK6", 51 | "colab_type": "code", 52 | "colab": {} 53 | }, 54 | "source": [ 55 | "%tensorflow_version 2.x" 56 | ], 57 | "execution_count": 0, 58 | "outputs": [] 59 | }, 60 | { 61 | "cell_type": "code", 62 | "metadata": { 63 | "colab_type": "code", 64 | "id": "PRNIed8V-Rry", 65 | "colab": {} 66 | }, 67 | "source": [ 68 | "# TensorFlow ≥2.0 is required\n", 69 | "import tensorflow as tf\n", 70 | "from tensorflow import keras\n", 71 | "assert tf.__version__ >= \"2.0\"\n", 72 | "\n", 73 | "if not tf.test.is_gpu_available():\n", 74 | " print(\"No GPU was detected. CNNs can be very slow without a GPU.\")\n", 75 | " if IS_COLAB:\n", 76 | " print(\"Go to Runtime > Change runtime and select a GPU hardware accelerator.\")\n" 77 | ], 78 | "execution_count": 0, 79 | "outputs": [] 80 | }, 81 | { 82 | "cell_type": "code", 83 | "metadata": { 84 | "colab_type": "code", 85 | "id": "ZO6p-aRv99m-", 86 | "colab": {} 87 | }, 88 | "source": [ 89 | "import numpy as np\n", 90 | "import matplotlib.pyplot as plt\n", 91 | "import tensorflow as tf\n", 92 | "import tensorflow_datasets as tfds\n", 93 | "import numpy as np\n", 94 | "from tensorflow.keras.datasets import mnist\n", 95 | "from tensorflow.keras.layers import Dense, Activation, Input, \\\n", 96 | " Dropout, Conv2D, MaxPooling2D, Flatten\n", 97 | "from tensorflow.keras.models import Model\n", 98 | "import matplotlib.pyplot as plt\n", 99 | "from scipy.stats import reciprocal\n", 100 | "from sklearn.model_selection import GridSearchCV, RandomizedSearchCV\n", 101 | "\n", 102 | "# jupyters magic command\n", 103 | "%matplotlib inline" 104 | ], 105 | "execution_count": 0, 106 | "outputs": [] 107 | }, 108 | { 109 | "cell_type": "code", 110 | "metadata": { 111 | "id": "B0de0EjqZ6i7", 112 | "colab_type": "code", 113 | "outputId": "7dd686bc-5e8a-4b43-b509-a3b25677e76f", 114 | "colab": { 115 | "base_uri": "https://localhost:8080/", 116 | "height": 446 117 | } 118 | }, 119 | "source": [ 120 | "!pip install --upgrade deeplearning2020" 121 | ], 122 | "execution_count": 0, 123 | "outputs": [ 124 | { 125 | "output_type": "stream", 126 | "text": [ 127 | "Collecting deeplearning2020\n", 128 | " Downloading https://files.pythonhosted.org/packages/3a/7f/6fee39d7590f4ae20a976131b1920d56a3dee138c208dfcb3959cd8c5275/deeplearning2020-0.4.21.tar.gz\n", 129 | "Collecting kerasltisubmission>=0.4.9\n", 130 | " Using cached https://files.pythonhosted.org/packages/de/56/0b6adef8e6f5d89e9daa68e03d00850509f1553ce6303c0a49d7c619dd26/kerasltisubmission-0.4.9.tar.gz\n", 131 | "Requirement already satisfied, skipping upgrade: numpy in /usr/local/lib/python3.6/dist-packages (from kerasltisubmission>=0.4.9->deeplearning2020) (1.18.2)\n", 132 | "Requirement already satisfied, skipping upgrade: progressbar2 in /usr/local/lib/python3.6/dist-packages (from kerasltisubmission>=0.4.9->deeplearning2020) (3.38.0)\n", 133 | "Requirement already satisfied, skipping upgrade: requests in /usr/local/lib/python3.6/dist-packages (from kerasltisubmission>=0.4.9->deeplearning2020) (2.21.0)\n", 134 | "Requirement already satisfied, skipping upgrade: python-utils>=2.3.0 in /usr/local/lib/python3.6/dist-packages (from progressbar2->kerasltisubmission>=0.4.9->deeplearning2020) (2.4.0)\n", 135 | "Requirement already satisfied, skipping upgrade: six in /usr/local/lib/python3.6/dist-packages (from progressbar2->kerasltisubmission>=0.4.9->deeplearning2020) (1.12.0)\n", 136 | "Requirement already satisfied, skipping upgrade: certifi>=2017.4.17 in /usr/local/lib/python3.6/dist-packages (from requests->kerasltisubmission>=0.4.9->deeplearning2020) (2020.4.5.1)\n", 137 | "Requirement already satisfied, skipping upgrade: idna<2.9,>=2.5 in /usr/local/lib/python3.6/dist-packages (from requests->kerasltisubmission>=0.4.9->deeplearning2020) (2.8)\n", 138 | "Requirement already satisfied, skipping upgrade: urllib3<1.25,>=1.21.1 in /usr/local/lib/python3.6/dist-packages (from requests->kerasltisubmission>=0.4.9->deeplearning2020) (1.24.3)\n", 139 | "Requirement already satisfied, skipping upgrade: chardet<3.1.0,>=3.0.2 in /usr/local/lib/python3.6/dist-packages (from requests->kerasltisubmission>=0.4.9->deeplearning2020) (3.0.4)\n", 140 | "Building wheels for collected packages: deeplearning2020, kerasltisubmission\n", 141 | " Building wheel for deeplearning2020 (setup.py) ... \u001b[?25l\u001b[?25hdone\n", 142 | " Created wheel for deeplearning2020: filename=deeplearning2020-0.4.21-py2.py3-none-any.whl size=8548 sha256=0ea0830d515fd509f6c003f900371260b49d96430d28f264643bbaae8ab7e93f\n", 143 | " Stored in directory: /root/.cache/pip/wheels/7f/c2/8a/f9f03fc839999f1fe9d5e5a9d2c97cdd5cb8329f61f82ea2c9\n", 144 | " Building wheel for kerasltisubmission (setup.py) ... \u001b[?25l\u001b[?25hdone\n", 145 | " Created wheel for kerasltisubmission: filename=kerasltisubmission-0.4.9-py2.py3-none-any.whl size=8867 sha256=46676efb4bbbe76f1b54684d83c45b469e905af7cf8d5966a5e4826eac478735\n", 146 | " Stored in directory: /root/.cache/pip/wheels/fd/61/f7/09171376b25408ae21b58e98c9fbf2eb924f676bb77659f983\n", 147 | "Successfully built deeplearning2020 kerasltisubmission\n", 148 | "Installing collected packages: kerasltisubmission, deeplearning2020\n", 149 | "Successfully installed deeplearning2020-0.4.21 kerasltisubmission-0.4.9\n" 150 | ], 151 | "name": "stdout" 152 | } 153 | ] 154 | }, 155 | { 156 | "cell_type": "code", 157 | "metadata": { 158 | "id": "Y4f0f8dndDUX", 159 | "colab_type": "code", 160 | "outputId": "ad21602d-5bff-4c0b-a1ef-e883ac7f7109", 161 | "colab": { 162 | "base_uri": "https://localhost:8080/", 163 | "height": 124 164 | } 165 | }, 166 | "source": [ 167 | "from deeplearning2020.datasets import ImageWoof\n", 168 | "train_data, test_data, classes= ImageWoof.load_data()\n" 169 | ], 170 | "execution_count": 0, 171 | "outputs": [ 172 | { 173 | "output_type": "stream", 174 | "text": [ 175 | "Downloading data from https://s3.amazonaws.com/fast-ai-imageclas/imagewoof2-320.tgz\n", 176 | "328294400/328288506 [==============================] - 8s 0us/step\n", 177 | "/root/.keras/datasets/imagewoof2-320/train\n", 178 | "Loaded 9025 images\n", 179 | "/root/.keras/datasets/imagewoof2-320/val\n", 180 | "Loaded 3929 images\n" 181 | ], 182 | "name": "stdout" 183 | } 184 | ] 185 | }, 186 | { 187 | "cell_type": "markdown", 188 | "metadata": { 189 | "id": "Fko1-mNnJ3Ji", 190 | "colab_type": "text" 191 | }, 192 | "source": [ 193 | "## Loading and Preprocessing the data" 194 | ] 195 | }, 196 | { 197 | "cell_type": "code", 198 | "metadata": { 199 | "id": "RDxi995yRt3-", 200 | "colab_type": "code", 201 | "colab": {} 202 | }, 203 | "source": [ 204 | "# resize the images to a uniform size\n", 205 | "def preprocess(image, label):\n", 206 | " resized_image = tf.image.resize(image, [300, 300])\n", 207 | " return resized_image, label" 208 | ], 209 | "execution_count": 0, 210 | "outputs": [] 211 | }, 212 | { 213 | "cell_type": "code", 214 | "metadata": { 215 | "colab_type": "code", 216 | "id": "-aba_6yC99ni", 217 | "outputId": "83adf767-7aab-4163-c403-5ae1aecca3f3", 218 | "colab": { 219 | "base_uri": "https://localhost:8080/", 220 | "height": 70 221 | } 222 | }, 223 | "source": [ 224 | "\n", 225 | "\n", 226 | "batch_size = 32\n", 227 | "print('shape of training data before preprocessing: ', train_data)\n", 228 | "train_data = train_data.shuffle(1000)\n", 229 | "\n", 230 | "\n", 231 | "train_data = train_data.map(preprocess) \\\n", 232 | " .batch(batch_size).prefetch(1)\n", 233 | "test_data = test_data.map(preprocess) \\\n", 234 | " .batch(batch_size).prefetch(1)\n", 235 | "print('shape of training data after preprocessing: ', train_data)\n", 236 | "print('shape of test data after preprocessing: ', test_data)" 237 | ], 238 | "execution_count": 0, 239 | "outputs": [ 240 | { 241 | "output_type": "stream", 242 | "text": [ 243 | "shape of training data before preprocessing: \n", 244 | "shape of training data after preprocessing: \n", 245 | "shape of test data after preprocessing: \n" 246 | ], 247 | "name": "stdout" 248 | } 249 | ] 250 | }, 251 | { 252 | "cell_type": "markdown", 253 | "metadata": { 254 | "id": "NnHSt3CVwrrP", 255 | "colab_type": "text" 256 | }, 257 | "source": [ 258 | "# Architektur des Netzes" 259 | ] 260 | }, 261 | { 262 | "cell_type": "code", 263 | "metadata": { 264 | "id": "Hik8RBJpwvvC", 265 | "colab_type": "code", 266 | "outputId": "ebb8f672-7249-4fb5-e1a4-9de6f3fe5574", 267 | "colab": { 268 | "base_uri": "https://localhost:8080/", 269 | "height": 799 270 | } 271 | }, 272 | "source": [ 273 | "# model\n", 274 | "learning_rate=0.001\n", 275 | "momentum=0.9\n", 276 | "dense_neurons=500\n", 277 | "n_filters=512\n", 278 | "first_kernel_size=(7,7)\n", 279 | "\n", 280 | "activation='elu'\n", 281 | "\n", 282 | "# input size of images must be 300x300 with RGB color\n", 283 | "input_layer = Input(shape=(300, 300, 3))\n", 284 | "\n", 285 | "# Convolutional Neural Network\n", 286 | "# It consists of 5 stacked Convolutional Layers with Max Pooling\n", 287 | "model = Conv2D(\n", 288 | " filters=256,\n", 289 | " kernel_size=(7,7),\n", 290 | " activation=activation\n", 291 | ")(input_layer)\n", 292 | "model = MaxPooling2D((2,2))(model)\n", 293 | "\n", 294 | "model = Conv2D(\n", 295 | " filters = 256, \n", 296 | " kernel_size=(3,3), \n", 297 | " activation=activation\n", 298 | ")(model)\n", 299 | "model = MaxPooling2D((2,2))(model)\n", 300 | "\n", 301 | "model = Conv2D(\n", 302 | " filters = n_filters, \n", 303 | " kernel_size=(3,3), \n", 304 | " activation=activation\n", 305 | ")(model)\n", 306 | "model = MaxPooling2D((2,2))(model)\n", 307 | "\n", 308 | "model = Conv2D(\n", 309 | " filters = n_filters, \n", 310 | " kernel_size=(3,3), \n", 311 | " activation=activation\n", 312 | ")(model)\n", 313 | "model = MaxPooling2D((2,2))(model)\n", 314 | "\n", 315 | "model = Conv2D(filters = n_filters, \n", 316 | " kernel_size=(3,3), \n", 317 | " activation=activation, \n", 318 | " padding='same'\n", 319 | ")(model)\n", 320 | "model = MaxPooling2D((2,2))(model)\n", 321 | "\n", 322 | "model = Conv2D(filters = n_filters, \n", 323 | " kernel_size=(3,3), \n", 324 | " activation=activation, \n", 325 | " padding='same'\n", 326 | ")(model)\n", 327 | "model = MaxPooling2D((2,2))(model)\n", 328 | "\n", 329 | "model = Conv2D(filters = n_filters, \n", 330 | " kernel_size=(3,3), \n", 331 | " activation=activation, \n", 332 | " padding='same'\n", 333 | ")(model)\n", 334 | "\n", 335 | "# Fully-Connected-Classifier\n", 336 | "model = Flatten()(model)\n", 337 | "model = Dense(\n", 338 | " dense_neurons,\n", 339 | " activation=activation\n", 340 | ")(model)\n", 341 | "\n", 342 | "model = Dense(\n", 343 | " dense_neurons / 2,\n", 344 | " activation='tanh'\n", 345 | ")(model)\n", 346 | "\n", 347 | "# Output Layer\n", 348 | "output = Dense(10, activation=\"softmax\")(model)\n", 349 | "\n", 350 | "model = Model(input_layer, output)\n", 351 | "\n", 352 | "# Compiling model\n", 353 | "optimizer = keras.optimizers.SGD(lr=learning_rate, momentum=momentum)\n", 354 | "model.compile(\n", 355 | " loss=\"sparse_categorical_crossentropy\",\n", 356 | " optimizer=optimizer,\n", 357 | " metrics=[\"accuracy\"]\n", 358 | ")\n", 359 | "model.summary()" 360 | ], 361 | "execution_count": 0, 362 | "outputs": [ 363 | { 364 | "output_type": "stream", 365 | "text": [ 366 | "Model: \"model\"\n", 367 | "_________________________________________________________________\n", 368 | "Layer (type) Output Shape Param # \n", 369 | "=================================================================\n", 370 | "input_1 (InputLayer) [(None, 300, 300, 3)] 0 \n", 371 | "_________________________________________________________________\n", 372 | "conv2d (Conv2D) (None, 294, 294, 256) 37888 \n", 373 | "_________________________________________________________________\n", 374 | "max_pooling2d (MaxPooling2D) (None, 147, 147, 256) 0 \n", 375 | "_________________________________________________________________\n", 376 | "conv2d_1 (Conv2D) (None, 145, 145, 256) 590080 \n", 377 | "_________________________________________________________________\n", 378 | "max_pooling2d_1 (MaxPooling2 (None, 72, 72, 256) 0 \n", 379 | "_________________________________________________________________\n", 380 | "conv2d_2 (Conv2D) (None, 70, 70, 512) 1180160 \n", 381 | "_________________________________________________________________\n", 382 | "max_pooling2d_2 (MaxPooling2 (None, 35, 35, 512) 0 \n", 383 | "_________________________________________________________________\n", 384 | "conv2d_3 (Conv2D) (None, 33, 33, 512) 2359808 \n", 385 | "_________________________________________________________________\n", 386 | "max_pooling2d_3 (MaxPooling2 (None, 16, 16, 512) 0 \n", 387 | "_________________________________________________________________\n", 388 | "conv2d_4 (Conv2D) (None, 16, 16, 512) 2359808 \n", 389 | "_________________________________________________________________\n", 390 | "max_pooling2d_4 (MaxPooling2 (None, 8, 8, 512) 0 \n", 391 | "_________________________________________________________________\n", 392 | "conv2d_5 (Conv2D) (None, 8, 8, 512) 2359808 \n", 393 | "_________________________________________________________________\n", 394 | "max_pooling2d_5 (MaxPooling2 (None, 4, 4, 512) 0 \n", 395 | "_________________________________________________________________\n", 396 | "conv2d_6 (Conv2D) (None, 4, 4, 512) 2359808 \n", 397 | "_________________________________________________________________\n", 398 | "flatten (Flatten) (None, 8192) 0 \n", 399 | "_________________________________________________________________\n", 400 | "dense (Dense) (None, 500) 4096500 \n", 401 | "_________________________________________________________________\n", 402 | "dense_1 (Dense) (None, 250) 125250 \n", 403 | "_________________________________________________________________\n", 404 | "dense_2 (Dense) (None, 10) 2510 \n", 405 | "=================================================================\n", 406 | "Total params: 15,471,620\n", 407 | "Trainable params: 15,471,620\n", 408 | "Non-trainable params: 0\n", 409 | "_________________________________________________________________\n" 410 | ], 411 | "name": "stdout" 412 | } 413 | ] 414 | }, 415 | { 416 | "cell_type": "code", 417 | "metadata": { 418 | "id": "G9J5rOK-w2qA", 419 | "colab_type": "code", 420 | "outputId": "20a1697f-4e23-4a2f-fe01-e5ed0009be52", 421 | "colab": { 422 | "base_uri": "https://localhost:8080/", 423 | "height": 373 424 | } 425 | }, 426 | "source": [ 427 | "# Train the model\n", 428 | "history = model.fit(\n", 429 | " train_data,\n", 430 | " epochs=10,\n", 431 | " validation_data = test_data\n", 432 | ")" 433 | ], 434 | "execution_count": 0, 435 | "outputs": [ 436 | { 437 | "output_type": "stream", 438 | "text": [ 439 | "Epoch 1/10\n", 440 | "283/283 [==============================] - 123s 436ms/step - loss: 0.8194 - accuracy: 0.7309 - val_loss: 1.9239 - val_accuracy: 0.4100\n", 441 | "Epoch 2/10\n", 442 | "283/283 [==============================] - 123s 436ms/step - loss: 0.6151 - accuracy: 0.8079 - val_loss: 2.0038 - val_accuracy: 0.4123\n", 443 | "Epoch 3/10\n", 444 | "283/283 [==============================] - 123s 436ms/step - loss: 0.2568 - accuracy: 0.9378 - val_loss: 2.2265 - val_accuracy: 0.4065\n", 445 | "Epoch 4/10\n", 446 | "283/283 [==============================] - 123s 435ms/step - loss: 0.1921 - accuracy: 0.9591 - val_loss: 2.3152 - val_accuracy: 0.4093\n", 447 | "Epoch 5/10\n", 448 | "283/283 [==============================] - 123s 436ms/step - loss: 0.0354 - accuracy: 0.9981 - val_loss: 2.3080 - val_accuracy: 0.4291\n", 449 | "Epoch 6/10\n", 450 | "283/283 [==============================] - 123s 436ms/step - loss: 0.0127 - accuracy: 0.9998 - val_loss: 2.3591 - val_accuracy: 0.4383\n", 451 | "Epoch 7/10\n", 452 | "283/283 [==============================] - 123s 436ms/step - loss: 0.0079 - accuracy: 0.9999 - val_loss: 2.4098 - val_accuracy: 0.4378\n", 453 | "Epoch 8/10\n", 454 | "283/283 [==============================] - 123s 436ms/step - loss: 0.0063 - accuracy: 0.9999 - val_loss: 2.4507 - val_accuracy: 0.4421\n", 455 | "Epoch 9/10\n", 456 | "283/283 [==============================] - 123s 436ms/step - loss: 0.0051 - accuracy: 0.9999 - val_loss: 2.4821 - val_accuracy: 0.4434\n", 457 | "Epoch 10/10\n", 458 | "283/283 [==============================] - 123s 436ms/step - loss: 0.0043 - accuracy: 0.9999 - val_loss: 2.5138 - val_accuracy: 0.4396\n" 459 | ], 460 | "name": "stdout" 461 | } 462 | ] 463 | } 464 | ] 465 | } -------------------------------------------------------------------------------- /woche3/assignment/exercise2/README.md: -------------------------------------------------------------------------------- 1 | **Diese Übung ist für Woche 3 und Woche 4 gedacht. In den nächsten beiden Kurswochen werdet ihr vielfältige Möglichkeiten kennenlernen die Genauigkeit eures Netzes zu verbessern.** 2 | 3 | EDIT: Die Lösungen zu dieser Übung befinden sich unter den folgenden Links: 4 | - [Lösung nach Woche 3](https://colab.research.google.com/drive/1Oqdv-ldz4WZJqhMbcjQJ24fBh2km4xIb) 5 | - [Lösung nach Woche 3 mit weniger Parametern](https://colab.research.google.com/drive/1C0YDbJb7qug0ibum4Ox8MI3l2vHSSi_G) 6 | - [Lösung nach Woche 4 mit Transferlearning](https://colab.research.google.com/drive/1JSgk_njvRxCl5njT1pQ1WuSKOnwzen9T) 7 | 8 | ![ImageWoof](https://drive.google.com/uc?id=1UVjiie92RMAcsmSgRpNugANX2m7nJOIx) 9 | 10 | **Errinnerung**: Durch die Bearbeitung der Übungen können insgesamt bis zu **40%** Prozent der Kurspunkte erhalten werden. Diese Summe setzt sich aus der Übung in dieser Woche (25%) und der Übung aus Woche 2 (15%) zusammen. 11 | 12 | #### Was sollt ihr in dieser Übung lernen? 13 | 14 | In dieser Kurswoche habt ihr gelernt, wie komplexere neuronale Netze aufgebaut werden und wie ihr diese auf eure Trainingsdaten anpassen könnt. Die Aufgabe in dieser Woche besteht darin, ein neuronales Netz für einen komplexen Datensatz zu trainieren und damit selbst durch Ausprobieren der verschiedenen Parameter weitere Einblicke in die Entwicklung neuronaler Netze zu erhalten. Dabei ist es egal, ob ihr [Google Colab](https://colab.research.google.com/) oder eine lokale Installation verwendet. Wir würden jedoch den Einsatz von Google Colab empfehlen, da ihr dort meist leistungsfähigere Hardware einsetzen könnt, die den Trainigsprozess stark beschleunigt. 15 | 16 | **Ziel ist es, ein Netz für den im folgenden vorgestellten Datensatz zu trainieren, das dessen Bilder so zuverlässig wie möglich klassifiziert.** 17 | 18 | #### Welchen Datensatz sollt ihr benutzen? 19 | 20 | Es wird wieder ein Teildatensatz des Imagenets benutzt. Dieser wird von Fast.ai zur Verfügung gestellt und kann [hier](https://github.com/fastai/imagenette) heruntergeladen werden. 21 | 22 | Die sehr genaue Klassifizierung ist hier nicht einfach und soll euch anregen, mit verschiedenen Parametern herumzuspielen. 23 | 24 | Der Datensatz besteht aus **10.000 Trainings-** und **3000 Testdaten**. Genauso wie beim Imagenette Datensatz, der in dieser Woche verwendet wurde, sind die Bilder in einer Dimension 320px groß und können wie in dieser Woche vorgestellt, verarbeitet werden. 25 | 26 | Jedes Bild ist mit je einer der **10 Klassen** klassifiziert, welche verschiedene Hunderassen darstellen. Dabei handelt es sich um Australian Terrier, Border Terrier, Samoyed, Beagle, Shih-Tzu, English Foxhound, Rhodesian Ridgeback, Dingo, Golden Retriever und Old English Sheepdog. Die genaue Liste an Klassen findet ihr [hier](https://github.com/fastai/imagenette). 27 | 28 | Euer Netz soll also lernen, zwischen verschiedenen Hunderassen zu unterscheiden. 29 | 30 | #### Wie bekommt ihr den Datensatz? 31 | 32 | Wir haben euch über unser `deeplearning2020` python package eine Funktion bereitgestellt, mit der ihr die Daten laden könnt. Diese kann folgendermaßen verwendet werden: 33 | 34 | ```python 35 | # ohne Ausrufezeichen bei Ausführung im lokalen Notebook 36 | !pip install --upgrade deeplearning2020 37 | from deeplearning2020.datasets import ImageWoof 38 | 39 | train_data, test_data, classes = ImageWoof.load_data() 40 | ``` 41 | Der Datensatz ist in einen `train_data` (Trainigsdaten) und einen `test_data` (Validierungdaten) Datensatz aufgeteilt, welche ihr wie oben gezeigt laden könnt. 42 | 43 | Die `load_data()` Funktion liefert sowohl einen Datensatz zurück, mit dem ihr genauso arbeiten könnt, wie mit den den aus `tfds.load` geladenen Datensets. 44 | 45 | Der Unterschied ist, dass wir euch mit diesem Befehl Trainigsdaten (Bilder und Label), Testdaten (Bilder und Label) und auch die Klassennamen über `classes` bereitstellen. Damit könnt ihr dann weiterarbeiten. 46 | 47 | Um einen Eindruck über die Klassen zu bekommen, könnt ihr folgendes ausführen: 48 | Wie im Notebook in dieser Woche gezeigt,könnt ihr über `helpers.plot_images(train_data.take(9), classes)` Bilder des Datensatzes anzeigen, um einen Eindruck zu bekommen, wie diese aussehen. 49 | 50 | 51 | Hier noch ein paar weitere Informationen zum Datensatz: 52 | - Die Bildpunkte sind als Floats zwischen 0 und 1 gespeichert. Das heißt für euch, dass die im Notebook 3.5.2 genutzte `preprocessing` Funktion genutzt werden kann, wobei das Teilen durch 255 weggelassen werden muss. 53 | - Die Labels der Daten liegen in sparse Form vor. Das heißt für euch, dass ihr die `sparse_categorical_crossentropy` Fehlerfunktion nutzen solltet. 54 | 55 | Somit sieht die preprocessing Funktion dieser Woche so aus: 56 | ```python 57 | def preprocess(image, label): 58 | resized_image = tf.image.resize(image, [300, 300]) 59 | return resized_image, label 60 | ``` 61 | Dies ist notwendig, da die Bilder nicht in der gleichen Bildgröße vorkommen und somit vorher auf eine einheitliche Größe resized werden müssen. 62 | 63 | Um auf dem Netz trainieren zu können orientiert ihr euch am besten am [Notebook zum Video `3.5.2`](https://colab.research.google.com/drive/18BGSjiQ9h7-XJ45HNV0iK2coaRTd8AQk), so das preprocessing der Daten im Abschnitt **Preprocessing der Daten zur schnelleren Verarbeitung** vorgestellt ist. 64 | 65 | #### Ich weiß nicht, wie ich anfangen soll 66 | 67 | Falls du nicht weißt, wie du am Besten anfangen solltest, orientiere dich am [Praxisvideo zum komplexen Aufbau neuronaler Netze](https://colab.research.google.com/drive/18BGSjiQ9h7-XJ45HNV0iK2coaRTd8AQk). Schau dir dazu am besten das kommentierte Notebook an, welches du unter Lehrmaterialien zu diesem Video findest. 68 | 69 | Realistische Werte für die Validation Accuracy für diesen Datensatz mit den gelernten Methoden aus Woche 3 sind um die 50% mit starken Overfitting. In der nächsten Kurswoche werdet ihr diese schrittweise verbessern können. 70 | 71 | Seid gerne ermutigt, neue Techniken auszuprobieren und an Parametern zu schrauben! 72 | 73 | #### Wie reicht ihr eure Lösung ein? 74 | 75 | Nachdem ihr euer Keras Netz trainiert habt, könnt ihr es ganz einfach hochladen: 76 | 77 | 1. Gehe dazu auf [open.hpi.de](https://open.hpi.de/) auf die Übungsaufgabe und klicke auf *Aufgabe starten*. 78 | 2. Es sollte sich ein neuer Tab öffnen, welcher dir den Python Code anzeigt, den du zur Abgabe deines Keras Models benötigst. Alle benötigten Informationen findest du dort auch in der Beschreibung. Trotzdem an dieser Stelle noch einmal: 79 | 1. Falls noch nicht getan, installiere das Python Package zu diesem Kurs mit Hilfe von pip: 80 | ``` 81 | pip install --upgrade deeplearning2020 82 | ``` 83 | 84 | In einem Jupyter Notebook (Google Colab oder lokal) geht das mit: 85 | ``` 86 | !pip install --upgrade deeplearning2020 87 | ``` 88 | 2. Importieren des Package 89 | ```python 90 | from deeplearning2020 import Submission 91 | ``` 92 | 3. Submitte dein Model, wobei du den Token und die Assignment ID von der Webseite kopieren musst: 93 | ```python 94 | Submission('', '', model).submit() 95 | ``` 96 | Falls du für dein Model einen anderen Variablennamen als `model` verwendest, musst du diese Variable entsprechend verwenden. 97 | 98 | 3. Mit dem Ausführen sollte das Model von uns validiert werden und du erhältst abschließend eine Accuracy und Benotung. **Unsere Accuracy kann sich von euer Accuracy unterscheiden, da wir euer Model mit Werten testen, die es eventuell noch nie gesehen hat. Das gilt aber gleichermaßen für alle Teilnehmer.** 99 | 100 | **Ihr könnt euer trainiertes Model beliebig oft submitten und es wird automatisch das beste Ergebnis gewählt, ohne dass ihr etwas machen müsst.** 101 | 102 | #### Wie werden wir eure Lösungen bewerten? 103 | 104 | In dieser Übung wird mit einem komplexeren Datensatz gearbeitet. Seid daher nicht frustriert, wenn ihr keine perfekte Accuracy erhaltet. In der nächsten Kurswoche werden Techniken vorgestellt, mit denen ihr dieses Netz verbessern könnt, sodass ihr eine höhere Genauigkeit erzielt und damit auch eine bessere Bewertung für die Übung. Sie ist also bewusst darauf ausgelegt, über beide Kurswochen gestreckt zu sein. Fangt also diese Woche mit der Bearbeitung der Aufgabe an und verbessert euer Netz in der nächsten Kurswoche. 105 | 106 | Eure Abgabe bewerten wir nach folgender Bewertungsgrundlage: 107 | 108 | - Bei einer **Accuracy >= 0.95** (95%) gibt es volle Punktzahl 109 | - Bei einer **Accuracy = 0.0** (0%) gibt es 0 Punkte 110 | - Alles dazwischen wird entsprechend linear interpoliert 111 | 112 | ### Schwierigkeit der Übung 113 | 114 | Wie ihr bei der Arbeit mit dem Datensatz vielleicht feststellen werdet, ist eine sehr gute Accuracy mit dem Wissen aus Woche 3 noch nicht machbar. Aus diesem Grund habt ihr auch in Woche 4 genügend Zeit, die Übung dann weiter zu bearbeiten. Wir würden euch trotzdem darum bitten, auch in dieser Woche schon herumzuprobieren, um das Wissen aus dieser Woche praktisch anzuwenden. 115 | 116 | Falls ihr mit einem anderen Datensatz arbeiten möchtet, könnt ihr gerne, die von uns zusätzlich bereitgestellte Möglichkeit der extra Übung nutzen. Weitere Informationen findet ihr [hier](https://open.hpi.de/courses/neuralnets2020/items/3vh2FG4fjjKKNPA2GnoQ8r). 117 | 118 | Wir wünschen euch viel Spaß und Erfolg bei der Übung! 119 | -------------------------------------------------------------------------------- /woche3/notebooks/complex-layer-structure/README.md: -------------------------------------------------------------------------------- 1 | #### Komplexe Layerstruktur 2 | 3 | Notebooks 4 | - [Komplexe Layerstruktur](./complex-layer-structure.ipynb) 5 | 6 | In Google Colab ist dieses Notebook unter [diesem Link](https://colab.research.google.com/drive/18BGSjiQ9h7-XJ45HNV0iK2coaRTd8AQk) erreichbar. 7 | -------------------------------------------------------------------------------- /woche3/notebooks/hyperparameter/README.md: -------------------------------------------------------------------------------- 1 | #### Hyperparameter 2 | 3 | Notebooks 4 | - [Hyperparameter](./hyperparameter.ipynb) 5 | - [Hyperparameter: Tiefe des Netzwerks](./hyperparameter-network-depth.ipynb) 6 | 7 | In Google Colab ist das Notebook zu den Hyperparametern unter [diesem Link](https://drive.google.com/file/d/1M9nBqqyhpkJJsJ50o4FQhDn455_gtXWQ/view?usp=sharing) erreichbar und das Notebook speziell zur Netzwerktiefe [unter diesem Link](https://drive.google.com/file/d/1y__ILHF7_7PFit4ZckyDkdNZ82Jj_Hf8/view?usp=sharing). 8 | -------------------------------------------------------------------------------- /woche3/notebooks/loss-functions/README.md: -------------------------------------------------------------------------------- 1 | #### Loss Functions 2 | 3 | Notebooks 4 | - [Loss Functions](./loss-functions.ipynb) 5 | - [Loss Functions Imagenette](./loss-functions-imagenette.ipynb) 6 | 7 | In Google Colab ist das Notebook zu den Loss Functions unter [diesem Link](https://colab.research.google.com/drive/1qo-epWNkGdq1uiZfZwMpi9ZCB0vwKmqt) erreichbar und das Notebook speziell zum Imagenette [unter diesem Link](https://colab.research.google.com/drive/1P528QmW117pq7va6fcVl2PQLtR9ualpx). 8 | -------------------------------------------------------------------------------- /woche3/notebooks/optimizer/README.md: -------------------------------------------------------------------------------- 1 | #### Optimizer 2 | 3 | Notebooks 4 | - [Optimizer](./optimizer.ipynb) 5 | - [Optimizer Imagenette](./optimizer-imagenette.ipynb) 6 | 7 | In Google Colab ist das Notebook zum Optimizer unter [diesem Link](https://colab.research.google.com/drive/1xgN7JeAnvREB0PnOKh9QoZdfKw8S4vyZ) erreichbar und das Notebook speziell zum Imagenette [unter diesem Link](https://colab.research.google.com/drive/1Mhntlje3XNuaSg5X_F9pjOUSpc7g6aTa). 8 | -------------------------------------------------------------------------------- /woche3/scratch-net/README.md: -------------------------------------------------------------------------------- 1 | #### ScratchNet 2 | ##### Oder auch: Keras in < 300 LOC 3 | 4 | Wolltet ihr auch schon einmal wissen wie Keras unter der Haube funktioniert? 5 | 6 | In diesem Exkurs implementieren wir unser eigenes Keras mit Python und `numpy`! 7 | 8 | Dabei gibt es folgende 3 Varianten des *ScratchNets*: 9 | 10 | 1. `scratchNet_full_commented_solution.ipynb` [Colab](https://colab.research.google.com/github/into-ai/deeplearning2020/blob/master/woche3/scratch-net/scratchNet_full_commented_solution.ipynb) 11 | 12 | 2. `scratchNet_full_uncommented_solution.ipynb` [Colab](https://colab.research.google.com/github/into-ai/deeplearning2020/blob/master/woche3/scratch-net/scratchNet_full_uncommented_solution.ipynb) 13 | 14 | 3. `scratchNet_partial_commented_solution.ipynb` [Colab](https://colab.research.google.com/github/into-ai/deeplearning2020/blob/master/woche3/scratch-net/scratchNet_partial_commented_solution.ipynb) 15 | 16 | - Verwende dieses wenn du die Methoden selber einmal implementieren möchtest! 17 | -------------------------------------------------------------------------------- /woche3/scratch-net/scratchNet_full_uncommented_solution.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "nbformat": 4, 3 | "nbformat_minor": 0, 4 | "metadata": { 5 | "colab": { 6 | "name": "scratchNet-full-uncommented-solution.ipynb", 7 | "provenance": [], 8 | "collapsed_sections": [] 9 | }, 10 | "kernelspec": { 11 | "name": "python3", 12 | "display_name": "Python 3" 13 | } 14 | }, 15 | "cells": [ 16 | { 17 | "cell_type": "markdown", 18 | "metadata": { 19 | "id": "52hHPx_BQQZ7", 20 | "colab_type": "text" 21 | }, 22 | "source": [ 23 | "# ScratchNet\n", 24 | "Ein einfaches künstliches neuronales Netz mit einer von `keras` inspirierten API.\n", 25 | "Hinweis: Das Netz wurde ausschließlich für Lernzwecke verfasst." 26 | ] 27 | }, 28 | { 29 | "cell_type": "code", 30 | "metadata": { 31 | "id": "JOixRSglQDcm", 32 | "colab_type": "code", 33 | "outputId": "04424eb6-87d6-4306-cdb5-c7c4f733a293", 34 | "colab": { 35 | "base_uri": "https://localhost:8080/", 36 | "height": 35 37 | } 38 | }, 39 | "source": [ 40 | "%tensorflow_version 2.x\n", 41 | "import abc\n", 42 | "import matplotlib.pyplot as plt\n", 43 | "import tensorflow as tf\n", 44 | "import numpy as np\n", 45 | "import random\n", 46 | "import time\n", 47 | "from tqdm import tqdm, trange" 48 | ], 49 | "execution_count": 1, 50 | "outputs": [ 51 | { 52 | "output_type": "stream", 53 | "text": [ 54 | "TensorFlow 2.x selected.\n" 55 | ], 56 | "name": "stdout" 57 | } 58 | ] 59 | }, 60 | { 61 | "cell_type": "code", 62 | "metadata": { 63 | "id": "u6c8fBcRQX3e", 64 | "colab_type": "code", 65 | "colab": {} 66 | }, 67 | "source": [ 68 | "class DifferentiableFunction(abc.ABC):\n", 69 | " def derivative(self, net_input):\n", 70 | " pass\n", 71 | "\n", 72 | " def __call__(self, net_input):\n", 73 | " pass" 74 | ], 75 | "execution_count": 0, 76 | "outputs": [] 77 | }, 78 | { 79 | "cell_type": "code", 80 | "metadata": { 81 | "id": "JYf4TAzdQall", 82 | "colab_type": "code", 83 | "colab": {} 84 | }, 85 | "source": [ 86 | "class Sigmoid(DifferentiableFunction):\n", 87 | " def derivative(self, net_input):\n", 88 | " return self(net_input) * (1 - self(net_input))\n", 89 | "\n", 90 | " def __call__(self, net_input):\n", 91 | " return 1 / (1 + np.exp(-net_input))" 92 | ], 93 | "execution_count": 0, 94 | "outputs": [] 95 | }, 96 | { 97 | "cell_type": "code", 98 | "metadata": { 99 | "id": "YX6Hw7hAQduw", 100 | "colab_type": "code", 101 | "colab": {} 102 | }, 103 | "source": [ 104 | "class SquaredError(DifferentiableFunction):\n", 105 | " def derivative(self, target, actual):\n", 106 | " return actual - target\n", 107 | "\n", 108 | " def __call__(self, target, actual):\n", 109 | " return 0.5 * np.sum((target - actual) ** 2)" 110 | ], 111 | "execution_count": 0, 112 | "outputs": [] 113 | }, 114 | { 115 | "cell_type": "code", 116 | "metadata": { 117 | "id": "gczgOtCWQh0O", 118 | "colab_type": "code", 119 | "colab": {} 120 | }, 121 | "source": [ 122 | "class DenseLayer:\n", 123 | " def __init__(\n", 124 | " self,\n", 125 | " neuron_count,\n", 126 | " depth=None,\n", 127 | " activation=None,\n", 128 | " biases=None,\n", 129 | " weights=None,\n", 130 | " prev_layer=None,\n", 131 | " next_layer=None,\n", 132 | " ):\n", 133 | " self.depth = depth\n", 134 | " self.next_layer = next_layer\n", 135 | " self.prev_layer = prev_layer\n", 136 | "\n", 137 | " self.neuron_count = neuron_count\n", 138 | " self.activation_func = activation or Sigmoid()\n", 139 | "\n", 140 | " self.weights = weights\n", 141 | " self.biases = biases\n", 142 | "\n", 143 | " def prepare_inputs(self, images, labels=None):\n", 144 | " return images if labels is None else images, labels\n", 145 | "\n", 146 | " def initialize_parameters(self):\n", 147 | " if self.weights is None:\n", 148 | " self.weights = np.random.randn(\n", 149 | " self.neuron_count, self.prev_layer.neuron_count\n", 150 | " )\n", 151 | " if self.biases is None:\n", 152 | " self.biases = np.random.randn(self.neuron_count, 1)\n", 153 | "\n", 154 | " def compute_cost_gradients(self, label_vec, cost_func):\n", 155 | " cost_gradients = cost_func.derivative(\n", 156 | " self.activation_vec, label_vec\n", 157 | " ) * self.activation_func.derivative(self.layer_inputs)\n", 158 | " self._update_layer_gradients(cost_gradients)\n", 159 | " return cost_gradients\n", 160 | "\n", 161 | " def feed_backwards(self, prev_input_gradients):\n", 162 | " new_input_gradients = np.dot(\n", 163 | " self.next_layer.weights.transpose(), prev_input_gradients\n", 164 | " ) * self.activation_func.derivative(self.layer_inputs)\n", 165 | " self._update_layer_gradients(new_input_gradients)\n", 166 | " return new_input_gradients\n", 167 | "\n", 168 | " def _update_layer_gradients(self, input_gradients):\n", 169 | " self.bias_gradients = input_gradients\n", 170 | " self.weight_gradients = np.dot(\n", 171 | " input_gradients, self.prev_layer.activation_vec.transpose()\n", 172 | " )\n", 173 | "\n", 174 | " def feed_forward_layer(self, input_activations):\n", 175 | " self.layer_inputs = np.dot(\n", 176 | " self.weights, input_activations) + self.biases\n", 177 | " self.activation_vec = self.activation_func(self.layer_inputs)\n", 178 | " return self.activation_vec\n", 179 | "\n", 180 | " def inspect(self):\n", 181 | " print(f\"--------- Layer L={self.depth} ---------\")\n", 182 | " print(f\" # Neuronen: {self.neuron_count}\")\n", 183 | " for n in range(self.neuron_count):\n", 184 | " print(f\" Neuron {n}\")\n", 185 | " if self.prev_layer:\n", 186 | " for w in self.weights[n]:\n", 187 | " print(f\" Weight: {w}\")\n", 188 | " print(f\" Bias: {self.biases[n][0]}\")" 189 | ], 190 | "execution_count": 0, 191 | "outputs": [] 192 | }, 193 | { 194 | "cell_type": "code", 195 | "metadata": { 196 | "id": "lKqSvjCgQjHS", 197 | "colab_type": "code", 198 | "colab": {} 199 | }, 200 | "source": [ 201 | "class FlattenLayer(DenseLayer):\n", 202 | " def __init__(self, input_shape):\n", 203 | " total_input_neurons = 1\n", 204 | " for dim in input_shape:\n", 205 | " total_input_neurons *= dim\n", 206 | " super().__init__(neuron_count=total_input_neurons)\n", 207 | "\n", 208 | " def initialize_parameters(self):\n", 209 | " pass\n", 210 | "\n", 211 | " def feed_forward_layer(self, input_activations):\n", 212 | " self.activation_vec = input_activations\n", 213 | " return input_activations\n", 214 | "\n", 215 | " def prepare_inputs(self, images, labels=None):\n", 216 | " flattened_images = images.reshape(\n", 217 | " images.shape[0], self.neuron_count, 1)\n", 218 | " if labels is not None:\n", 219 | " labels = labels.reshape(labels.shape[0], -1, 1)\n", 220 | " return flattened_images, labels\n", 221 | " return flattened_images" 222 | ], 223 | "execution_count": 0, 224 | "outputs": [] 225 | }, 226 | { 227 | "cell_type": "code", 228 | "metadata": { 229 | "id": "8vB7U79cQsSI", 230 | "colab_type": "code", 231 | "colab": {} 232 | }, 233 | "source": [ 234 | "class ScratchNet:\n", 235 | " def __init__(self, layers):\n", 236 | " self.learning_rate = 0.5\n", 237 | " self.cost_func = SquaredError()\n", 238 | " self.layers = layers\n", 239 | " for index, layer in enumerate(self.layers):\n", 240 | " layer.prev_layer = self.layers[index - 1] if index > 0 else None\n", 241 | " layer.next_layer = (\n", 242 | " self.layers[index + 1] if index +\n", 243 | " 1 < len(self.layers) else None\n", 244 | " )\n", 245 | " layer.depth = index\n", 246 | " layer.initialize_parameters()\n", 247 | "\n", 248 | " def _calculate_loss(self, input_samples):\n", 249 | " total_error = 0.0\n", 250 | " for sample in input_samples:\n", 251 | " image, label_vec = sample\n", 252 | " output_activations = self._feed_forward(image)\n", 253 | " total_error += self.cost_func(label_vec, output_activations)\n", 254 | " return total_error / len(input_samples)\n", 255 | "\n", 256 | " def _calculate_accuracy(self, input_samples):\n", 257 | " results = [\n", 258 | " (np.argmax(self._feed_forward(image)), np.argmax(expected_label))\n", 259 | " for image, expected_label in input_samples\n", 260 | " ]\n", 261 | " num_correct = sum(int(x == y) for (x, y) in results)\n", 262 | " return num_correct / len(input_samples)\n", 263 | "\n", 264 | " def _feed_forward(self, input_sample):\n", 265 | " for layer in self.layers:\n", 266 | " input_sample = layer.feed_forward_layer(input_sample)\n", 267 | " return input_sample\n", 268 | "\n", 269 | " def _update_parameters(self, input_samples):\n", 270 | " weight_gradients = [np.zeros(layer.weights.shape)\n", 271 | " for layer in self.layers[1:]]\n", 272 | " bias_gradients = [np.zeros(layer.biases.shape)\n", 273 | " for layer in self.layers[1:]]\n", 274 | "\n", 275 | " for sample in input_samples:\n", 276 | " sample_weight_gradients, sample_bias_gradients = self._backpropagate(\n", 277 | " sample)\n", 278 | " weight_gradients = np.add(\n", 279 | " weight_gradients, sample_weight_gradients)\n", 280 | " bias_gradients = np.add(bias_gradients, sample_bias_gradients)\n", 281 | "\n", 282 | " for layer, layer_weight_gradients, layer_bias_gradients in zip(\n", 283 | " self.layers[1:], weight_gradients, bias_gradients\n", 284 | " ):\n", 285 | " layer.weights += (\n", 286 | " self.learning_rate *\n", 287 | " layer_weight_gradients / len(input_samples)\n", 288 | " )\n", 289 | " layer.biases += (\n", 290 | " self.learning_rate * layer_bias_gradients / len(input_samples)\n", 291 | " )\n", 292 | "\n", 293 | " def _backpropagate(self, training_sample):\n", 294 | " train_input, train_output = training_sample\n", 295 | " self._feed_forward(train_input)\n", 296 | " gradients = self.layers[-1].compute_cost_gradients(\n", 297 | " train_output, cost_func=self.cost_func\n", 298 | " )\n", 299 | "\n", 300 | " for layer in reversed(self.layers[1:-1]):\n", 301 | " gradients = layer.feed_backwards(gradients)\n", 302 | "\n", 303 | " weight_gradients = [\n", 304 | " layer.weight_gradients for layer in self.layers[1:]]\n", 305 | " bias_gradients = [layer.bias_gradients for layer in self.layers[1:]]\n", 306 | " return weight_gradients, bias_gradients\n", 307 | "\n", 308 | " def _stochastic_gradient_descent(\n", 309 | " self, training_data, epochs=1, batch_size=1, avg_lookbehind=None\n", 310 | " ):\n", 311 | " losses, accuracies = list(), list()\n", 312 | " training_set_size = len(training_data)\n", 313 | "\n", 314 | " avg_lookbehind = avg_lookbehind or int(\n", 315 | " 0.10 * training_set_size / batch_size)\n", 316 | " running_loss, running_acc = [], []\n", 317 | "\n", 318 | " for epoch in range(epochs):\n", 319 | " random.shuffle(training_data)\n", 320 | "\n", 321 | " with tqdm(total=training_set_size) as progress:\n", 322 | " for t in range(0, training_set_size, batch_size):\n", 323 | " batch = training_data[t: t + batch_size]\n", 324 | "\n", 325 | " self._update_parameters(batch)\n", 326 | " loss, accuracy = (\n", 327 | " self._calculate_loss(batch),\n", 328 | " self._calculate_accuracy(batch),\n", 329 | " )\n", 330 | "\n", 331 | " running_loss = ([loss] + running_loss)[:avg_lookbehind]\n", 332 | " running_acc = ([accuracy] + running_acc)[:avg_lookbehind]\n", 333 | " running_loss_avg = np.average(running_loss)\n", 334 | " running_acc_avg = np.average(running_acc)\n", 335 | " losses.append(running_loss_avg)\n", 336 | " accuracies.append(running_acc_avg)\n", 337 | "\n", 338 | " progress.set_description(f\"Epoch {epoch+1}\")\n", 339 | " progress.set_postfix(\n", 340 | " loss=\"{0:.3f}\".format(running_loss_avg),\n", 341 | " accuracy=\"{0:.2f}\".format(running_acc_avg),\n", 342 | " )\n", 343 | "\n", 344 | " progress.update(len(batch))\n", 345 | " return losses, accuracies\n", 346 | "\n", 347 | " def fit(self, train_images, train_labels, epochs=1, batch_size=1):\n", 348 | " train_images, train_labels = self.layers[0].prepare_inputs(\n", 349 | " train_images, train_labels\n", 350 | " )\n", 351 | " training_data = list(zip(train_images, train_labels))\n", 352 | " losses, accuracies = self._stochastic_gradient_descent(\n", 353 | " training_data, epochs=epochs, batch_size=batch_size\n", 354 | " )\n", 355 | " return losses, accuracies\n", 356 | "\n", 357 | " def predict(self, model_inputs):\n", 358 | " model_inputs = self.layers[0].prepare_inputs(model_inputs)\n", 359 | " predicted = np.zeros(\n", 360 | " (model_inputs.shape[0], self.layers[-1].neuron_count, 1))\n", 361 | " for i, model_input in enumerate(model_inputs):\n", 362 | " predicted[i] = self._feed_forward(model_input)\n", 363 | " return predicted\n", 364 | "\n", 365 | " def evaluate(self, validation_images, validation_labels):\n", 366 | " validation_images, validation_labels = self.layers[0].prepare_inputs(\n", 367 | " validation_images, validation_labels\n", 368 | " )\n", 369 | " validation_data = list(zip(validation_images, validation_labels))\n", 370 | " return (\n", 371 | " self._calculate_loss(validation_data),\n", 372 | " self._calculate_accuracy(validation_data),\n", 373 | " )\n", 374 | "\n", 375 | " def compile(self, learning_rate=None, loss=None):\n", 376 | " self.learning_rate = learning_rate or self.learning_rate\n", 377 | " self.cost_func = loss or self.cost_func\n", 378 | "\n", 379 | " def inspect(self):\n", 380 | " print(f\"--------- {self.__class__.__name__} ---------\")\n", 381 | " print(f\" # Inputs: {self.layers[0].neuron_count}\")\n", 382 | " for layer in self.layers:\n", 383 | " layer.inspect()" 384 | ], 385 | "execution_count": 0, 386 | "outputs": [] 387 | } 388 | ] 389 | } -------------------------------------------------------------------------------- /woche4/README.md: -------------------------------------------------------------------------------- 1 | #### Woche 4 2 | 3 | In der vierten Woche geht es um die Optimierung von neuronalen Netzen. Wir schauen uns verschiedene Techniken an, die ihr benutzen könnt, um auch Netze mit sehr wenigen Bildern zu trainieren. Wir benutzen dabei einen besonders herausfordernden und hochauflösenden Bilddatensatz. Ihr lernt, wie ihr State-of-the-Art-Netze benutzen könnt, um euer die eigenen Ergebnisse zu verbessern. Mit Abschluss der Woche werdet ihr eure eigenen Probleme mit Deep Learning lösen könnt. 4 | 5 | ##### Inhalt 6 | - [Notebooks](./notebooks/) 7 | - [Optimierung Hyperparameter](./notebooks/hyperparameter-optimization/) 8 | - [Dropout](./notebooks/dropout/) 9 | - [Batch Normalization](./notebooks/batch-normalization/) 10 | - [Regularisierungstechniken (wie Data Augmentation)](./notebooks/regularization-techniques/) 11 | - [Transfer Learning](./notebooks/transfer-learning/) 12 | - [Automated Machine Learning](./notebooks/automated-machine-learning/) 13 | - [Exkurs-GAN](./gan/) 14 | - [Praktische Übungen](./assignment/) 15 | - [Bewertete Übung](./assignment/exercise2/) 16 | - [Zusätzliche Übung](./assignment/additional/) 17 | -------------------------------------------------------------------------------- /woche4/assignment/additional/README.md: -------------------------------------------------------------------------------- 1 | ## Informationen zu weiteren Übungsmöglichkeiten 2 | 3 | Im Internet und vor allem direkt in [Tensorflow](https://www.tensorflow.org/datasets/catalog/overview) gibt es einige Datensätze mit denen das erlernte Wissen ganz einfach auf die Probe gestellt werden kann. Seid also neugierig und spielt gerne so viel ihr wollt mit diesen Datensätzen herum. Solange ihr es während der Kurslaufzeit tut, können eventuell aufkommende Fragen noch im Forum geklärt werden. 4 | 5 | Da ihr in der aktuellen Übung in dieser Woche noch keine optimalen Ergebnisse erzielen werdet und durch die Inhalte der nächsten Woche euer Netz stark verbessern könnt, wollten wir euch an dieser Stelle nochmal speziell die Möglichkeit geben, eine bessere Genauigkeit mit den bis jetzt erlernten Methoden zu erzielen. 6 | 7 | Der Datensatz, den wir euch hierfür vorstellen wollen, nennt sich `deep_weeds` und enthält Bilder von 9 verschiedenen Gräsern. Ebenso steht er ganz unkompliziert unter den Tensorflow Datasätzen zur Verfügbar. Weitere Informationen findet ihr [hier](https://www.tensorflow.org/datasets/catalog/deep_weeds). 8 | 9 | Diese weitere Übungsmöglichkeit ist **komplett freiwillig** und es wird somit **keine Punkte** geben. 10 | 11 | ### Einbindung des Datensatzes 12 | 13 | Über folgenden Befehl kann der Datensatz genauso wie der in Woche 3 behandelte Datensatz eingebunden werden: 14 | 15 | ```python 16 | train_data_weed = tfds.load( 17 | 'deep_weeds', 18 | split='train[:80%]', 19 | as_supervised=True, 20 | with_info=True 21 | ) 22 | 23 | test_data_weed = tfds.load( 24 | 'deep_weeds', 25 | split='train[80%:]', 26 | as_supervised=True, 27 | with_info=True 28 | ) 29 | ``` 30 | 31 | Viel Erfolg bei der Bearbeitung. 32 | -------------------------------------------------------------------------------- /woche4/assignment/exercise2/Exercise_2_solution_week_3.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "nbformat": 4, 3 | "nbformat_minor": 0, 4 | "metadata": { 5 | "accelerator": "GPU", 6 | "colab": { 7 | "name": "Exercise 2 - solution week 3", 8 | "provenance": [], 9 | "collapsed_sections": [], 10 | "machine_shape": "hm" 11 | }, 12 | "kernelspec": { 13 | "display_name": "Python [conda env:MOOC] *", 14 | "language": "python", 15 | "name": "conda-env-MOOC-py" 16 | }, 17 | "language_info": { 18 | "codemirror_mode": { 19 | "name": "ipython", 20 | "version": 3 21 | }, 22 | "file_extension": ".py", 23 | "mimetype": "text/x-python", 24 | "name": "python", 25 | "nbconvert_exporter": "python", 26 | "pygments_lexer": "ipython3", 27 | "version": "3.6.9" 28 | } 29 | }, 30 | "cells": [ 31 | { 32 | "cell_type": "markdown", 33 | "metadata": { 34 | "id": "ntOuL-4wHtZ9", 35 | "colab_type": "text" 36 | }, 37 | "source": [ 38 | "# Lösung Übung 2 - Woche 3 und 4\n", 39 | "\n", 40 | "Mit dem Wissen aus Woche 3 konnte man noch keine sehr zufriedenstellenden Ergebnisse erzielen. Das Problem hierbei war das schnelle Overfitting auf die Daten, da Dropout noch nicht bekannt war und auch Batch Normalization erst in Woche 4 vorgestellt wurde.\n", 41 | "\n", 42 | "Da alle Bilder Hunde zeigen, die sich nicht so einfach voneinander unterscheiden lassen wie die Klassen im ImageNette Datensatz, war hier eine Genauigkeit von 40-50% zu erreichen.\n", 43 | "\n", 44 | "Dieses Notebook stellt keine optimale Lösung dar, soll euch aber zeigen, welches grobe Netz gewählt werden kann.\n" 45 | ] 46 | }, 47 | { 48 | "cell_type": "code", 49 | "metadata": { 50 | "id": "BlNuB2X7JSK6", 51 | "colab_type": "code", 52 | "colab": {} 53 | }, 54 | "source": [ 55 | "%tensorflow_version 2.x" 56 | ], 57 | "execution_count": 0, 58 | "outputs": [] 59 | }, 60 | { 61 | "cell_type": "code", 62 | "metadata": { 63 | "colab_type": "code", 64 | "id": "PRNIed8V-Rry", 65 | "colab": {} 66 | }, 67 | "source": [ 68 | "# TensorFlow ≥2.0 is required\n", 69 | "import tensorflow as tf\n", 70 | "from tensorflow import keras\n", 71 | "assert tf.__version__ >= \"2.0\"\n", 72 | "\n", 73 | "if not tf.test.is_gpu_available():\n", 74 | " print(\"No GPU was detected. CNNs can be very slow without a GPU.\")\n", 75 | " if IS_COLAB:\n", 76 | " print(\"Go to Runtime > Change runtime and select a GPU hardware accelerator.\")\n" 77 | ], 78 | "execution_count": 0, 79 | "outputs": [] 80 | }, 81 | { 82 | "cell_type": "code", 83 | "metadata": { 84 | "colab_type": "code", 85 | "id": "ZO6p-aRv99m-", 86 | "colab": {} 87 | }, 88 | "source": [ 89 | "import numpy as np\n", 90 | "import matplotlib.pyplot as plt\n", 91 | "import tensorflow as tf\n", 92 | "import tensorflow_datasets as tfds\n", 93 | "import numpy as np\n", 94 | "from tensorflow.keras.datasets import mnist\n", 95 | "from tensorflow.keras.layers import Dense, Activation, Input, \\\n", 96 | " Dropout, Conv2D, MaxPooling2D, Flatten\n", 97 | "from tensorflow.keras.models import Model\n", 98 | "import matplotlib.pyplot as plt\n", 99 | "from scipy.stats import reciprocal\n", 100 | "from sklearn.model_selection import GridSearchCV, RandomizedSearchCV\n", 101 | "\n", 102 | "# jupyters magic command\n", 103 | "%matplotlib inline" 104 | ], 105 | "execution_count": 0, 106 | "outputs": [] 107 | }, 108 | { 109 | "cell_type": "code", 110 | "metadata": { 111 | "id": "B0de0EjqZ6i7", 112 | "colab_type": "code", 113 | "outputId": "7dd686bc-5e8a-4b43-b509-a3b25677e76f", 114 | "colab": { 115 | "base_uri": "https://localhost:8080/", 116 | "height": 446 117 | } 118 | }, 119 | "source": [ 120 | "!pip install --upgrade deeplearning2020" 121 | ], 122 | "execution_count": 0, 123 | "outputs": [ 124 | { 125 | "output_type": "stream", 126 | "text": [ 127 | "Collecting deeplearning2020\n", 128 | " Downloading https://files.pythonhosted.org/packages/3a/7f/6fee39d7590f4ae20a976131b1920d56a3dee138c208dfcb3959cd8c5275/deeplearning2020-0.4.21.tar.gz\n", 129 | "Collecting kerasltisubmission>=0.4.9\n", 130 | " Using cached https://files.pythonhosted.org/packages/de/56/0b6adef8e6f5d89e9daa68e03d00850509f1553ce6303c0a49d7c619dd26/kerasltisubmission-0.4.9.tar.gz\n", 131 | "Requirement already satisfied, skipping upgrade: numpy in /usr/local/lib/python3.6/dist-packages (from kerasltisubmission>=0.4.9->deeplearning2020) (1.18.2)\n", 132 | "Requirement already satisfied, skipping upgrade: progressbar2 in /usr/local/lib/python3.6/dist-packages (from kerasltisubmission>=0.4.9->deeplearning2020) (3.38.0)\n", 133 | "Requirement already satisfied, skipping upgrade: requests in /usr/local/lib/python3.6/dist-packages (from kerasltisubmission>=0.4.9->deeplearning2020) (2.21.0)\n", 134 | "Requirement already satisfied, skipping upgrade: python-utils>=2.3.0 in /usr/local/lib/python3.6/dist-packages (from progressbar2->kerasltisubmission>=0.4.9->deeplearning2020) (2.4.0)\n", 135 | "Requirement already satisfied, skipping upgrade: six in /usr/local/lib/python3.6/dist-packages (from progressbar2->kerasltisubmission>=0.4.9->deeplearning2020) (1.12.0)\n", 136 | "Requirement already satisfied, skipping upgrade: certifi>=2017.4.17 in /usr/local/lib/python3.6/dist-packages (from requests->kerasltisubmission>=0.4.9->deeplearning2020) (2020.4.5.1)\n", 137 | "Requirement already satisfied, skipping upgrade: idna<2.9,>=2.5 in /usr/local/lib/python3.6/dist-packages (from requests->kerasltisubmission>=0.4.9->deeplearning2020) (2.8)\n", 138 | "Requirement already satisfied, skipping upgrade: urllib3<1.25,>=1.21.1 in /usr/local/lib/python3.6/dist-packages (from requests->kerasltisubmission>=0.4.9->deeplearning2020) (1.24.3)\n", 139 | "Requirement already satisfied, skipping upgrade: chardet<3.1.0,>=3.0.2 in /usr/local/lib/python3.6/dist-packages (from requests->kerasltisubmission>=0.4.9->deeplearning2020) (3.0.4)\n", 140 | "Building wheels for collected packages: deeplearning2020, kerasltisubmission\n", 141 | " Building wheel for deeplearning2020 (setup.py) ... \u001b[?25l\u001b[?25hdone\n", 142 | " Created wheel for deeplearning2020: filename=deeplearning2020-0.4.21-py2.py3-none-any.whl size=8548 sha256=0ea0830d515fd509f6c003f900371260b49d96430d28f264643bbaae8ab7e93f\n", 143 | " Stored in directory: /root/.cache/pip/wheels/7f/c2/8a/f9f03fc839999f1fe9d5e5a9d2c97cdd5cb8329f61f82ea2c9\n", 144 | " Building wheel for kerasltisubmission (setup.py) ... \u001b[?25l\u001b[?25hdone\n", 145 | " Created wheel for kerasltisubmission: filename=kerasltisubmission-0.4.9-py2.py3-none-any.whl size=8867 sha256=46676efb4bbbe76f1b54684d83c45b469e905af7cf8d5966a5e4826eac478735\n", 146 | " Stored in directory: /root/.cache/pip/wheels/fd/61/f7/09171376b25408ae21b58e98c9fbf2eb924f676bb77659f983\n", 147 | "Successfully built deeplearning2020 kerasltisubmission\n", 148 | "Installing collected packages: kerasltisubmission, deeplearning2020\n", 149 | "Successfully installed deeplearning2020-0.4.21 kerasltisubmission-0.4.9\n" 150 | ], 151 | "name": "stdout" 152 | } 153 | ] 154 | }, 155 | { 156 | "cell_type": "code", 157 | "metadata": { 158 | "id": "Y4f0f8dndDUX", 159 | "colab_type": "code", 160 | "outputId": "ad21602d-5bff-4c0b-a1ef-e883ac7f7109", 161 | "colab": { 162 | "base_uri": "https://localhost:8080/", 163 | "height": 124 164 | } 165 | }, 166 | "source": [ 167 | "from deeplearning2020.datasets import ImageWoof\n", 168 | "train_data, test_data, classes= ImageWoof.load_data()\n" 169 | ], 170 | "execution_count": 0, 171 | "outputs": [ 172 | { 173 | "output_type": "stream", 174 | "text": [ 175 | "Downloading data from https://s3.amazonaws.com/fast-ai-imageclas/imagewoof2-320.tgz\n", 176 | "328294400/328288506 [==============================] - 8s 0us/step\n", 177 | "/root/.keras/datasets/imagewoof2-320/train\n", 178 | "Loaded 9025 images\n", 179 | "/root/.keras/datasets/imagewoof2-320/val\n", 180 | "Loaded 3929 images\n" 181 | ], 182 | "name": "stdout" 183 | } 184 | ] 185 | }, 186 | { 187 | "cell_type": "markdown", 188 | "metadata": { 189 | "id": "Fko1-mNnJ3Ji", 190 | "colab_type": "text" 191 | }, 192 | "source": [ 193 | "## Loading and Preprocessing the data" 194 | ] 195 | }, 196 | { 197 | "cell_type": "code", 198 | "metadata": { 199 | "id": "RDxi995yRt3-", 200 | "colab_type": "code", 201 | "colab": {} 202 | }, 203 | "source": [ 204 | "# resize the images to a uniform size\n", 205 | "def preprocess(image, label):\n", 206 | " resized_image = tf.image.resize(image, [300, 300])\n", 207 | " return resized_image, label" 208 | ], 209 | "execution_count": 0, 210 | "outputs": [] 211 | }, 212 | { 213 | "cell_type": "code", 214 | "metadata": { 215 | "colab_type": "code", 216 | "id": "-aba_6yC99ni", 217 | "outputId": "83adf767-7aab-4163-c403-5ae1aecca3f3", 218 | "colab": { 219 | "base_uri": "https://localhost:8080/", 220 | "height": 70 221 | } 222 | }, 223 | "source": [ 224 | "\n", 225 | "\n", 226 | "batch_size = 32\n", 227 | "print('shape of training data before preprocessing: ', train_data)\n", 228 | "train_data = train_data.shuffle(1000)\n", 229 | "\n", 230 | "\n", 231 | "train_data = train_data.map(preprocess) \\\n", 232 | " .batch(batch_size).prefetch(1)\n", 233 | "test_data = test_data.map(preprocess) \\\n", 234 | " .batch(batch_size).prefetch(1)\n", 235 | "print('shape of training data after preprocessing: ', train_data)\n", 236 | "print('shape of test data after preprocessing: ', test_data)" 237 | ], 238 | "execution_count": 0, 239 | "outputs": [ 240 | { 241 | "output_type": "stream", 242 | "text": [ 243 | "shape of training data before preprocessing: \n", 244 | "shape of training data after preprocessing: \n", 245 | "shape of test data after preprocessing: \n" 246 | ], 247 | "name": "stdout" 248 | } 249 | ] 250 | }, 251 | { 252 | "cell_type": "markdown", 253 | "metadata": { 254 | "id": "NnHSt3CVwrrP", 255 | "colab_type": "text" 256 | }, 257 | "source": [ 258 | "# Architektur des Netzes" 259 | ] 260 | }, 261 | { 262 | "cell_type": "code", 263 | "metadata": { 264 | "id": "Hik8RBJpwvvC", 265 | "colab_type": "code", 266 | "outputId": "ebb8f672-7249-4fb5-e1a4-9de6f3fe5574", 267 | "colab": { 268 | "base_uri": "https://localhost:8080/", 269 | "height": 799 270 | } 271 | }, 272 | "source": [ 273 | "# model\n", 274 | "learning_rate=0.001\n", 275 | "momentum=0.9\n", 276 | "dense_neurons=500\n", 277 | "n_filters=512\n", 278 | "first_kernel_size=(7,7)\n", 279 | "\n", 280 | "activation='elu'\n", 281 | "\n", 282 | "# input size of images must be 300x300 with RGB color\n", 283 | "input_layer = Input(shape=(300, 300, 3))\n", 284 | "\n", 285 | "# Convolutional Neural Network\n", 286 | "# It consists of 5 stacked Convolutional Layers with Max Pooling\n", 287 | "model = Conv2D(\n", 288 | " filters=256,\n", 289 | " kernel_size=(7,7),\n", 290 | " activation=activation\n", 291 | ")(input_layer)\n", 292 | "model = MaxPooling2D((2,2))(model)\n", 293 | "\n", 294 | "model = Conv2D(\n", 295 | " filters = 256, \n", 296 | " kernel_size=(3,3), \n", 297 | " activation=activation\n", 298 | ")(model)\n", 299 | "model = MaxPooling2D((2,2))(model)\n", 300 | "\n", 301 | "model = Conv2D(\n", 302 | " filters = n_filters, \n", 303 | " kernel_size=(3,3), \n", 304 | " activation=activation\n", 305 | ")(model)\n", 306 | "model = MaxPooling2D((2,2))(model)\n", 307 | "\n", 308 | "model = Conv2D(\n", 309 | " filters = n_filters, \n", 310 | " kernel_size=(3,3), \n", 311 | " activation=activation\n", 312 | ")(model)\n", 313 | "model = MaxPooling2D((2,2))(model)\n", 314 | "\n", 315 | "model = Conv2D(filters = n_filters, \n", 316 | " kernel_size=(3,3), \n", 317 | " activation=activation, \n", 318 | " padding='same'\n", 319 | ")(model)\n", 320 | "model = MaxPooling2D((2,2))(model)\n", 321 | "\n", 322 | "model = Conv2D(filters = n_filters, \n", 323 | " kernel_size=(3,3), \n", 324 | " activation=activation, \n", 325 | " padding='same'\n", 326 | ")(model)\n", 327 | "model = MaxPooling2D((2,2))(model)\n", 328 | "\n", 329 | "model = Conv2D(filters = n_filters, \n", 330 | " kernel_size=(3,3), \n", 331 | " activation=activation, \n", 332 | " padding='same'\n", 333 | ")(model)\n", 334 | "\n", 335 | "# Fully-Connected-Classifier\n", 336 | "model = Flatten()(model)\n", 337 | "model = Dense(\n", 338 | " dense_neurons,\n", 339 | " activation=activation\n", 340 | ")(model)\n", 341 | "\n", 342 | "model = Dense(\n", 343 | " dense_neurons / 2,\n", 344 | " activation='tanh'\n", 345 | ")(model)\n", 346 | "\n", 347 | "# Output Layer\n", 348 | "output = Dense(10, activation=\"softmax\")(model)\n", 349 | "\n", 350 | "model = Model(input_layer, output)\n", 351 | "\n", 352 | "# Compiling model\n", 353 | "optimizer = keras.optimizers.SGD(lr=learning_rate, momentum=momentum)\n", 354 | "model.compile(\n", 355 | " loss=\"sparse_categorical_crossentropy\",\n", 356 | " optimizer=optimizer,\n", 357 | " metrics=[\"accuracy\"]\n", 358 | ")\n", 359 | "model.summary()" 360 | ], 361 | "execution_count": 0, 362 | "outputs": [ 363 | { 364 | "output_type": "stream", 365 | "text": [ 366 | "Model: \"model\"\n", 367 | "_________________________________________________________________\n", 368 | "Layer (type) Output Shape Param # \n", 369 | "=================================================================\n", 370 | "input_1 (InputLayer) [(None, 300, 300, 3)] 0 \n", 371 | "_________________________________________________________________\n", 372 | "conv2d (Conv2D) (None, 294, 294, 256) 37888 \n", 373 | "_________________________________________________________________\n", 374 | "max_pooling2d (MaxPooling2D) (None, 147, 147, 256) 0 \n", 375 | "_________________________________________________________________\n", 376 | "conv2d_1 (Conv2D) (None, 145, 145, 256) 590080 \n", 377 | "_________________________________________________________________\n", 378 | "max_pooling2d_1 (MaxPooling2 (None, 72, 72, 256) 0 \n", 379 | "_________________________________________________________________\n", 380 | "conv2d_2 (Conv2D) (None, 70, 70, 512) 1180160 \n", 381 | "_________________________________________________________________\n", 382 | "max_pooling2d_2 (MaxPooling2 (None, 35, 35, 512) 0 \n", 383 | "_________________________________________________________________\n", 384 | "conv2d_3 (Conv2D) (None, 33, 33, 512) 2359808 \n", 385 | "_________________________________________________________________\n", 386 | "max_pooling2d_3 (MaxPooling2 (None, 16, 16, 512) 0 \n", 387 | "_________________________________________________________________\n", 388 | "conv2d_4 (Conv2D) (None, 16, 16, 512) 2359808 \n", 389 | "_________________________________________________________________\n", 390 | "max_pooling2d_4 (MaxPooling2 (None, 8, 8, 512) 0 \n", 391 | "_________________________________________________________________\n", 392 | "conv2d_5 (Conv2D) (None, 8, 8, 512) 2359808 \n", 393 | "_________________________________________________________________\n", 394 | "max_pooling2d_5 (MaxPooling2 (None, 4, 4, 512) 0 \n", 395 | "_________________________________________________________________\n", 396 | "conv2d_6 (Conv2D) (None, 4, 4, 512) 2359808 \n", 397 | "_________________________________________________________________\n", 398 | "flatten (Flatten) (None, 8192) 0 \n", 399 | "_________________________________________________________________\n", 400 | "dense (Dense) (None, 500) 4096500 \n", 401 | "_________________________________________________________________\n", 402 | "dense_1 (Dense) (None, 250) 125250 \n", 403 | "_________________________________________________________________\n", 404 | "dense_2 (Dense) (None, 10) 2510 \n", 405 | "=================================================================\n", 406 | "Total params: 15,471,620\n", 407 | "Trainable params: 15,471,620\n", 408 | "Non-trainable params: 0\n", 409 | "_________________________________________________________________\n" 410 | ], 411 | "name": "stdout" 412 | } 413 | ] 414 | }, 415 | { 416 | "cell_type": "code", 417 | "metadata": { 418 | "id": "G9J5rOK-w2qA", 419 | "colab_type": "code", 420 | "outputId": "20a1697f-4e23-4a2f-fe01-e5ed0009be52", 421 | "colab": { 422 | "base_uri": "https://localhost:8080/", 423 | "height": 373 424 | } 425 | }, 426 | "source": [ 427 | "# Train the model\n", 428 | "history = model.fit(\n", 429 | " train_data,\n", 430 | " epochs=10,\n", 431 | " validation_data = test_data\n", 432 | ")" 433 | ], 434 | "execution_count": 0, 435 | "outputs": [ 436 | { 437 | "output_type": "stream", 438 | "text": [ 439 | "Epoch 1/10\n", 440 | "283/283 [==============================] - 123s 436ms/step - loss: 0.8194 - accuracy: 0.7309 - val_loss: 1.9239 - val_accuracy: 0.4100\n", 441 | "Epoch 2/10\n", 442 | "283/283 [==============================] - 123s 436ms/step - loss: 0.6151 - accuracy: 0.8079 - val_loss: 2.0038 - val_accuracy: 0.4123\n", 443 | "Epoch 3/10\n", 444 | "283/283 [==============================] - 123s 436ms/step - loss: 0.2568 - accuracy: 0.9378 - val_loss: 2.2265 - val_accuracy: 0.4065\n", 445 | "Epoch 4/10\n", 446 | "283/283 [==============================] - 123s 435ms/step - loss: 0.1921 - accuracy: 0.9591 - val_loss: 2.3152 - val_accuracy: 0.4093\n", 447 | "Epoch 5/10\n", 448 | "283/283 [==============================] - 123s 436ms/step - loss: 0.0354 - accuracy: 0.9981 - val_loss: 2.3080 - val_accuracy: 0.4291\n", 449 | "Epoch 6/10\n", 450 | "283/283 [==============================] - 123s 436ms/step - loss: 0.0127 - accuracy: 0.9998 - val_loss: 2.3591 - val_accuracy: 0.4383\n", 451 | "Epoch 7/10\n", 452 | "283/283 [==============================] - 123s 436ms/step - loss: 0.0079 - accuracy: 0.9999 - val_loss: 2.4098 - val_accuracy: 0.4378\n", 453 | "Epoch 8/10\n", 454 | "283/283 [==============================] - 123s 436ms/step - loss: 0.0063 - accuracy: 0.9999 - val_loss: 2.4507 - val_accuracy: 0.4421\n", 455 | "Epoch 9/10\n", 456 | "283/283 [==============================] - 123s 436ms/step - loss: 0.0051 - accuracy: 0.9999 - val_loss: 2.4821 - val_accuracy: 0.4434\n", 457 | "Epoch 10/10\n", 458 | "283/283 [==============================] - 123s 436ms/step - loss: 0.0043 - accuracy: 0.9999 - val_loss: 2.5138 - val_accuracy: 0.4396\n" 459 | ], 460 | "name": "stdout" 461 | } 462 | ] 463 | } 464 | ] 465 | } -------------------------------------------------------------------------------- /woche4/assignment/exercise2/README.md: -------------------------------------------------------------------------------- 1 | **Diese Übung ist für Woche 3 und Woche 4 gedacht. In den nächsten beiden Kurswochen werdet ihr vielfältige Möglichkeiten kennenlernen die Genauigkeit eures Netzes zu verbessern.** 2 | 3 | EDIT: Die Lösungen zu dieser Übung befinden sich unter den folgenden Links: 4 | - [Lösung nach Woche 3](https://colab.research.google.com/drive/1Oqdv-ldz4WZJqhMbcjQJ24fBh2km4xIb) 5 | - [Lösung nach Woche 3 mit weniger Parametern](https://colab.research.google.com/drive/1C0YDbJb7qug0ibum4Ox8MI3l2vHSSi_G) 6 | - [Lösung nach Woche 4 mit Transferlearning](https://colab.research.google.com/drive/1JSgk_njvRxCl5njT1pQ1WuSKOnwzen9T) 7 | 8 | ![ImageWoof](https://drive.google.com/uc?id=1UVjiie92RMAcsmSgRpNugANX2m7nJOIx) 9 | 10 | **Errinnerung**: Durch die Bearbeitung der Übungen können insgesamt bis zu **40%** Prozent der Kurspunkte erhalten werden. Diese Summe setzt sich aus der Übung in dieser Woche (25%) und der Übung aus Woche 2 (15%) zusammen. 11 | 12 | #### Was sollt ihr in dieser Übung lernen? 13 | 14 | In dieser Kurswoche habt ihr gelernt, wie komplexere neuronale Netze aufgebaut werden und wie ihr diese auf eure Trainingsdaten anpassen könnt. Die Aufgabe in dieser Woche besteht darin, ein neuronales Netz für einen komplexen Datensatz zu trainieren und damit selbst durch Ausprobieren der verschiedenen Parameter weitere Einblicke in die Entwicklung neuronaler Netze zu erhalten. Dabei ist es egal, ob ihr [Google Colab](https://colab.research.google.com/) oder eine lokale Installation verwendet. Wir würden jedoch den Einsatz von Google Colab empfehlen, da ihr dort meist leistungsfähigere Hardware einsetzen könnt, die den Trainigsprozess stark beschleunigt. 15 | 16 | **Ziel ist es, ein Netz für den im folgenden vorgestellten Datensatz zu trainieren, das dessen Bilder so zuverlässig wie möglich klassifiziert.** 17 | 18 | #### Welchen Datensatz sollt ihr benutzen? 19 | 20 | Es wird wieder ein Teildatensatz des Imagenets benutzt. Dieser wird von Fast.ai zur Verfügung gestellt und kann [hier](https://github.com/fastai/imagenette) heruntergeladen werden. 21 | 22 | Die sehr genaue Klassifizierung ist hier nicht einfach und soll euch anregen, mit verschiedenen Parametern herumzuspielen. 23 | 24 | Der Datensatz besteht aus **10.000 Trainings-** und **3000 Testdaten**. Genauso wie beim Imagenette Datensatz, der in dieser Woche verwendet wurde, sind die Bilder in einer Dimension 320px groß und können wie in dieser Woche vorgestellt, verarbeitet werden. 25 | 26 | Jedes Bild ist mit je einer der **10 Klassen** klassifiziert, welche verschiedene Hunderassen darstellen. Dabei handelt es sich um Australian Terrier, Border Terrier, Samoyed, Beagle, Shih-Tzu, English Foxhound, Rhodesian Ridgeback, Dingo, Golden Retriever und Old English Sheepdog. Die genaue Liste an Klassen findet ihr [hier](https://github.com/fastai/imagenette). 27 | 28 | Euer Netz soll also lernen, zwischen verschiedenen Hunderassen zu unterscheiden. 29 | 30 | #### Wie bekommt ihr den Datensatz? 31 | 32 | Wir haben euch über unser `deeplearning2020` python package eine Funktion bereitgestellt, mit der ihr die Daten laden könnt. Diese kann folgendermaßen verwendet werden: 33 | 34 | ```python 35 | # ohne Ausrufezeichen bei Ausführung im lokalen Notebook 36 | !pip install --upgrade deeplearning2020 37 | from deeplearning2020.datasets import ImageWoof 38 | 39 | train_data, test_data, classes = ImageWoof.load_data() 40 | ``` 41 | Der Datensatz ist in einen `train_data` (Trainigsdaten) und einen `test_data` (Validierungdaten) Datensatz aufgeteilt, welche ihr wie oben gezeigt laden könnt. 42 | 43 | Die `load_data()` Funktion liefert sowohl einen Datensatz zurück, mit dem ihr genauso arbeiten könnt, wie mit den den aus `tfds.load` geladenen Datensets. 44 | 45 | Der Unterschied ist, dass wir euch mit diesem Befehl Trainigsdaten (Bilder und Label), Testdaten (Bilder und Label) und auch die Klassennamen über `classes` bereitstellen. Damit könnt ihr dann weiterarbeiten. 46 | 47 | Um einen Eindruck über die Klassen zu bekommen, könnt ihr folgendes ausführen: 48 | Wie im Notebook in dieser Woche gezeigt,könnt ihr über `helpers.plot_images(train_data.take(9), classes)` Bilder des Datensatzes anzeigen, um einen Eindruck zu bekommen, wie diese aussehen. 49 | 50 | 51 | Hier noch ein paar weitere Informationen zum Datensatz: 52 | - Die Bildpunkte sind als Floats zwischen 0 und 1 gespeichert. Das heißt für euch, dass die im Notebook 3.5.2 genutzte `preprocessing` Funktion genutzt werden kann, wobei das Teilen durch 255 weggelassen werden muss. 53 | - Die Labels der Daten liegen in sparse Form vor. Das heißt für euch, dass ihr die `sparse_categorical_crossentropy` Fehlerfunktion nutzen solltet. 54 | 55 | Somit sieht die preprocessing Funktion dieser Woche so aus: 56 | ```python 57 | def preprocess(image, label): 58 | resized_image = tf.image.resize(image, [300, 300]) 59 | return resized_image, label 60 | ``` 61 | Dies ist notwendig, da die Bilder nicht in der gleichen Bildgröße vorkommen und somit vorher auf eine einheitliche Größe resized werden müssen. 62 | 63 | Um auf dem Netz trainieren zu können orientiert ihr euch am besten am [Notebook zum Video `3.5.2`](https://colab.research.google.com/drive/18BGSjiQ9h7-XJ45HNV0iK2coaRTd8AQk), so das preprocessing der Daten im Abschnitt **Preprocessing der Daten zur schnelleren Verarbeitung** vorgestellt ist. 64 | 65 | #### Ich weiß nicht, wie ich anfangen soll 66 | 67 | Falls du nicht weißt, wie du am Besten anfangen solltest, orientiere dich am [Praxisvideo zum komplexen Aufbau neuronaler Netze](https://colab.research.google.com/drive/18BGSjiQ9h7-XJ45HNV0iK2coaRTd8AQk). Schau dir dazu am besten das kommentierte Notebook an, welches du unter Lehrmaterialien zu diesem Video findest. 68 | 69 | Realistische Werte für die Validation Accuracy für diesen Datensatz mit den gelernten Methoden aus Woche 3 sind um die 50% mit starken Overfitting. In der nächsten Kurswoche werdet ihr diese schrittweise verbessern können. 70 | 71 | Seid gerne ermutigt, neue Techniken auszuprobieren und an Parametern zu schrauben! 72 | 73 | #### Wie reicht ihr eure Lösung ein? 74 | 75 | Nachdem ihr euer Keras Netz trainiert habt, könnt ihr es ganz einfach hochladen: 76 | 77 | 1. Gehe dazu auf [open.hpi.de](https://open.hpi.de/) auf die Übungsaufgabe und klicke auf *Aufgabe starten*. 78 | 2. Es sollte sich ein neuer Tab öffnen, welcher dir den Python Code anzeigt, den du zur Abgabe deines Keras Models benötigst. Alle benötigten Informationen findest du dort auch in der Beschreibung. Trotzdem an dieser Stelle noch einmal: 79 | 1. Falls noch nicht getan, installiere das Python Package zu diesem Kurs mit Hilfe von pip: 80 | ``` 81 | pip install --upgrade deeplearning2020 82 | ``` 83 | 84 | In einem Jupyter Notebook (Google Colab oder lokal) geht das mit: 85 | ``` 86 | !pip install --upgrade deeplearning2020 87 | ``` 88 | 2. Importieren des Package 89 | ```python 90 | from deeplearning2020 import Submission 91 | ``` 92 | 3. Submitte dein Model, wobei du den Token und die Assignment ID von der Webseite kopieren musst: 93 | ```python 94 | Submission('', '', model).submit() 95 | ``` 96 | Falls du für dein Model einen anderen Variablennamen als `model` verwendest, musst du diese Variable entsprechend verwenden. 97 | 98 | 3. Mit dem Ausführen sollte das Model von uns validiert werden und du erhältst abschließend eine Accuracy und Benotung. **Unsere Accuracy kann sich von euer Accuracy unterscheiden, da wir euer Model mit Werten testen, die es eventuell noch nie gesehen hat. Das gilt aber gleichermaßen für alle Teilnehmer.** 99 | 100 | **Ihr könnt euer trainiertes Model beliebig oft submitten und es wird automatisch das beste Ergebnis gewählt, ohne dass ihr etwas machen müsst.** 101 | 102 | #### Wie werden wir eure Lösungen bewerten? 103 | 104 | In dieser Übung wird mit einem komplexeren Datensatz gearbeitet. Seid daher nicht frustriert, wenn ihr keine perfekte Accuracy erhaltet. In der nächsten Kurswoche werden Techniken vorgestellt, mit denen ihr dieses Netz verbessern könnt, sodass ihr eine höhere Genauigkeit erzielt und damit auch eine bessere Bewertung für die Übung. Sie ist also bewusst darauf ausgelegt, über beide Kurswochen gestreckt zu sein. Fangt also diese Woche mit der Bearbeitung der Aufgabe an und verbessert euer Netz in der nächsten Kurswoche. 105 | 106 | Eure Abgabe bewerten wir nach folgender Bewertungsgrundlage: 107 | 108 | - Bei einer **Accuracy >= 0.95** (95%) gibt es volle Punktzahl 109 | - Bei einer **Accuracy = 0.0** (0%) gibt es 0 Punkte 110 | - Alles dazwischen wird entsprechend linear interpoliert 111 | 112 | ### Schwierigkeit der Übung 113 | 114 | Wie ihr bei der Arbeit mit dem Datensatz vielleicht feststellen werdet, ist eine sehr gute Accuracy mit dem Wissen aus Woche 3 noch nicht machbar. Aus diesem Grund habt ihr auch in Woche 4 genügend Zeit, die Übung dann weiter zu bearbeiten. Wir würden euch trotzdem darum bitten, auch in dieser Woche schon herumzuprobieren, um das Wissen aus dieser Woche praktisch anzuwenden. 115 | 116 | Falls ihr mit einem anderen Datensatz arbeiten möchtet, könnt ihr gerne, die von uns zusätzlich bereitgestellte Möglichkeit der extra Übung nutzen. Weitere Informationen findet ihr [hier](https://open.hpi.de/courses/neuralnets2020/items/3vh2FG4fjjKKNPA2GnoQ8r). 117 | 118 | Wir wünschen euch viel Spaß und Erfolg bei der Übung! 119 | -------------------------------------------------------------------------------- /woche4/gan/README.md: -------------------------------------------------------------------------------- 1 | #### Generative Adversarial Networks (GAN) 2 | 3 | [Notebook](./exkurs-gan.ipynb) 4 | 5 | In Google Colab ist dieses Notebook unter 6 | [diesem Link](https://colab.research.google.com/drive/1Q3mk3dI61wXn2VlbDfCUNeN3l9BoiCKB) erreichbar. 7 | -------------------------------------------------------------------------------- /woche4/notebooks/automated-machine-learning/README.md: -------------------------------------------------------------------------------- 1 | #### Automated Machine Learning 2 | 3 | Notebooks 4 | - [Automated Machine Learning](./automated-machine-learning.ipynb) 5 | 6 | In Google Colab ist dieses Notebook unter 7 | [diesem Link](https://colab.research.google.com/github/into-ai/deeplearning2020/blob/master/woche4/notebooks/automated-machine-learning/automated-machine-learning.ipynb) erreichbar. 8 | -------------------------------------------------------------------------------- /woche4/notebooks/automated-machine-learning/automated-machine-learning.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": { 6 | "id": "W2TBIAmXHUES", 7 | "colab_type": "text" 8 | }, 9 | "source": [ 10 | "# Automated Machine Learning with Auto-Keras" 11 | ] 12 | }, 13 | { 14 | "cell_type": "markdown", 15 | "metadata": { 16 | "id": "K3BcRKp4Bv2P", 17 | "colab_type": "text" 18 | }, 19 | "source": [ 20 | "## Imports and Version Selection" 21 | ] 22 | }, 23 | { 24 | "cell_type": "code", 25 | "execution_count": 0, 26 | "metadata": { 27 | "colab_type": "code", 28 | "id": "PRNIed8V-Rry", 29 | "outputId": "eec587a6-be2a-4266-a802-d446323a6280", 30 | "colab": { 31 | "base_uri": "https://localhost:8080/", 32 | "height": 91.0 33 | } 34 | }, 35 | "outputs": [ 36 | { 37 | "name": "stdout", 38 | "output_type": "stream", 39 | "text": [ 40 | "WARNING:tensorflow:From :5: is_gpu_available (from tensorflow.python.framework.test_util) is deprecated and will be removed in a future version.\n", 41 | "Instructions for updating:\n", 42 | "Use `tf.config.list_physical_devices('GPU')` instead.\n" 43 | ] 44 | } 45 | ], 46 | "source": [ 47 | "# TensorFlow ≥2.0 is required\n", 48 | "import tensorflow as tf\n", 49 | "from tensorflow import keras\n", 50 | "assert tf.__version__ >= \"2.0\"\n", 51 | "\n", 52 | "if not tf.test.is_gpu_available():\n", 53 | " print(\"No GPU was detected. CNNs can be very slow without a GPU.\")\n", 54 | " if IS_COLAB:\n", 55 | " print(\"Go to Runtime > Change runtime and select a GPU hardware accelerator.\")\n" 56 | ] 57 | }, 58 | { 59 | "cell_type": "code", 60 | "execution_count": 0, 61 | "metadata": { 62 | "colab_type": "code", 63 | "id": "ZO6p-aRv99m-", 64 | "outputId": "af945252-4a68-4615-ec08-7c36e44eb5d5", 65 | "colab": { 66 | "base_uri": "https://localhost:8080/", 67 | "height": 235.0 68 | } 69 | }, 70 | "outputs": [ 71 | { 72 | "name": "stdout", 73 | "output_type": "stream", 74 | "text": [ 75 | "Requirement already up-to-date: deeplearning2020 in /usr/local/lib/python3.6/dist-packages (0.4.18)\n", 76 | "Requirement already satisfied, skipping upgrade: kerasltisubmission>=0.4.9 in /usr/local/lib/python3.6/dist-packages (from deeplearning2020) (0.4.9)\n", 77 | "Requirement already satisfied, skipping upgrade: numpy in /usr/local/lib/python3.6/dist-packages (from kerasltisubmission>=0.4.9->deeplearning2020) (1.18.2)\n", 78 | "Requirement already satisfied, skipping upgrade: requests in /usr/local/lib/python3.6/dist-packages (from kerasltisubmission>=0.4.9->deeplearning2020) (2.21.0)\n", 79 | "Requirement already satisfied, skipping upgrade: progressbar2 in /usr/local/lib/python3.6/dist-packages (from kerasltisubmission>=0.4.9->deeplearning2020) (3.38.0)\n", 80 | "Requirement already satisfied, skipping upgrade: urllib3<1.25,>=1.21.1 in /usr/local/lib/python3.6/dist-packages (from requests->kerasltisubmission>=0.4.9->deeplearning2020) (1.24.3)\n", 81 | "Requirement already satisfied, skipping upgrade: idna<2.9,>=2.5 in /usr/local/lib/python3.6/dist-packages (from requests->kerasltisubmission>=0.4.9->deeplearning2020) (2.8)\n", 82 | "Requirement already satisfied, skipping upgrade: certifi>=2017.4.17 in /usr/local/lib/python3.6/dist-packages (from requests->kerasltisubmission>=0.4.9->deeplearning2020) (2019.11.28)\n", 83 | "Requirement already satisfied, skipping upgrade: chardet<3.1.0,>=3.0.2 in /usr/local/lib/python3.6/dist-packages (from requests->kerasltisubmission>=0.4.9->deeplearning2020) (3.0.4)\n", 84 | "Requirement already satisfied, skipping upgrade: python-utils>=2.3.0 in /usr/local/lib/python3.6/dist-packages (from progressbar2->kerasltisubmission>=0.4.9->deeplearning2020) (2.4.0)\n", 85 | "Requirement already satisfied, skipping upgrade: six in /usr/local/lib/python3.6/dist-packages (from progressbar2->kerasltisubmission>=0.4.9->deeplearning2020) (1.12.0)\n" 86 | ] 87 | } 88 | ], 89 | "source": [ 90 | "import numpy as np\n", 91 | "import matplotlib.pyplot as plt\n", 92 | "import tensorflow as tf\n", 93 | "import tensorflow_datasets as tfds\n", 94 | "import numpy as np\n", 95 | "from tensorflow.keras.datasets import mnist\n", 96 | "from tensorflow.keras.layers import Dense, Activation, Input, Dropout, Conv2D, MaxPooling2D, Flatten\n", 97 | "from tensorflow.keras.models import Model\n", 98 | "import matplotlib.pyplot as plt\n", 99 | "\n", 100 | "!pip install --upgrade deeplearning2020\n", 101 | "from deeplearning2020 import helpers\n", 102 | "\n", 103 | "# jupyters magic command\n", 104 | "%matplotlib inline" 105 | ] 106 | }, 107 | { 108 | "cell_type": "code", 109 | "execution_count": 0, 110 | "metadata": { 111 | "colab_type": "code", 112 | "id": "cFMqXEbU99nb", 113 | "colab": {} 114 | }, 115 | "outputs": [], 116 | "source": [ 117 | "" 118 | ] 119 | }, 120 | { 121 | "cell_type": "markdown", 122 | "metadata": { 123 | "id": "y_bDm2PzB-_A", 124 | "colab_type": "text" 125 | }, 126 | "source": [ 127 | "## Loading and Preprocessing" 128 | ] 129 | }, 130 | { 131 | "cell_type": "code", 132 | "execution_count": 0, 133 | "metadata": { 134 | "colab_type": "code", 135 | "id": "3L0mN6fs99nJ", 136 | "outputId": "b0feb6d2-baff-4337-bfde-1c6d0291f22c", 137 | "colab": { 138 | "base_uri": "https://localhost:8080/", 139 | "height": 89.0 140 | } 141 | }, 142 | "outputs": [ 143 | { 144 | "name": "stdout", 145 | "output_type": "stream", 146 | "text": [ 147 | "dataset size: 3670\n", 148 | "class names: ['dandelion', 'daisy', 'tulips', 'sunflowers', 'roses']\n", 149 | "number of classes: 5\n", 150 | "\n" 151 | ] 152 | } 153 | ], 154 | "source": [ 155 | "# download the dataset with labels and with information about the data\n", 156 | "data, info = tfds.load(\"tf_flowers\", as_supervised=True, with_info=True)\n", 157 | "\n", 158 | "# print the most important information\n", 159 | "dataset_size = info.splits['train'].num_examples\n", 160 | "print('dataset size: ', dataset_size)\n", 161 | "class_names = info.features['label'].names\n", 162 | "print('class names: ', class_names)\n", 163 | "n_classes = info.features['label'].num_classes\n", 164 | "print('number of classes: ', n_classes)\n", 165 | "\n", 166 | "# resize the images to a uniform size\n", 167 | "def preprocess(image, label):\n", 168 | " resized_image = tf.image.resize(image, [224, 224])\n", 169 | " resized_image /= 255\n", 170 | "\n", 171 | " # one-hot encode the labels, because autokeras needs this form\n", 172 | " label = tf.one_hot(label, n_classes)\n", 173 | " return resized_image, label\n", 174 | "\n", 175 | "batch_size = 32\n", 176 | "\n", 177 | "try:\n", 178 | " train_data = tfds.load('tf_flowers', split=\"train[:80%]\", as_supervised=True)\n", 179 | " test_data = tfds.load('tf_flowers', split=\"train[80%:100%]\", as_supervised=True)\n", 180 | " train_data = train_data.shuffle(1000).map(preprocess)\n", 181 | " test_data = test_data.map(preprocess)\n", 182 | "except(Exception):\n", 183 | " # split the data into train and test data with a 8:2 ratio\n", 184 | " train_split, test_split = tfds.Split.TRAIN.subsplit([8, 2])\n", 185 | " train_data = tfds.load('tf_flowers', split=train_split, as_supervised=True)\n", 186 | " test_data = tfds.load('tf_flowers', split=test_split, as_supervised=True)\n", 187 | " train_data = train_data.shuffle(1000).map(preprocess)\n", 188 | " test_data = test_data.map(preprocess)\n", 189 | "\n", 190 | "print(train_data)\n", 191 | "# convert tf.dataset to numpy array\n", 192 | "# X, y, X_test, y_test = helpers.dataset_to_ndarray(train_data, test_data)\n", 193 | "\n", 194 | "# X = X/255.0\n", 195 | "# X_test = X_test/255.0" 196 | ] 197 | }, 198 | { 199 | "cell_type": "markdown", 200 | "metadata": { 201 | "id": "PFOeGXdTCZBj", 202 | "colab_type": "text" 203 | }, 204 | "source": [ 205 | "## Additional necessary import" 206 | ] 207 | }, 208 | { 209 | "cell_type": "code", 210 | "execution_count": 0, 211 | "metadata": { 212 | "colab_type": "code", 213 | "id": "kzPVsPlS99np", 214 | "outputId": "4ec4d5ec-c2de-4d88-9a3f-61add3c41d3f", 215 | "colab": { 216 | "base_uri": "https://localhost:8080/", 217 | "height": 433.0 218 | } 219 | }, 220 | "outputs": [ 221 | { 222 | "name": "stdout", 223 | "output_type": "stream", 224 | "text": [ 225 | "Requirement already satisfied: autokeras in /usr/local/lib/python3.6/dist-packages (1.0.2)\n", 226 | "Requirement already satisfied: pandas in /usr/local/lib/python3.6/dist-packages (from autokeras) (1.0.3)\n", 227 | "Requirement already satisfied: numpy in /usr/local/lib/python3.6/dist-packages (from autokeras) (1.18.2)\n", 228 | "Requirement already satisfied: packaging in /usr/local/lib/python3.6/dist-packages (from autokeras) (20.3)\n", 229 | "Requirement already satisfied: keras-tuner>=1.0.1 in /usr/local/lib/python3.6/dist-packages (from autokeras) (1.0.1)\n", 230 | "Requirement already satisfied: scikit-learn in /usr/local/lib/python3.6/dist-packages (from autokeras) (0.22.2.post1)\n", 231 | "Requirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.6/dist-packages (from pandas->autokeras) (2018.9)\n", 232 | "Requirement already satisfied: python-dateutil>=2.6.1 in /usr/local/lib/python3.6/dist-packages (from pandas->autokeras) (2.8.1)\n", 233 | "Requirement already satisfied: pyparsing>=2.0.2 in /usr/local/lib/python3.6/dist-packages (from packaging->autokeras) (2.4.6)\n", 234 | "Requirement already satisfied: six in /usr/local/lib/python3.6/dist-packages (from packaging->autokeras) (1.12.0)\n", 235 | "Requirement already satisfied: terminaltables in /usr/local/lib/python3.6/dist-packages (from keras-tuner>=1.0.1->autokeras) (3.1.0)\n", 236 | "Requirement already satisfied: tqdm in /usr/local/lib/python3.6/dist-packages (from keras-tuner>=1.0.1->autokeras) (4.38.0)\n", 237 | "Requirement already satisfied: tabulate in /usr/local/lib/python3.6/dist-packages (from keras-tuner>=1.0.1->autokeras) (0.8.7)\n", 238 | "Requirement already satisfied: colorama in /usr/local/lib/python3.6/dist-packages (from keras-tuner>=1.0.1->autokeras) (0.4.3)\n", 239 | "Requirement already satisfied: requests in /usr/local/lib/python3.6/dist-packages (from keras-tuner>=1.0.1->autokeras) (2.21.0)\n", 240 | "Requirement already satisfied: scipy in /usr/local/lib/python3.6/dist-packages (from keras-tuner>=1.0.1->autokeras) (1.4.1)\n", 241 | "Requirement already satisfied: future in /usr/local/lib/python3.6/dist-packages (from keras-tuner>=1.0.1->autokeras) (0.16.0)\n", 242 | "Requirement already satisfied: joblib>=0.11 in /usr/local/lib/python3.6/dist-packages (from scikit-learn->autokeras) (0.14.1)\n", 243 | "Requirement already satisfied: idna<2.9,>=2.5 in /usr/local/lib/python3.6/dist-packages (from requests->keras-tuner>=1.0.1->autokeras) (2.8)\n", 244 | "Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.6/dist-packages (from requests->keras-tuner>=1.0.1->autokeras) (2019.11.28)\n", 245 | "Requirement already satisfied: chardet<3.1.0,>=3.0.2 in /usr/local/lib/python3.6/dist-packages (from requests->keras-tuner>=1.0.1->autokeras) (3.0.4)\n", 246 | "Requirement already satisfied: urllib3<1.25,>=1.21.1 in /usr/local/lib/python3.6/dist-packages (from requests->keras-tuner>=1.0.1->autokeras) (1.24.3)\n" 247 | ] 248 | } 249 | ], 250 | "source": [ 251 | "!pip install autokeras\n", 252 | "import autokeras as ak" 253 | ] 254 | }, 255 | { 256 | "cell_type": "markdown", 257 | "metadata": { 258 | "id": "21Mr6U7KChWj", 259 | "colab_type": "text" 260 | }, 261 | "source": [ 262 | "## Definition and Training" 263 | ] 264 | }, 265 | { 266 | "cell_type": "code", 267 | "execution_count": 0, 268 | "metadata": { 269 | "colab_type": "code", 270 | "id": "cGgLOgDq99nv", 271 | "colab": {} 272 | }, 273 | "outputs": [], 274 | "source": [ 275 | "clf = ak.ImageClassifier(max_trials=10)" 276 | ] 277 | }, 278 | { 279 | "cell_type": "code", 280 | "execution_count": 0, 281 | "metadata": { 282 | "colab_type": "code", 283 | "id": "qJlQ6jbn99nz", 284 | "colab": {} 285 | }, 286 | "outputs": [], 287 | "source": [ 288 | "# Auto-Keras often has a lot of bugs, so don't be surprised in case it doesn't work as expected\n", 289 | "clf.fit(train_data)" 290 | ] 291 | }, 292 | { 293 | "cell_type": "markdown", 294 | "metadata": { 295 | "id": "lGIDqn2nCpQp", 296 | "colab_type": "text" 297 | }, 298 | "source": [ 299 | "## Validierung" 300 | ] 301 | }, 302 | { 303 | "cell_type": "code", 304 | "execution_count": 0, 305 | "metadata": { 306 | "colab_type": "code", 307 | "id": "jT2AhmMU99n6", 308 | "colab": {} 309 | }, 310 | "outputs": [], 311 | "source": [ 312 | "clf.evaluate(test_data)" 313 | ] 314 | }, 315 | { 316 | "cell_type": "code", 317 | "execution_count": 0, 318 | "metadata": { 319 | "id": "AJtPHlucHoci", 320 | "colab_type": "code", 321 | "colab": {} 322 | }, 323 | "outputs": [], 324 | "source": [ 325 | "" 326 | ] 327 | } 328 | ], 329 | "metadata": { 330 | "accelerator": "GPU", 331 | "colab": { 332 | "name": "4.8 Automated Machine Learning.ipynb", 333 | "provenance": [], 334 | "collapsed_sections": [ 335 | "ChA9nDuqB33I" 336 | ], 337 | "machine_shape": "hm" 338 | }, 339 | "kernelspec": { 340 | "name": "python3", 341 | "display_name": "Python 3" 342 | } 343 | }, 344 | "nbformat": 4, 345 | "nbformat_minor": 0 346 | } 347 | -------------------------------------------------------------------------------- /woche4/notebooks/batch-normalization/README.md: -------------------------------------------------------------------------------- 1 | #### Batch Normalization 2 | 3 | Notebooks 4 | - [Batch Normalization](./batch-normalization.ipynb) 5 | 6 | In Google Colab ist dieses Notebook unter 7 | [diesem Link](https://colab.research.google.com/github/into-ai/deeplearning2020/blob/master/woche4/notebooks/batch-normalization/batch-normalization.ipynb) erreichbar. 8 | -------------------------------------------------------------------------------- /woche4/notebooks/dropout/README.md: -------------------------------------------------------------------------------- 1 | #### Dropout 2 | 3 | Notebooks 4 | - [Dropout](./dropout.ipynb) 5 | 6 | In Google Colab ist dieses Notebook unter 7 | [diesem Link](https://colab.research.google.com/github/into-ai/deeplearning2020/blob/master/woche4/notebooks/dropout/dropout.ipynb) erreichbar. 8 | -------------------------------------------------------------------------------- /woche4/notebooks/hyperparameter-optimization/README.md: -------------------------------------------------------------------------------- 1 | #### Optimierung Hyperparameter 2 | 3 | Notebooks 4 | - [Optimierung Hyperparameter](./hyperparameter-optimization.ipynb) 5 | 6 | In Google Colab ist dieses Notebook unter [diesem Link](https://colab.research.google.com/github/into-ai/deeplearning2020/blob/master/woche4/notebooks/hyperparameter-optimization/hyperparameter-optimization.ipynb) erreichbar. 7 | -------------------------------------------------------------------------------- /woche4/notebooks/regularization-techniques/README.md: -------------------------------------------------------------------------------- 1 | #### Regularisierungstechniken 2 | 3 | Notebooks 4 | - [Data Augmentation](./data-augmentation.ipynb) (in [Colab](https://colab.research.google.com/github/into-ai/deeplearning2020/blob/master/woche4/notebooks/regularization-techniques/data-augmentation.ipynb)) 5 | - [Regularisierungstechniken Zusammenfassung](./summary-regularization-techniques.ipynb) (in [Colab](https://colab.research.google.com/github/into-ai/deeplearning2020/blob/master/woche4/notebooks/regularization-techniques/summary-regularization-techniques.ipynb)) 6 | 7 | -------------------------------------------------------------------------------- /woche4/notebooks/transfer-learning/README.md: -------------------------------------------------------------------------------- 1 | #### Transfer Learning 2 | 3 | Notebooks 4 | - [Transfer Learning](./transfer-learning.ipynb) 5 | 6 | In Google Colab ist dieses Notebook unter 7 | [diesem Link](https://colab.research.google.com/github/into-ai/deeplearning2020/blob/master/woche4/notebooks/transfer-learning/transfer-learning.ipynb) erreichbar. 8 | --------------------------------------------------------------------------------