1
---
2
name: Neural Network Design
3
description: Design and architect neural networks with various architectures including CNNs, RNNs, Transformers, and attention mechanisms using PyTorch and TensorFlow
4
---
5
6
# Neural Network Design
7
8
## Overview
9
10
This skill covers designing and implementing neural network architectures including CNNs, RNNs, Transformers, and ResNets using PyTorch and TensorFlow, with focus on architecture selection, layer composition, and optimization techniques.
11
12
## When to Use
13
14
- Designing custom neural network architectures for computer vision tasks like image classification or object detection
15
- Building sequence models for time series forecasting, natural language processing, or video analysis
16
- Implementing transformer-based models for language understanding or generation tasks
17
- Creating hybrid architectures that combine CNNs, RNNs, and attention mechanisms
18
- Optimizing network depth, width, and skip connections for better training and performance
19
- Selecting appropriate activation functions, normalization layers, and regularization techniques
20
21
## Core Architecture Types
22
23
- **Feedforward Networks (MLPs)**: Fully connected layers
24
- **Convolutional Networks (CNNs)**: Image processing
25
- **Recurrent Networks (RNNs, LSTMs, GRUs)**: Sequence processing
26
- **Transformers**: Self-attention based architecture
27
- **Hybrid Models**: Combining multiple architecture types
28
29
## Network Design Principles
30
31
- **Depth vs Width**: Trade-offs between layers and units
32
- **Skip Connections**: Residual networks for deeper training
33
- **Normalization**: Batch norm, layer norm for stability
34
- **Regularization**: Dropout, L1/L2 preventing overfitting
35
- **Activation Functions**: ReLU, GELU, Swish for non-linearity
36
37
## PyTorch and TensorFlow Implementation
38
39
```python
40
import torch
41
import torch.nn as nn
42
import tensorflow as tf
43
from tensorflow import keras
44
import numpy as np
45
import matplotlib.pyplot as plt
46
47
# 1. Feedforward Neural Network (MLP)
48
print("=== 1. Feedforward Neural Network ===")
49
50
class MLPPyTorch(nn.Module):
51
def __init__(self, input_size, hidden_sizes, output_size):
52
super().__init__()
53
layers = []
54
prev_size = input_size
55
56
for hidden_size in hidden_sizes:
57
layers.append(nn.Linear(prev_size, hidden_size))
58
layers.append(nn.BatchNorm1d(hidden_size))
59
layers.append(nn.ReLU())
60
layers.append(nn.Dropout(0.3))
61
prev_size = hidden_size
62
63
layers.append(nn.Linear(prev_size, output_size))
64
self.model = nn.Sequential(*layers)
65
66
def forward(self, x):
67
return self.model(x)
68
69
mlp = MLPPyTorch(input_size=784, hidden_sizes=[512, 256, 128], output_size=10)
70
print(f"MLP Parameters: {sum(p.numel() for p in mlp.parameters()):,}")
71
72
# 2. Convolutional Neural Network (CNN)
73
print("\n=== 2. Convolutional Neural Network ===")
74
75
class CNNPyTorch(nn.Module):
76
def __init__(self):
77
super().__init__()
78
# Conv blocks
79
self.conv1 = nn.Conv2d(3, 32, kernel_size=3, padding=1)
80
self.bn1 = nn.BatchNorm2d(32)
81
self.pool1 = nn.MaxPool2d(2, 2)
82
83
self.conv2 = nn.Conv2d(32, 64, kernel_size=3, padding=1)
84
self.bn2 = nn.BatchNorm2d(64)
85
self.pool2 = nn.MaxPool2d(2, 2)
86
87
self.conv3 = nn.Conv2d(64, 128, kernel_size=3, padding=1)
88
self.bn3 = nn.BatchNorm2d(128)
89
self.pool3 = nn.MaxPool2d(2, 2)
90
91
# Fully connected layers
92
self.fc1 = nn.Linear(128 * 4 * 4, 256)
93
self.dropout = nn.Dropout(0.5)
94
self.fc2 = nn.Linear(256, 10)
95
self.relu = nn.ReLU()
96
97
def forward(self, x):
98
x = self.relu(self.bn1(self.conv1(x)))
99
x = self.pool1(x)
100
x = self.relu(self.bn2(self.conv2(x)))
101
x = self.pool2(x)
102
x = self.relu(self.bn3(self.conv3(x)))
103
x = self.pool3(x)
104
x = x.view(x.size(0), -1)
105
x = self.relu(self.fc1(x))
106
x = self.dropout(x)
107
x = self.fc2(x)
108
return x
109
110
cnn = CNNPyTorch()
111
print(f"CNN Parameters: {sum(p.numel() for p in cnn.parameters()):,}")
112
113
# 3. Recurrent Neural Network (LSTM)
114
print("\n=== 3. LSTM Network ===")
115
116
class LSTMPyTorch(nn.Module):
117
def __init__(self, input_size, hidden_size, num_layers, output_size):
118
super().__init__()
119
self.lstm = nn.LSTM(input_size, hidden_size, num_layers,
120
batch_first=True, dropout=0.3)
121
self.fc = nn.Linear(hidden_size, output_size)
122
123
def forward(self, x):
124
lstm_out, (h_n, c_n) = self.lstm(x)
125
last_hidden = h_n[-1]
126
output = self.fc(last_hidden)
127
return output
128
129
lstm = LSTMPyTorch(input_size=100, hidden_size=128, num_layers=2, output_size=10)
130
print(f"LSTM Parameters: {sum(p.numel() for p in lstm.parameters()):,}")
131
132
# 4. Transformer Block
133
print("\n=== 4. Transformer Architecture ===")
134
135
class TransformerBlock(nn.Module):
136
def __init__(self, d_model, num_heads, d_ff, dropout=0.1):
137
super().__init__()
138
self.attention = nn.MultiheadAttention(d_model, num_heads, dropout=dropout)
139
self.norm1 = nn.LayerNorm(d_model)
140
self.norm2 = nn.LayerNorm(d_model)
141
142
self.feedforward = nn.Sequential(
143
nn.Linear(d_model, d_ff),
144
nn.ReLU(),
145
nn.Dropout(dropout),
146
nn.Linear(d_ff, d_model),
147
nn.Dropout(dropout)
148
)
149
150
def forward(self, x):
151
# Self-attention
152
attn_out, _ = self.attention(x, x, x)
153
x = self.norm1(x + attn_out)
154
155
# Feedforward
156
ff_out = self.feedforward(x)
157
x = self.norm2(x + ff_out)
158
return x
159
160
class TransformerPyTorch(nn.Module):
161
def __init__(self, vocab_size, d_model, num_heads, num_layers, d_ff):
162
super().__init__()
163
self.embedding = nn.Embedding(vocab_size, d_model)
164
self.transformer_blocks = nn.ModuleList([
165
TransformerBlock(d_model, num_heads, d_ff)
166
for _ in range(num_layers)
167
])
168
self.fc = nn.Linear(d_model, 10)
169
170
def forward(self, x):
171
x = self.embedding(x)
172
for block in self.transformer_blocks:
173
x = block(x)
174
x = x.mean(dim=1) # Global average pooling
175
x = self.fc(x)
176
return x
177
178
transformer = TransformerPyTorch(vocab_size=1000, d_model=256, num_heads=8,
179
num_layers=3, d_ff=512)
180
print(f"Transformer Parameters: {sum(p.numel() for p in transformer.parameters()):,}")
181
182
# 5. Residual Network (ResNet)
183
print("\n=== 5. Residual Network ===")
184
185
class ResidualBlock(nn.Module):
186
def __init__(self, in_channels, out_channels, stride=1):
187
super().__init__()
188
self.conv1 = nn.Conv2d(in_channels, out_channels, 3, stride=stride, padding=1)
189
self.bn1 = nn.BatchNorm2d(out_channels)
190
self.conv2 = nn.Conv2d(out_channels, out_channels, 3, padding=1)
191
self.bn2 = nn.BatchNorm2d(out_channels)
192
self.relu = nn.ReLU()
193
194
self.shortcut = nn.Sequential()
195
if stride != 1 or in_channels != out_channels:
196
self.shortcut = nn.Sequential(
197
nn.Conv2d(in_channels, out_channels, 1, stride=stride),
198
nn.BatchNorm2d(out_channels)
199
)
200
201
def forward(self, x):
202
residual = self.shortcut(x)
203
out = self.relu(self.bn1(self.conv1(x)))
204
out = self.bn2(self.conv2(out))
205
out += residual
206
out = self.relu(out)
207
return out
208
209
class ResNetPyTorch(nn.Module):
210
def __init__(self):
211
super().__init__()
212
self.conv1 = nn.Conv2d(3, 64, 7, stride=2, padding=3)
213
self.bn1 = nn.BatchNorm2d(64)
214
self.maxpool = nn.MaxPool2d(3, stride=2, padding=1)
215
216
self.layer1 = self._make_layer(64, 64, 3, stride=1)
217
self.layer2 = self._make_layer(64, 128, 4, stride=2)
218
self.layer3 = self._make_layer(128, 256, 6, stride=2)
219
self.layer4 = self._make_layer(256, 512, 3, stride=2)
220
221
self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
222
self.fc = nn.Linear(512, 10)
223
224
def _make_layer(self, in_channels, out_channels, blocks, stride):
225
layers = [ResidualBlock(in_channels, out_channels, stride)]
226
for _ in range(1, blocks):
227
layers.append(ResidualBlock(out_channels, out_channels))
228
return nn.Sequential(*layers)
229
230
def forward(self, x):
231
x = self.maxpool(self.bn1(self.conv1(x)))
232
x = self.layer1(x)
233
x = self.layer2(x)
234
x = self.layer3(x)
235
x = self.layer4(x)
236
x = self.avgpool(x)
237
x = x.view(x.size(0), -1)
238
x = self.fc(x)
239
return x
240
241
resnet = ResNetPyTorch()
242
print(f"ResNet Parameters: {sum(p.numel() for p in resnet.parameters()):,}")
243
244
# 6. TensorFlow Keras model with custom layers
245
print("\n=== 6. TensorFlow Keras Model ===")
246
247
tf_model = keras.Sequential([
248
keras.layers.Conv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 3)),
249
keras.layers.BatchNormalization(),
250
keras.layers.MaxPooling2D((2, 2)),
251
252
keras.layers.Conv2D(64, (3, 3), activation='relu'),
253
keras.layers.BatchNormalization(),
254
keras.layers.MaxPooling2D((2, 2)),
255
256
keras.layers.Conv2D(128, (3, 3), activation='relu'),
257
keras.layers.BatchNormalization(),
258
keras.layers.GlobalAveragePooling2D(),
259
260
keras.layers.Dense(256, activation='relu'),
261
keras.layers.Dropout(0.5),
262
keras.layers.Dense(10, activation='softmax')
263
])
264
265
print(f"TensorFlow Model Parameters: {tf_model.count_params():,}")
266
tf_model.summary()
267
268
# 7. Model comparison
269
models_info = {
270
'MLP': mlp,
271
'CNN': cnn,
272
'LSTM': lstm,
273
'Transformer': transformer,
274
'ResNet': resnet,
275
}
276
277
param_counts = {name: sum(p.numel() for p in model.parameters())
278
for name, model in models_info.items()}
279
280
fig, axes = plt.subplots(1, 2, figsize=(14, 5))
281
282
# Parameter counts
283
axes[0].barh(list(param_counts.keys()), list(param_counts.values()), color='steelblue')
284
axes[0].set_xlabel('Number of Parameters')
285
axes[0].set_title('Model Complexity Comparison')
286
axes[0].set_xscale('log')
287
288
# Architecture comparison table
289
architectures = {
290
'MLP': 'Feedforward, Dense layers',
291
'CNN': 'Conv layers, Pooling',
292
'LSTM': 'Recurrent, Long-term memory',
293
'Transformer': 'Self-attention, Parallel processing',
294
'ResNet': 'Residual connections, Skip paths'
295
}
296
297
y_pos = np.arange(len(architectures))
298
axes[1].axis('off')
299
table_data = [[name, architectures[name]] for name in architectures.keys()]
300
table = axes[1].table(cellText=table_data, colLabels=['Model', 'Architecture'],
301
cellLoc='left', loc='center', bbox=[0, 0, 1, 1])
302
table.auto_set_font_size(False)
303
table.set_fontsize(9)
304
table.scale(1, 2)
305
306
plt.tight_layout()
307
plt.savefig('neural_network_architectures.png', dpi=100, bbox_inches='tight')
308
print("\nVisualization saved as 'neural_network_architectures.png'")
309
310
print("\nNeural network design analysis complete!")
311
```
312
313
## Architecture Selection Guide
314
315
- **MLP**: Tabular data, simple classification
316
- **CNN**: Image classification, object detection
317
- **LSTM/GRU**: Time series, sequential data
318
- **Transformer**: NLP, long-range dependencies
319
- **ResNet**: Very deep networks, image tasks
320
321
## Key Design Considerations
322
323
- Input/output shape compatibility
324
- Receptive field size for CNNs
325
- Sequence length for RNNs
326
- Attention head count for Transformers
327
- Skip connection placement for ResNets
328
329
## Deliverables
330
331
- Network architecture definition
332
- Parameter count analysis
333
- Layer-by-layer description
334
- Data flow diagrams
335
- Performance benchmarks
336
- Deployment requirements
337