BasicsPyTorchActivationsGoogleMetaAmazon
Problem
Implement leaky_and_tanh(x, alpha=0.1) returning a 2-tuple (leaky_out, tanh_out) where LeakyReLU(x)=x for x>0 and αx for x≤0, and tanh(x)=ex+e−xex−e−x.
Why It Matters: LeakyReLU prevents 'dying ReLU' neurons by keeping a small non-zero slope for negative inputs, while tanh maps activations into zero-centered (-1, 1) bounds used in RNNs, LSTMs, and gating units.
Function Signature
import torch
def leaky_and_tanh(x: torch.Tensor, alpha: float = 0.1):
"""Return (LeakyReLU(x, alpha), Tanh(x))."""
Sample Input & Output
Example 1: Mixed Values With alpha = 0.1
Input:
x = torch.tensor([-2.0, 0.0, 2.0]), alpha = 0.1
Expected Output:
(tensor([-0.2, 0.0, 2.0]), tensor([-0.9640, 0.0000, 0.9640]))
Explanation: For -2.0, LeakyReLU outputs 0.1 * (-2.0) = -0.2 and tanh(-2.0) ≈ -0.9640.
Example 2: Custom Negative Slope alpha = 0.25
Input:
x = torch.tensor([-4.0, 1.0]), alpha = 0.25
Expected Output:
(tensor([-1.0, 1.0]), tensor([-0.9993, 0.7616]))
Explanation: Negative entries scale by 0.25; positive entries remain unchanged under LeakyReLU.
Constraints & Edge Cases
- Return
(leaky_out, tanh_out). - Both outputs must have the same shape as
x. - Use
torch.where(x > 0, x, alpha * x)andtorch.tanh(x).
Constraints & Evaluation Criteria
- Return `(leaky_out, tanh_out)`.
Hints
Python 3⌘/Ctrl+Enter to Run · ⌘/Ctrl+Shift+Enter to Submit
Loading Code Editor...
+1 Hidden Submit Case
Input / Scenario
[-2, 0, 2], alpha=0.1
Expected Output / Criteria
leaky=[-0.2,0,2], tanh=[-0.964,0,0.964]