random_choice
random_choice is an algorithm used to randomly select elements from a set by probability. In computer science, random selection is a common operation used in scenarios such as random sampling, random arrangement, and Monte Carlo simulation.
The core of the random selection algorithm is to randomly select an element from a given set. For an input whose sum is 1, it randomly selects an element by probability and returns the index of the element.
Interface Definition
def random_choice(arr: np.ndarray, seed: int)->List[int]
Receives NumPy arrays and random seeds, and returns the result of random_choice calculation.
Input Parameters
Parameter |
Type |
Description |
|---|---|---|
arr |
ndarray |
The data type is FP32, and the dimension can be 1D or 2D. When the dimension is 2D, the shape must be (1, N) or (N, 1). |
seed |
int |
Random seed. If seed=-1, the random seed is generated by the system based on the current timestamp. If seed!=-1, the random seed is the input value. |
Return Value
Type |
Description |
|---|---|
List[int] |
The length is 1. If an exception occurs, [-1] is returned. |
Example
>>> import numpy as np >>> from libkdnn_ext import random_choice >>> a = np.random.rand(1, 70336).astype(np.float32) >>> a = np.abs(a) >>> t = a.sum(axis=1) >>> a = a / t >>> random_choice(a, -1) array([17630], dtype=int32) >>> random_choice(a, 2) array([49333], dtype=int32)