






























Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!































TensorFlow vs Keras: Quick Comparison Table Aspect TensorFlow Keras Core Identity End-to-end machine learning platform/framework High-level neural networks API (interface) Development Created by Google Brain team (2015) Created by François Chollet (2015), now part of TensorFlow Abstraction Level Low-level + high-level (complete stack) Purely high-level abstraction layer Primary Purpose Build, train, deploy production ML systems Fast prototyping and experimentation Learning Curve Steeper (requires understanding of computational graphs) Gentle & intuitive (beginner-friendly) Flexibility Highly flexible - customize everything Less flexible but easier for standard tasks Code Required More verbose code Minimal, concise code Backend Self-contained framework (no external backend) Can run on multiple backends (TF, Theano, CNTK) Built-in Datasets Limited Extensive collection included Debugging More complex (graph-based debugging) Simpler (Pythonic debugging) Production Deployment Excellent (Serving, Lite, JS, Extended) Primarily for prototyping (not deployment) Performance Control Granular control over optimization Automatic optimization (less control) Current Status Complete ecosystem with tf.keras as default API Largely integrated as tf.keras within TensorFlow Best For Production systems, custom algorithms, research Learning, rapid prototyping, standard models Analogy Car manufacturing plant (build everything) Car's dashboard (user-friendly interface) Key Relationship Evolution: Period Relationship Status 2015-2017 Separate entities; Keras could use TensorFlow as backend 2017-2019 Keras integrated into TensorFlow as tf.keras
2019-Present TensorFlow 2.x uses Keras as official high-level API Today tf.keras = Recommended approach; standalone Keras for backend flexibility Quick Decision Guide: Choose TensorFlow (with tf.keras) when: Building production systems Need custom operations/layers Require mobile/browser deployment Working with distributed training Choose standalone Keras when: Just starting with deep learning Need backend flexibility (not tied to TF) Rapid prototyping only Working with standard architectures For most users today: Use tf.keras within TensorFlow 2.x - it provides the best of both worlds.
5. Layers (tf.keras.layers) Pre-built neural network components (Dense, Conv2D, LSTM, Dropout, etc.). Combine operations, activation functions, and parameter handling. Role: Core units for building deep learning models. 6. Models (tf.keras.Model) Two main types: Sequential models (simple stack of layers). Functional/API models (complex DAG architectures). Role: Represent complete neural networks with forward passes. 7. Loss Functions Measure how far predictions deviate from ground truth. Examples: cross-entropy, MSE, hinge loss. Role: Guide optimization. 8. Optimizers Algorithms that update model parameters via gradients. E.g., SGD, Adam, RMSProp. Role: Minimize loss using backpropagation + gradient descent. 9. GradientTape (Automatic Differentiation Engine) TensorFlow’s mechanism to compute derivatives. Records operations and computes gradients automatically. Role: Enables training, custom backpropagation, and optimization. 10. Datasets (tf.data API) Efficient pipeline for loading, batching, shuffling, prefetching data. Supports TFRecord, CSV, image datasets, streaming. Role: High-performance input pipeline for model training/inference.
11. Checkpoints & SavedModel Format Mechanisms to save/restore models and weights. Role: Persistence, deployment, transfer learning. 12. Accelerators (CPU/GPU/TPU Execution) TensorFlow includes: Device placement Automatic parallelization XLA compiler for optimization Role: High-performance execution of tensor computations.
Workload Type CPU Performance
Performance
Performance Single-threaded tasks ✅✅✅ Excellent ✅ Poor ✅ Poor Matrix multiplication ✅ Medium ✅✅✅ Excellent ✅✅✅✅ Best Image processing ✅ Medium ✅✅✅ Excellent ✅✅ Very Good Inference (small batch) ✅ Good ✅✅ Good ✅✅✅ Excellent Training (large batch) ✅ Poor ✅✅✅ Excellent ✅✅✅✅ Best Convolution operations ✅ Poor ✅✅✅ Excellent ✅✅✅ Excellent Natural language tasks ✅ Medium ✅✅ Good ✅✅✅ Excellent DEEP LEARNING SPECIFICS: Deep Learning Aspect
Model Training Small models only Standard choice Large-scale training Model Inference Edge devices, small scale Server inference High-throughput inference Batch Size Small (1-32) Medium-Large (32-
Very Large (1024+) Framework Support All frameworks All frameworks Primarily TensorFlow Memory Bandwidth 50-200 GB/s 400-1000 GB/s 600-1200+ GB/s Energy Efficiency
Development Easy debugging Moderate Specialized
complexity knowledge ARCHITECTURE ANALOGY: Process or Factory Analogy Strengths CPU Skilled artisan workshop Versatility, complex tasks, decision- making GPU Mass production assembly line Repetitive tasks, parallel work, throughput TPU Specialized car manufacturing plant One specific task, optimized pipeline, efficiency CPU: Like a team of 10 PhDs - each brilliant but expensive GPU: Like 1000 high school graduates - massive parallel workforce TPU: Like 100 specialized robots - each perfectly designed for one task PRACTICAL USE CASES: Use Case Recommended Processor Why Web server CPU General-purpose, low latency Video game graphics GPU Parallel pixel rendering Small ML model inference CPU Low cost, sufficient speed Deep learning research GPU Flexibility, framework support Large-scale ML training TPU/GPU Throughput, efficiency Image/video editing GPU Parallel pixel processing Scientific simulations GPU/CPU Parallel computation Autonomous vehicles GPU/TPU Real-time tensor operations Mobile devices CPU/Neural Engine Power efficiency Cloud AI services TPU/GPU Cost efficiency at scale
Technical Detail CPU GPU TPU shaders instructions ML WORKFLOW RECOMMENDATIONS:
Low latency needed Small-scale ML Budget constraints Choose GPU when: Deep learning training/research Graphics rendering Multi-framework support needed General parallel computing Choose TPU when: Large-scale TensorFlow workloads Maximum throughput needed Cost efficiency at scale Google Cloud ecosystem
Defines a seed value (here, 42). The specific number doesn’t matter—any integer works. It ensures that all random operations produce the same results every time the code is run.
3. np.random.seed (SEED) Sets the seed for NumPy’s random number generator. NumPy randomness is used in: dataset preparation generating synthetic data initializing arrays certain preprocessing operations Setting the seed ensures NumPy produces the same sequence of random values each run. 4. tf.random.set_seed(SEED) Sets the seed for TensorFlow’s random operations. TensorFlow randomness influences: weight initialization of neural network layers dropout masks random shuffling in tf.data pipelines random augmentations (if using TF functions) This ensures that a deep neural network starts with the same initial weights every time, enabling identical training behaviour for reproducibility. 5. random.seed(SEED) Sets the seed for Python's built-in random module. Common use cases: random train–test splits (if using Python random) randomly selecting samples simulating stochastic behavior in loops or conditions
Why This Matters in Deep Learning Deep neural networks involve many components that are inherently random. Examples: ✔ Weight initialization Different initial weights → different model convergence paths. ✔ Dropout Creates random masking of neurons during training. ✔ Data shuffling Affects training order and gradient updates. ✔ Data augmentation Random rotations, flips, crops. Setting the seed ensures: reproducible training curves reproducible accuracy values reproducible model weights easier debugging and comparison of architectures In Summary The code ensures that NumPy , TensorFlow , and Python's random module all use the same, fixed randomness seed. This makes your entire deep-learning experiment deterministic , so running the code multiple times yields identical and repeatable results , which is critical for: research publications debugging comparing models fairly controlled experiments
random shuffling data augmentation These random processes can lead to different results each run. What setting a SEED does A SEED ensures that all random operations generate the same sequence of random numbers every time you run the code. Why SEED matters ✔ Ensures reproducibility ✔ Makes experiments consistent for research ✔ Helps debugging by eliminating randomness ✔ Enables fair comparison of models In Summary Conce pt Meaning Why Important Dropo ut Randomly disables neurons during training Prevents overfitting, improves generalization SEED Fixed number controlling random behavior Ensures reproducible, repeatable results
Topic-4 – “Batch Size”: Batch Size in Deep Neural Networks - Core Concept Batch size is the number of training examples processed together before the model updates its internal weights. It represents a fundamental trade-off between computational efficiency and learning quality. The Three Approaches Batch Gradient Descent : Uses the entire dataset for each update - accurate but slow Stochastic Gradient Descent : Updates after each single example - fast but noisy Mini-Batch Gradient Descent : Processes small groups (typically 32- examples) - the balanced standard approach Key Effects and Trade-offs Small Batch Sizes (e.g., 32): Better generalization (acts as implicit regularization) Noisier weight updates but more exploration Lower GPU utilization Slower convergence per epoch Large Batch Sizes (e.g., 256+): Smoother, more accurate gradient estimates Faster convergence per epoch Risk of overfitting (less regularization) Better GPU parallelization Higher memory requirements Practical Considerations Generalization Paradox : Smaller batches often lead to better performance on new data despite noisier training Learning Rate Relationship : Larger batches require smaller learning rates, and vice versa Memory Constraints : Maximum batch size is limited by available GPU/TPU memory Default Starting Point : 32 is the recommended default for most applications
Topic-5 – “Mutually exclusive classes ”:
1. Mutually Exclusive Classes Definition Classes are mutually exclusive if each instance belongs to exactly one class. A sample cannot belong to more than one class simultaneously. Characteristics Typical setup for softmax output layers in neural networks. Uses categorical cross-entropy loss. Examples 1. Digit recognition: o Input: an image of a handwritten digit (0–9) o Classes: 10 digits o Each image can only be one digit → mutually exclusive 2. Animal classification: o Input: an image o Classes: cat, dog, horse o An image is labeled as one animal only → mutually exclusive 3. Traffic light detection: o Classes: red, yellow, green o Each light can only be one color at a time → mutually exclusive 2. Non-Mutually Exclusive Classes (Multi-label Classification) Definition Classes are not mutually exclusive if each instance can belong to multiple classes simultaneously. This is sometimes called multi-label classification. Characteristics Uses sigmoid activation per class instead of softmax. Typically uses binary cross-entropy per class.
Examples