r"""An initializer that returns a sparse matrix. Args: sparsity (float): The fraction of elements in each column to be set to zero. mean (float, optional): Mean of the normal distribution. Default: ``0.0``. std (float, optional): Standard deviation of t
(
sparsity: float,
mean: float = 0.0,
std: float = 1.0,
dtype: mx.Dtype = mx.float32,
)
| 351 | |
| 352 | |
| 353 | def sparse( |
| 354 | sparsity: float, |
| 355 | mean: float = 0.0, |
| 356 | std: float = 1.0, |
| 357 | dtype: mx.Dtype = mx.float32, |
| 358 | ) -> Callable[[mx.array], mx.array]: |
| 359 | r"""An initializer that returns a sparse matrix. |
| 360 | |
| 361 | Args: |
| 362 | sparsity (float): The fraction of elements in each column to be set to |
| 363 | zero. |
| 364 | mean (float, optional): Mean of the normal distribution. Default: |
| 365 | ``0.0``. |
| 366 | std (float, optional): Standard deviation of the normal distribution. |
| 367 | Default: ``1.0``. |
| 368 | dtype (Dtype, optional): The data type of the array. Default: |
| 369 | ``float32``. |
| 370 | |
| 371 | Returns: |
| 372 | Callable[[array], array]: An initializer that returns an array with the |
| 373 | same shape as the input, filled with samples from a normal distribution. |
| 374 | |
| 375 | Example: |
| 376 | |
| 377 | >>> init_fn = nn.init.sparse(sparsity=0.5) |
| 378 | >>> init_fn(mx.zeros((2, 2))) |
| 379 | array([[-1.91187, -0.117483], |
| 380 | [0, 0]], dtype=float32) |
| 381 | """ |
| 382 | |
| 383 | def initializer(a: mx.array) -> mx.array: |
| 384 | if a.ndim != 2: |
| 385 | raise ValueError("Only tensors with 2 dimensions are supported") |
| 386 | |
| 387 | rows, cols = a.shape |
| 388 | num_zeros = int(math.ceil(sparsity * cols)) |
| 389 | |
| 390 | order = mx.argsort(mx.random.uniform(shape=a.shape), axis=1) |
| 391 | a = mx.random.normal(shape=a.shape, scale=std, loc=mean, dtype=dtype) |
| 392 | |
| 393 | a[mx.arange(rows).reshape(rows, 1), order[:, :num_zeros]] = 0 |
| 394 | |
| 395 | return a |
| 396 | |
| 397 | return initializer |
| 398 | |
| 399 | |
| 400 | def orthogonal( |
nothing calls this directly
no outgoing calls
no test coverage detected