Practice
import numpy as np
def numerical_gradient(f, x):
h = 1e-4
grad = np.zeros_like(x)
for i in range(x.size):
x[i] += h
fxh1 = f(x)
x[i] -= 2 * h
fxh2 = f(x)
grad[i] = (fxh1 - fxh2) / (2 * h)
x[i] += h
return grad
# Test function
f = lambda x: x[0]**2 + x[1]**2
x = np.array([3.0, 4.0])
print(numerical_gradient(f, x))Solution
Step 1: Understand the numerical gradient calculation
The function calculates the gradient using central difference approximation.Step 2: Calculate the gradient for each element
For x = [3.0, 4.0], the gradient is [6.0, 8.0] because the derivative of x^2 is 2x.Final Answer:
Option A -> Option AQuick Check:
Central difference gives exact gradient for quadratic. [OK]
Solution
Step 1: Identify vanishing gradient issue
Vanishing gradients occur when gradients become too small to update weights effectively.Step 2: Correct approach
Gradient clipping prevents gradients from becoming too small or too large.Final Answer:
Option C -> Option CQuick Check:
Clip gradients to prevent vanishing [OK]
import torch
import torch.nn.functional as F
queries = torch.randn(2, 3)
keys = torch.randn(2, 3)
values = torch.randn(2, 3)
scores = torch.matmul(queries, keys.T) / torch.sqrt(torch.tensor(3.0))
attention_weights = F.softmax(scores, dim=0)
output = torch.matmul(attention_weights, values)Solution
Step 1: Identify the issue
Softmax should be applied on the last dimension, not the first.Step 2: Eliminate other causes
Scaling factor and tensor shapes are correct; normalization is handled by softmax.Final Answer:
Option B -> Option BQuick Check:
Softmax on last dim for attention [OK]
Solution
Step 1: Identify optimization techniques
Fusing operations can reduce computational overhead.Step 2: Evaluate each option
Fusing batch normalization with linear layers reduces redundant computations.Final Answer:
Option A -> Option AQuick Check:
Fuse layers to optimize batch norm [OK]
Solution
Step 1: Identify computational overhead sources
Frequent updates can increase overhead, especially in large-scale setups.Step 2: Optimize scheduler updates
Creating a custom scheduler that reduces the frequency of updates can minimize computational costs while maintaining performance.Final Answer:
Option D -> Option DQuick Check:
Custom schedulers can reduce update frequency. [OK]
