DeepLearning
Erstelle, trainiere und optimiere neuronale Netzwerke mit TensorFlow und Keras. Von grundlegenden Konzepten bis zu fortgeschrittenen Architekturen.
🎯 Intermediate Level
25 min Lesezeit
💻 Hands-On
Mit TensorFlow Code
⚡ Deep Learning Quick Tips
GPU verwenden
Training um 10x beschleunigen
Batch Normalization
Stabileres Training
Early Stopping
Overfitting vermeiden
TensorBoard
Training visualisieren
🧠 Was ist Deep Learning?
Deep Learning ist ein Teilbereich des Machine Learning, der von der Struktur und Funktion des menschlichen Gehirns inspiriert ist. Es verwendet künstliche neuronale Netzwerke mit mehreren Schichten (daher "deep"), um komplexe Muster in großen Datenmengen zu erkennen.
✅ Vorteile von Deep Learning
- • Automatische Feature-Extraktion
- - Excellent performance with large data sets
- • Vielseitig einsetzbar (Bild, Text, Audio)
- • State-of-the-art Ergebnisse
- • Kontinuierliche Verbesserung
⚠️ Herausforderungen
- - Requires large amounts of data
- • Hoher Rechenaufwand (GPU erforderlich)
- • "Black Box" - schwer interpretierbar
- - Overfitting for small data records
- • Hyperparameter-Tuning komplex
🎯 Hauptanwendungsbereiche
Computer Vision
Bilderkennung, Objekterkennung, medizinische Bildanalyse
Natural Language Processing
Language translation, chatbots, text analysis
Audio Processing
Spracherkennung, Musikgenerierung, Audioanalyse
🔗 Arten von Neuronalen Netzwerken
Feedforward Neural Networks
EinsteigerBasic neural networks for tabular data
MNIST Ziffernerkennung
Hauspreisvorhersage
Klassifikation
Regression
Convolutional Neural Networks (CNN)
MittelEspecially for image processing and Computer Vision
Bilderkennung
Objekterkennung
Medizinische Bildanalyse
Gesichtserkennung
Recurrent Neural Networks (RNN)
FortgeschrittenFor sequential data such as text and time series
Language translation
Zeitserien-Vorhersage
Chatbots
Sentiment-Analyse
⚙️ TensorFlow & Keras Setup
TensorFlow ist Googles Open-Source-Framework für Machine Learning, und Keras ist die benutzerfreundliche High-Level-API, die in TensorFlow integriert ist.
💻 Installation
# CPU Version (für erste Experimente) pip install tensorflow # GPU Version (für ernsthafte Projekte) pip install tensorflow-gpu # Zusätzliche hilfreiche Pakete pip install numpy pandas matplotlib seaborn pip install scikit-learn jupyter notebook # Jupyter Lab für bessere Entwicklungserfahrung pip install jupyterlab
🚀 Erste Schritte Test
import tensorflow as tf import keras import numpy as np # TensorFlow Version prüfen print(f"TensorFlow Version: {tf.__version__}") print(f"Keras Version: {keras.__version__}") # GPU Verfügbarkeit prüfen print(f"GPU available: {tf.config.list_physical_devices('GPU')}") # Einfache Tensor-Operationen a = tf.constant([[1, 2], [3, 4]]) b = tf.constant([[2, 0], [0, 2]]) c = tf.matmul(a, b) print(f"Matrix Multiplikation:\n{c.numpy()}")
💡 Entwicklungsumgebung Tipps
- Google Colab: Free GPU/TPU usage for experiments
- Jupyter Notebooks: Interaktive Entwicklung und Visualisierung
- TensorBoard: Built-in visualization for training metrics
- Keras Tuner: Automatische Hyperparameter-Optimierung
🎯 Erstes Deep Learning Modell
Wir erstellen ein einfaches neuronales Netzwerk für die Klassifikation von handgeschriebenen Ziffern (MNIST-Dataset).
🔢 MNIST Ziffernerkennung
import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers import numpy as np import matplotlib.pyplot as plt # 1. Daten laden und vorbereiten (x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data() # Daten normalisieren (0-1 Bereich) x_train = x_train.astype('float32') / 255.0 x_test = x_test.astype('float32') / 255.0 # Shape prüfen print(f"Training Data: {x_train.shape}") print(f"Training Labels: {y_train.shape}") # 2. Modell definieren model = keras.Sequential([ layers.Flatten(input_shape=(28, 28)), # 28x28 -> 784 layers.Dense(128, activation='relu'), # Hidden Layer 1 layers.Dropout(0.2), # Regularisierung layers.Dense(64, activation='relu'), # Hidden Layer 2 layers.Dense(10, activation='softmax') # Output Layer ]) # 3. Modell kompilieren model.compile( optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'] ) # 4. Modell-Architektur anzeigen model.summary() # 5. Modell trainieren history = model.fit( x_train, y_train, epochs=10, batch_size=32, validation_split=0.2, verbose=1 ) # 6. Modell evaluieren test_loss, test_accuracy = model.evaluate(x_test, y_test, verbose=0) print(f"Test Accuracy: {test_accuracy:.4f}") # 7. Vorhersagen machen predictions = model.predict(x_test[:5]) predicted_classes = np.argmax(predictions, axis=1) print(f"Vorhergesagte Klassen: {predicted_classes}") print(f"Echte Klassen: {y_test[:5]}")
📊 Training visualisieren
# Training-Verlauf plotten plt.figure(figsize=(12, 4)) plt.subplot(1, 2, 1) plt.plot(history.history['accuracy']) plt.plot(history.history['val_accuracy']) plt.title('Model Accuracy') plt.ylabel('Accuracy') plt.xlabel('Epoch') plt.legend(['Train', 'Validation']) plt.subplot(1, 2, 2) plt.plot(history.history['loss']) plt.plot(history.history['val_loss']) plt.title('Model Loss') plt.ylabel('Loss') plt.xlabel('Epoch') plt.legend(['Train', 'Validation']) plt.tight_layout() plt.show()
💾 Modell speichern
# Komplettes Modell speichern model.save('mnist_model.h5') # Nur Gewichte speichern model.save_weights('mnist_weights.h5') # Modell laden loaded_model = keras.models.load_model('mnist_model.h5') # Architektur als JSON model_json = model.to_json() with open("model.json", "w") as json_file: json_file.write(model_json)
🛠️ TensorFlow Ecosystem
TensorFlow & Keras
High-level API for simple model development
Intuitive API
Eager Execution
Auto-Differentiation
Distributed Training
TensorBoard
Visualisierung und Monitoring von Training
Loss Curves
Model Graph
Histogram
Embeddings
TensorFlow Extended (TFX)
End-to-end ML Pipeline for Production
Data Validation
Model Serving
Monitoring
A/B Testing
TensorFlow Lite
Mobile und Edge Device Deployment
Quantization
Pruning
Hardware Optimization
Cross-Platform
👁️ CNN for Computer Vision
Convolutional Neural Networks (CNNs) sind speziell für die Verarbeitung von Bilddaten entwickelt und erzielen hervorragende Ergebnisse in der Computer Vision.
🔍 Convolution Layer
Wendet Filter auf das Bild an, um Features wie Kanten, Texturen zu erkennen.
- - Kernel/filter size
- • Stride (Schrittweite)
- • Padding (Randbehandlung)
📉 Pooling Layer
Reduziert die Größe und macht das Modell robuster gegen kleine Verschiebungen.
- • Max Pooling
- • Average Pooling
- • Global Pooling
🎯 Fully Connected
Klassische Dense Layer für die finale Klassifikation nach Feature-Extraktion.
- • Flatten Layer
- • Dense Layer
- • Dropout
📷 CIFAR-10 Bildklassifikation mit CNN
import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers # 1. CIFAR-10 Daten laden (x_train, y_train), (x_test, y_test) = keras.datasets.cifar10.load_data() # Daten normalisieren x_train = x_train.astype('float32') / 255.0 x_test = x_test.astype('float32') / 255.0 # Labels zu kategorisch y_train = keras.utils.to_categorical(y_train, 10) y_test = keras.utils.to_categorical(y_test, 10) # 2. CNN Modell definieren model = keras.Sequential([ # Erste Convolution Block layers.Conv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 3)), layers.BatchNormalization(), layers.Conv2D(32, (3, 3), activation='relu'), layers.MaxPooling2D((2, 2)), layers.Dropout(0.25), # Zweite Convolution Block layers.Conv2D(64, (3, 3), activation='relu'), layers.BatchNormalization(), layers.Conv2D(64, (3, 3), activation='relu'), layers.MaxPooling2D((2, 2)), layers.Dropout(0.25), # Dritte Convolution Block layers.Conv2D(128, (3, 3), activation='relu'), layers.BatchNormalization(), layers.Dropout(0.25), # Klassifikation layers.Flatten(), layers.Dense(512, activation='relu'), layers.BatchNormalization(), layers.Dropout(0.5), layers.Dense(10, activation='softmax') ]) # 3. Kompilieren mit verbesserter Konfiguration model.compile( optimizer=keras.optimizers.Adam(learning_rate=0.001), loss='categorical_crossentropy', metrics=['accuracy'] ) # 4. Callbacks definieren callbacks = [ keras.callbacks.EarlyStopping(patience=10, restore_best_weights=True), keras.callbacks.ReduceLROnPlateau(factor=0.5, patience=5), keras.callbacks.ModelCheckpoint('best_model.h5', save_best_only=True) ] # 5. Training mit Data Augmentation datagen = keras.preprocessing.image.ImageDataGenerator( rotation_range=15, width_shift_range=0.1, height_shift_range=0.1, horizontal_flip=True, zoom_range=0.1 ) datagen.fit(x_train) # 6. Modell trainieren history = model.fit( datagen.flow(x_train, y_train, batch_size=32), epochs=100, validation_data=(x_test, y_test), callbacks=callbacks, verbose=1 ) # 7. Evaluation test_loss, test_accuracy = model.evaluate(x_test, y_test, verbose=0) print(f"Test Accuracy: {test_accuracy:.4f}")
⚡ Deep Learning Best Practices
🎯 Training Optimierung
- • Batch Normalization: Stabileres Training
- • Dropout: Overfitting verhindern
- • Early Stopping: Automatisches Stoppen
- • Learning Rate Scheduling: Adaptive LR
- • Data Augmentation: Mehr Trainingsdaten
🔧 Architektur Design
- • Start Simple: Dann komplexer werden
- • Residual Connections: Bei tiefen Netzen
- • Transfer Learning: Vortrainierte Modelle
- • Ensemble Methods: Mehrere Modelle kombinieren
- - Model Compression: For Production
⚠️ Avoid common problems
Overfitting
Modell lernt Trainingsdaten auswendig, performt schlecht auf neuen Daten
→ Dropout, Early Stopping, Regularization
Vanishing Gradients
Gradienten werden zu klein in tiefen Netzwerken
→ Batch Norm, ReLU, Residual Connections
🚀 Next steps
📚 Related articles
🛠️ Praktische Tools
💡 Empfohlene Projekt-Pipeline
- 1. Beginnen Sie mit MNIST und einfachen Dense Networks
- 2. Experimentieren Sie mit CNNs auf CIFAR-10
- 3. Probieren Sie Transfer Learning mit vortrainierten Modellen
- 4. Implement RNNs for text classification
- 5. Deployen Sie Ihr erstes Modell in Production