#369 · Deep Learning · Easy
⊣ Solve on deep-ml.comImplement Xavier/Glorot weight initialization for neural network layers. This method initializes weights from a distribution scaled by the number of input and output neurons, keeping variance stable across layers.
import numpy as np
def xavier_init(fan_in: int, fan_out: int, mode: str = "uniform") -> np.ndarray:
if mode == "uniform":
limit = np.sqrt(6.0 / (fan_in + fan_out))
return np.random.uniform(-limit, limit, (fan_in, fan_out))
elif mode == "normal":
std = np.sqrt(2.0 / (fan_in + fan_out))
return np.random.normal(0, std, (fan_in, fan_out))
else:
raise ValueError(f"Unknown mode: {mode}")limit = sqrt(6 / (fan_in + fan_out)).std = sqrt(2 / (fan_in + fan_out)).