MCPcopy Create free account
hub / github.com/OpenDriveLab/ReSim / weighted_randint

Function weighted_randint

sat/sgm/modules/diffusionmodules/sigma_sampling.py:9–39  ·  view source on GitHub ↗

Generates weighted random integers within a specified range. Args: low (int): The lower bound of the random integers (inclusive). high (int): The upper bound of the random integers (exclusive). size (tuple): The desired shape of the output tensor. weight_fun

(values, weight_function=None)

Source from the content-addressed store, hash-verified

7
8
9def weighted_randint(values, weight_function=None):
10 """
11 Generates weighted random integers within a specified range.
12
13 Args:
14 low (int): The lower bound of the random integers (inclusive).
15 high (int): The upper bound of the random integers (exclusive).
16 size (tuple): The desired shape of the output tensor.
17 weight_function (callable, optional): A function that takes an integer
18 within the range [low, high) and returns a weight (probability).
19 If None, uniform sampling is used.
20
21 Returns:
22 torch.Tensor: A tensor of weighted random integers.
23 """
24
25 # values: a tensor
26
27 # 2. Apply the weight function (if provided)
28 if weight_function is not None:
29 weights = torch.tensor([weight_function(v) for v in values], dtype=torch.float)
30 # Normalize weights to sum to 1
31 weights /= weights.sum()
32 else:
33 weights = torch.ones_like(values, dtype=torch.float) / len(values)
34
35 # 3. Sample indices based on weights
36 indices = torch.multinomial(weights, num_samples=len(values), replacement=True)
37
38 # 4. Gather values based on sampled indices and reshape
39 return values[indices]
40
41def my_weight_function(x):
42 if 500 <= x < 1000:

Callers 1

__call__Method · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected