Docsity

computer security principles and practice global edition, Lecture notes of Computer Communication Systems

Toggle sidebar
bg1
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
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26

Partial preview of the text

Download computer security principles and practice global edition and more Lecture notes Computer Communication Systems in PDF only on Docsity!

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 systemsNeed custom operations/layersRequire mobile/browser deploymentWorking with distributed training Choose standalone Keras when:Just starting with deep learningNeed backend flexibility (not tied to TF)Rapid prototyping onlyWorking 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.

PERFORMANCE CHARACTERISTICS:

Workload Type CPU Performance

GPU

Performance

TPU

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

CPU GPU TPU

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

5-50 TFLOPS/W 10-100 TFLOPS/W 100-300+

TFLOPS/W

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:

  1. Development & Prototyping: CPU (local), GPU (cloud for larger models)
  2. Training: o Small models: High-end GPU o Large models: Multi-GPU or TPU pods
  3. Inference: o Edge devices: CPU or mobile GPU o Cloud services: GPU or TPU for high throughput
  4. Production Scale: TPU for Google ecosystem, GPU for multi-framework FUTURE TRENDS: Trend CPU GPU TPU AI Integration Adding ML accelerators (AMX, AVX-512) Tensor cores (NVIDIA) Continued specialization Market Share Universal presence Dominating ML training Growing in cloud ML Specializati on General-purpose + AI acceleration Gaming + AI + HPC Pure ML optimization Edge Computing CPU + NPU combos Mobile GPUs + tensor cores Edge TPU deployment BOTTOM LINE: Choose CPU when:  General-purpose computing

 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 ApproachesBatch 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 ConsiderationsGeneralization 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

  1. Movie genres: o Input: a movie o Classes: Action, Comedy, Drama, Sci-Fi o A movie can be both Action and Sci-Fi → not mutually exclusive
  2. Medical diagnosis: o Input: patient data or X-ray image o Classes: pneumonia, asthma, bronchitis o A patient may have more than one condition → not mutually exclusive
  3. Object detection in images: o Classes: person, car, bicycle, dog o One image can contain multiple objects → not mutually exclusive Key Differences Aspect Mutually Exclusive Non-Mutually Exclusive Label per instance Exactly 1 0 or more Output activation Softmax Sigmoid (per class) Loss function Categorical cross- entropy Binary cross-entropy Example Digit recognition Multi-genre movies SummaryMulti-class classification is usually mutually exclusive if the problem requires exactly one label per instance.  If instances can belong to multiple classes , it becomes multi-label classification , where classes are not mutually exclusive.