Skip to content

Commit 74894e9

Browse files
authored
Merge pull request #175 from codeharborhub/dev-1
more content added...
2 parents ab520d9 + 299b824 commit 74894e9

File tree

7 files changed

+401
-52
lines changed

7 files changed

+401
-52
lines changed
Lines changed: 121 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,121 @@
1+
---
2+
title: "Keras: Deep Learning for Humans"
3+
sidebar_label: Keras
4+
description: "Understanding the high-level API that makes building neural networks as easy as stacking LEGO blocks."
5+
tags: [deep-learning, keras, tensorflow, neural-networks, api, python]
6+
---
7+
8+
**Keras** is an open-source deep learning library written in Python. It was designed by François Chollet with a simple mission: **to enable fast experimentation.** Being able to go from idea to result with the least possible delay is key to doing good research.
9+
10+
Since the release of TensorFlow 2.0, Keras has become the official high-level API for TensorFlow, providing a polished, user-friendly interface for the powerful engine beneath.
11+
12+
## 1. The Design Philosophy
13+
14+
Keras is built on four core principles:
15+
1. **User Friendliness:** It provides consistent and simple APIs that minimize the number of user actions required for common use cases.
16+
2. **Modularity:** A model is understood as a sequence or a graph of standalone, fully configurable modules (layers, loss functions, optimizers).
17+
3. **Easy Extensibility:** New modules are easy to add as new classes and functions.
18+
4. **Work with Python:** Keras models are defined in Python code, which is compact, easy to debug, and easy to extend.
19+
20+
## 2. Three Ways to Build Models
21+
22+
Keras offers three different APIs to balance ease of use with flexibility:
23+
24+
### A. The Sequential API
25+
The simplest way to build a model. You literally "stack" layers one on top of the other. It is perfect for $90\%$ of use cases where you have one input and one output.
26+
27+
```python title="Building a Sequential Model"
28+
from tensorflow.keras import Sequential
29+
from tensorflow.keras.layers import Dense
30+
31+
model = Sequential([
32+
Dense(64, activation='relu', input_shape=(20,)),
33+
Dense(10, activation='softmax')
34+
])
35+
36+
```
37+
38+
### B. The Functional API
39+
40+
Used for more complex models. It allows you to build graphs of layers with multiple inputs, multiple outputs, or shared layers. It treats layers as functions.
41+
42+
```python title="Building a Functional Model"
43+
from tensorflow.keras import Input, Model
44+
from tensorflow.keras.layers import Dense
45+
inputs = Input(shape=(20,))
46+
x = Dense(64, activation='relu')(inputs)
47+
outputs = Dense(10, activation='softmax')(x)
48+
model = Model(inputs=inputs, outputs=outputs)
49+
```
50+
51+
### C. Model Subclassing
52+
53+
The "pro" way. You define everything from scratch by subclassing the `Model` class. This gives you total control over the forward pass, which is essential for custom research or complex dynamic networks.
54+
55+
```python title="Building a Subclassed Model"
56+
from tensorflow.keras import Model
57+
from tensorflow.keras.layers import Dense
58+
class MyModel(Model):
59+
def __init__(self):
60+
super(MyModel, self).__init__()
61+
self.dense1 = Dense(64, activation='relu')
62+
self.dense2 = Dense(10, activation='softmax')
63+
64+
def call(self, inputs):
65+
x = self.dense1(inputs)
66+
return self.dense2(x)
67+
model = MyModel()
68+
```
69+
70+
## 3. The Keras Workflow
71+
72+
Building and training a model in Keras always follows this 5-step lifecycle:
73+
74+
1. **Define:** Specify the layers and architecture.
75+
2. **Compile:** Choose an **Optimizer** (e.g., Adam), a **Loss Function** (e.g., MSE), and **Metrics** (e.g., Accuracy).
76+
3. **Fit:** Train the model on your data.
77+
4. **Evaluate:** Check how the model performs on unseen data.
78+
5. **Predict:** Use the model to generate outputs for new samples.
79+
80+
```python title="Keras Workflow Example"
81+
# The 'Compile' step is where the math meets the code
82+
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
83+
84+
# The 'Fit' step starts the training loop
85+
model.fit(X_train, y_train, epochs=10, batch_size=32)
86+
87+
```
88+
89+
## 4. Key Components: Layers & Callbacks
90+
91+
### Common Layers:
92+
93+
* `Dense`: Standard fully connected layer.
94+
* `Conv2D`: Used for image processing (Computer Vision).
95+
* `LSTM` / `GRU`: Used for sequence data (NLP).
96+
* `Dropout`: A regularization technique to prevent overfitting by randomly "killing" neurons during training.
97+
98+
### Callbacks:
99+
100+
Callbacks are tools that perform actions at various stages of training, such as:
101+
102+
* **EarlyStopping:** Stop training when the model stops improving.
103+
* **ModelCheckpoint:** Save the "best" version of your model automatically.
104+
105+
## 5. Pros and Cons
106+
107+
| Advantages | Disadvantages |
108+
| --- | --- |
109+
| **Simplicity:** The most beginner-friendly library in the ecosystem. | **Lower-level Control:** It can be harder to implement highly experimental, custom logic compared to PyTorch. |
110+
| **Speed of Prototyping:** Build a working CNN in under 20 lines of code. | **Opaque Errors:** Because it is high-level, stack traces can sometimes be harder to interpret. |
111+
| **Large Community:** Thousands of tutorials and pre-trained models. | **Performance:** Occasionally slightly slower than raw TensorFlow code due to the abstraction layer. |
112+
113+
## References
114+
115+
* **Official Keras Site:** [keras.io](https://keras.io/)
116+
* **Book:** *Deep Learning with Python* by François Chollet.
117+
* **Guide:** [The Functional API vs Sequential API](https://www.tensorflow.org/guide/keras/functional)
118+
119+
---
120+
121+
**Keras makes building models easy. But what if you want more "Pythonic" control and dynamic computation graphs?** Check out our guide on [PyTorch](./pytorch)!
Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
---
2+
title: "PyTorch: The Researcher's Powerhouse"
3+
sidebar_label: PyTorch
4+
description: "Exploring Facebook's PyTorch library, dynamic computational graphs, and its Pythonic approach to deep learning."
5+
tags: [deep-learning, pytorch, facebook, meta, neural-networks, research]
6+
---
7+
8+
**PyTorch**, developed by Meta's (Facebook) AI Research lab (FAIR), is an open-source machine learning library based on the Torch library. Since its release, it has overtaken other frameworks in the research community due to its **Dynamic Computational Graphs** and its seamless integration with the Python ecosystem.
9+
10+
## 1. The Core Philosophy: "Pythonic" Design
11+
12+
Unlike other frameworks that feel like a separate language ported into Python, PyTorch feels like **native Python**.
13+
* If you know how to use NumPy, you already know 80% of PyTorch.
14+
* It uses standard Python debugging tools (like `pdb` or print statements).
15+
* It follows Object-Oriented Programming (OOP) principles strictly.
16+
17+
## 2. Dynamic vs. Static Graphs
18+
19+
The defining feature of PyTorch is the **Dynamic Computational Graph** (also known as *Define-by-Run*).
20+
21+
* **Static Graphs (Old TensorFlow):** You build a roadmap, then send cars (data) through it. You cannot change the road once the cars are moving.
22+
* **Dynamic Graphs (PyTorch):** The roadmap is built as the car moves. You can change the network's behavior on the fly based on the data it receives.
23+
24+
This makes PyTorch exceptionally good for **Natural Language Processing (NLP)**, where sentences have different lengths and require flexible architectures.
25+
26+
## 3. The Building Blocks: Tensors and Autograd
27+
28+
### Tensors
29+
30+
The fundamental unit in PyTorch is the `torch.Tensor`. It is essentially an n-dimensional array that can be moved to a **GPU** with a single line of code (`.to('cuda')`) for massive speedups.
31+
32+
### Autograd
33+
34+
PyTorch’s `autograd` engine automatically calculates derivatives (gradients). When you perform operations on tensors, PyTorch remembers the "math history" and can automatically apply the **Chain Rule** to find gradients during backpropagation.
35+
36+
$$
37+
\text{loss.backward()} \rightarrow \text{Automatically calculates } \frac{\partial Loss}{\partial w}
38+
$$
39+
40+
## 4. Building a Model in PyTorch
41+
42+
In PyTorch, you define a model by creating a class that inherits from `nn.Module`.
43+
44+
```python
45+
import torch
46+
import torch.nn as nn
47+
48+
class SimpleNet(nn.Module):
49+
def __init__(self):
50+
super(SimpleNet, self).__init__()
51+
# Define the layers
52+
self.hidden = nn.Linear(10, 32)
53+
self.output = nn.Linear(32, 1)
54+
self.relu = nn.ReLU()
55+
self.sigmoid = nn.Sigmoid()
56+
57+
def forward(self, x):
58+
# Define the flow of data
59+
x = self.relu(self.hidden(x))
60+
x = self.sigmoid(self.output(x))
61+
return x
62+
63+
model = SimpleNet()
64+
65+
```
66+
67+
## 5. The PyTorch Ecosystem
68+
69+
PyTorch isn't just for building models; it has a rich set of libraries for specific domains:
70+
71+
| Library | Domain | Key Features |
72+
| --- | --- | --- |
73+
| **TorchVision** | Computer Vision | Pre-trained models (ResNet, VGG), image transforms. |
74+
| **TorchText** | NLP | Data loaders for text, tokenization tools. |
75+
| **TorchAudio** | Audio | Signal processing and audio data manipulation. |
76+
| **PyTorch Lightning** | Boilerplate | A high-level wrapper that organizes PyTorch code for better readability. |
77+
78+
## 6. Pros and Cons
79+
80+
| Advantages | Disadvantages |
81+
| --- | --- |
82+
| **Debuggability:** Error messages are clear and standard Python debuggers work. | **Deployment:** Historically, it was harder to put into production than TensorFlow (though this is changing with TorchScript). |
83+
| **Community:** Most modern AI research papers are published with PyTorch code. | **Verbosity:** You have to write your own training loops (manual control). |
84+
| **Flexibility:** Easiest library for building custom, complex architectures. | **Mobile:** Smaller ecosystem for mobile/edge deployment compared to TF Lite. |
85+
86+
## References
87+
88+
* **PyTorch Tutorials:** [Welcome to PyTorch Tutorials](https://pytorch.org/tutorials/)
89+
* **Deep Learning with PyTorch:** [Free e-book by Eli Stevens](https://pytorch.org/assets/deep-learning/Deep-Learning-with-PyTorch.pdf)
90+
91+
---
92+
93+
**PyTorch gives you total control over your training loop. But how do you handle data that doesn't fit into a standard table, like images?**
Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
---
2+
title: "TensorFlow: Production-Grade Deep Learning Library"
3+
sidebar_label: TensorFlow
4+
description: "An introduction to Google's TensorFlow ecosystem, Keras API, and the dataflow graph architecture."
5+
tags: [deep-learning, tensorflow, keras, google, neural-networks, production]
6+
---
7+
8+
**TensorFlow**, developed by the Google Brain team, is one of the most popular open-source libraries for high-performance numerical computation and machine learning. Its name comes from **Tensors** (multi-dimensional arrays) and the **Flow** of data through a computational graph.
9+
10+
## 1. The Core Concept: Tensors
11+
12+
In TensorFlow, all data is represented as a **Tensor**.
13+
* **Scalar:** Rank 0 (a single number)
14+
* **Vector:** Rank 1 (a list of numbers)
15+
* **Matrix:** Rank 2 (a table of numbers)
16+
* **n-Tensor:** Rank n (multi-dimensional arrays)
17+
18+
Tensors flow through a **computational graph**, where nodes represent operations (like addition or multiplication) and edges represent the tensors being passed between them. This graph-based approach allows TensorFlow to optimize computations for performance and scalability, making it suitable for both research and production environments.
19+
20+
## 2. Evolution: TensorFlow 1.x vs. 2.x
21+
22+
One of the biggest shifts in the library's history was the move to version 2.0.
23+
24+
* **TF 1.x (Static Graphs):** You had to define the entire architecture (the "Graph") before running any data through it using a `Session`. It was powerful but notoriously difficult to debug.
25+
* **TF 2.x (Eager Execution):** TensorFlow now runs operations immediately, just like standard Python code. It also fully integrated **Keras** as the official high-level API, making it much more user-friendly.
26+
27+
This change made TensorFlow more accessible to beginners while retaining its powerful capabilities for advanced users.
28+
29+
## 3. The TensorFlow Ecosystem
30+
31+
What sets TensorFlow apart is that it isn't just a library; it's a full production ecosystem:
32+
33+
| Component | Purpose |
34+
| :--- | :--- |
35+
| **TensorFlow Core** | The base engine for building and training models. |
36+
| **Keras** | The high-level API for rapid prototyping (Human-centric). |
37+
| **TF Hub** | A repository of pre-trained models for Transfer Learning. |
38+
| **TensorBoard** | A suite of visualization tools to track training progress and graphs. |
39+
| **TF Lite** | Optimized for mobile and IoT devices. |
40+
| **TF Serving** | For deploying models in production environments via APIs. |
41+
42+
## 4. Building Your First Model (Keras API)
43+
44+
The `Sequential` API is the easiest way to stack layers in TensorFlow.
45+
46+
```python
47+
import tensorflow as tf
48+
from tensorflow.keras import layers
49+
50+
# 1. Define the architecture
51+
model = tf.keras.Sequential([
52+
layers.Dense(64, activation='relu', input_shape=(10,)),
53+
layers.Dense(32, activation='relu'),
54+
layers.Dense(1, activation='sigmoid') # Binary output
55+
])
56+
57+
# 2. Compile the model
58+
model.compile(
59+
optimizer='adam',
60+
loss='binary_crossentropy',
61+
metrics=['accuracy']
62+
)
63+
64+
# 3. View the structure
65+
model.summary()
66+
67+
```
68+
69+
## 5. Visualization with TensorBoard
70+
71+
TensorBoard is TensorFlow's "secret weapon." It allows you to visualize your loss curves, layer distributions, and even the computational graph in real-time through a web browser.
72+
73+
```python
74+
# To use it, simply add a callback during training:
75+
tensorboard_callback = tf.keras.callbacks.TensorBoard(log_dir="./logs")
76+
77+
model.fit(x_train, y_train, epochs=5, callbacks=[tensorboard_callback])
78+
79+
```
80+
81+
## 6. Pros and Cons
82+
83+
| Advantages | Disadvantages |
84+
| --- | --- |
85+
| **Scalability:** Built to run on everything from mobile phones to massive TPU clusters. | **Steep Learning Curve:** Even with TF 2.x, the lower-level API can be complex. |
86+
| **Deployment:** Best-in-class tools for putting models into production. | **API Fragmentation:** Older tutorials for 1.x are incompatible with 2.x, which can be confusing. |
87+
| **Community:** Massive support and extensive pre-trained models. | **Heavyweight:** Larger library size compared to PyTorch. |
88+
89+
## References
90+
91+
* **TensorFlow Official:** [Install and Get Started](https://www.tensorflow.org/install)
92+
* **Keras Documentation:** [Simple. Flexible. Powerful.](https://keras.io/)
93+
94+
---
95+
96+
**TensorFlow is a powerhouse for production. But many researchers prefer a more "Pythonic" and flexible approach.** If you're looking for that, check out our guide on [PyTorch](./pytorch)!

0 commit comments

Comments
 (0)