|
| 1 | +# Weighted Random |
| 2 | + |
| 3 | +## What is "Weighted Random" |
| 4 | + |
| 5 | +Let's say you have a list of **items**. Item could be anything. For example, we may have a list of fruits and vegetables that you like to eat: `[ '🍌', '🍎', '🥕' ]`. |
| 6 | + |
| 7 | +The list of **weights** represent the weight (or probability, or importance) of each item. Weights are numbers. For example, the weights like `[3, 7, 1]` would say that: |
| 8 | + |
| 9 | +- you would like to eat `🍎 apples` more often (`7` out of `3 + 7 + 1 = 11` times), |
| 10 | +- then you would like to eat `bananas 🍌` less often (only `3` out of `11` times), |
| 11 | +- and the `carrots 🥕` you really don't like (want to eat it only `1` out of `11` times). |
| 12 | + |
| 13 | +> If we speak in terms of probabilities than the weights list might be an array of floats that sum up to `1` (i.e. `[0.1, 0.5, 0.2, 0.2]`). |
| 14 | +
|
| 15 | +The **Weighted Random** in this case will be the function that will randomly return you the item from the list, and it will take each item's weight into account, so that items with the higher weight will be picked more often. |
| 16 | + |
| 17 | +Example of the function interface: |
| 18 | + |
| 19 | +```javascript |
| 20 | +const items = [ '🍌', '🍎', '🥕' ]; |
| 21 | +const weights = [ 3, 7, 1 ]; |
| 22 | + |
| 23 | +function weightedRandom(items, weights) { |
| 24 | + // implementation goes here ... |
| 25 | +} |
| 26 | + |
| 27 | +const nextSnackToEat = weightedRandom(items, weights); // Could be '🍎' |
| 28 | +``` |
| 29 | + |
| 30 | +## Applications of Weighted Random |
| 31 | + |
| 32 | +- In [Genetic Algorithm](https://en.wikipedia.org/wiki/Genetic_algorithm) the weighted random is used during the "Selection" phase, when we need to select the fittest/strongest individuums based on their fitness score for mating and for producing the next stronger generation. You may find an **example** in the [Self-Parking Car in 500 Lines of Code](https://trekhleb.dev/blog/2021/self-parking-car-evolution/) article. |
| 33 | +- In [Recurrent Neural Networks (RNN)](https://en.wikipedia.org/wiki/Recurrent_neural_network) when trying to decide what letter to choose next (to form the sentence) based on the next letter probability. You may find an **example** in the [Recipe Generation using Recurrent Neural Network (RNN)](https://nbviewer.org/github/trekhleb/machine-learning-experiments/blob/master/experiments/recipe_generation_rnn/recipe_generation_rnn.ipynb) Jupyter notebook. |
| 34 | +- In [Nginx Load Balancing](https://docs.nginx.com/nginx/admin-guide/load-balancer/http-load-balancer/) to send HTTP requests more often to the servers with the higher weights. |
| 35 | +- And more... |
| 36 | + |
| 37 | +## The Algorithm |
| 38 | + |
| 39 | +The **straightforward approach** would be to: |
| 40 | + |
| 41 | +1. Repeat each item in the list according to its weight. |
| 42 | +2. Pick the random item from the list. |
| 43 | + |
| 44 | +For example in our case with fruits and vegetables we could generate the following list of size `3 + 7 + 1 = 11`: |
| 45 | + |
| 46 | +```javascript |
| 47 | +const items = [ '🍌', '🍎', '🥕' ]; |
| 48 | +const weights = [ 3, 7, 1 ]; |
| 49 | + |
| 50 | +// Repeating the items based on weights. |
| 51 | +const weightedItems = [ |
| 52 | + '🍌', '🍌', '🍌', |
| 53 | + '🍎', '🍎', '🍎', '🍎', '🍎', '🍎', '🍎', |
| 54 | + '🥕', |
| 55 | +]; |
| 56 | + |
| 57 | +// And now just pick the random item from weightedItems array. |
| 58 | +``` |
| 59 | + |
| 60 | +However, as you may see, this approach may require a lot of memory, in case if the objects are heavy, and in case if we have a lot of them to repeat in `weightedItems` list. |
| 61 | + |
| 62 | +The **more efficient approach** would be to: |
| 63 | + |
| 64 | +1. Prepare the list of cumulative weights for each item (i.e. the `cumulativeWeights` list which will have the same number of elements as the original `weights` list). In our case it will look like this: `cumulativeWeights = [3, 3 + 7, 3 + 7 + 1] = [3, 10, 11]` |
| 65 | +2. Generate the random number `randomNumber` from `0` to the highest cumulative weight value. In our case the random number will be in a range of `[0..11]`. Let's say that we have `randomNumber = 8`. |
| 66 | +3. Go through the `cumulativeWeights` list from left to right and pick the first element which is higher or equal to the `randomNumber`. The index of such element we will use to pick the item from the `items` array. |
| 67 | + |
| 68 | +The idea behind this approach is that the higher weights will "occupy" more numeric space. Therefore, there is a higher chance that the random number will fall into the "higher weight numeric bucket". |
| 69 | + |
| 70 | +```javascript |
| 71 | +const weights = [3, 7, 1 ]; |
| 72 | +const cumulativeWeights = [3, 10, 11]; |
| 73 | + |
| 74 | +// In a pseudo-representation we may think about the cumulativeWeights array like this. |
| 75 | +const pseudoCumulativeWeights = [ |
| 76 | + 1, 2, 3, // <-- [3] numbers |
| 77 | + 4, 5, 6, 7, 8, 9, 10, // <-- [7] numbers |
| 78 | + 11, // <-- [1] number |
| 79 | +]; |
| 80 | +``` |
| 81 | + |
| 82 | +Here is an example of how the `weightedRandom` function might be implemented: |
| 83 | + |
| 84 | +```javascript |
| 85 | +/** |
| 86 | + * Picks the random item based on its weight. |
| 87 | + * The items with higher weight will be picked more often (with a higher probability). |
| 88 | + * |
| 89 | + * For example: |
| 90 | + * - items = ['banana', 'orange', 'apple'] |
| 91 | + * - weights = [0, 0.2, 0.8] |
| 92 | + * - weightedRandom(items, weights) in 80% of cases will return 'apple', in 20% of cases will return |
| 93 | + * 'orange' and it will never return 'banana' (because probability of picking the banana is 0%) |
| 94 | + * |
| 95 | + * @param {any[]} items |
| 96 | + * @param {number[]} weights |
| 97 | + * @returns {{item: any, index: number}} |
| 98 | + */ |
| 99 | +export default function weightedRandom(items, weights) { |
| 100 | + if (items.length !== weights.length) { |
| 101 | + throw new Error('Items and weights must be of the same size'); |
| 102 | + } |
| 103 | + |
| 104 | + if (!items.length) { |
| 105 | + throw new Error('Items must not be empty'); |
| 106 | + } |
| 107 | + |
| 108 | + // Preparing the cumulative weights array. |
| 109 | + // For example: |
| 110 | + // - weights = [1, 4, 3] |
| 111 | + // - cumulativeWeights = [1, 5, 8] |
| 112 | + const cumulativeWeights = []; |
| 113 | + for (let i = 0; i < weights.length; i += 1) { |
| 114 | + cumulativeWeights[i] = weights[i] + (cumulativeWeights[i - 1] || 0); |
| 115 | + } |
| 116 | + |
| 117 | + // Getting the random number in a range of [0...sum(weights)] |
| 118 | + // For example: |
| 119 | + // - weights = [1, 4, 3] |
| 120 | + // - maxCumulativeWeight = 8 |
| 121 | + // - range for the random number is [0...8] |
| 122 | + const maxCumulativeWeight = cumulativeWeights[cumulativeWeights.length - 1]; |
| 123 | + const randomNumber = maxCumulativeWeight * Math.random(); |
| 124 | + |
| 125 | + // Picking the random item based on its weight. |
| 126 | + // The items with higher weight will be picked more often. |
| 127 | + for (let itemIndex = 0; itemIndex < items.length; itemIndex += 1) { |
| 128 | + if (cumulativeWeights[itemIndex] >= randomNumber) { |
| 129 | + return { |
| 130 | + item: items[itemIndex], |
| 131 | + index: itemIndex, |
| 132 | + }; |
| 133 | + } |
| 134 | + } |
| 135 | +} |
| 136 | +``` |
| 137 | + |
| 138 | +## Implementation |
| 139 | + |
| 140 | +- Check the [weightedRandom.js](weightedRandom.js) file for the implementation of the `weightedRandom()` function. |
| 141 | +- Check the [weightedRandom.test.js](__test__/weightedRandom.test.js) file for the tests-cases. |
0 commit comments