MCPcopy Index your code
hub / github.com/python/cpython / kde_random

Function kde_random

Lib/statistics.py:1094–1136  ·  view source on GitHub ↗

Return a function that makes a random selection from the estimated probability density function created by kde(data, h, kernel). Providing a *seed* allows reproducible selections within a single thread. The seed may be an integer, float, str, or bytes. A StatisticsError will be ra

(data, h, kernel='normal', *, seed=None)

Source from the content-addressed store, hash-verified

1092
1093
1094def kde_random(data, h, kernel='normal', *, seed=None):
1095 """Return a function that makes a random selection from the estimated
1096 probability density function created by kde(data, h, kernel).
1097
1098 Providing a *seed* allows reproducible selections within a single
1099 thread. The seed may be an integer, float, str, or bytes.
1100
1101 A StatisticsError will be raised if the *data* sequence is empty.
1102
1103 Example:
1104
1105 >>> data = [-2.1, -1.3, -0.4, 1.9, 5.1, 6.2]
1106 >>> rand = kde_random(data, h=1.5, seed=8675309)
1107 >>> new_selections = [rand() for i in range(10)]
1108 >>> [round(x, 1) for x in new_selections]
1109 [0.7, 6.2, 1.2, 6.9, 7.0, 1.8, 2.5, -0.5, -1.8, 5.6]
1110
1111 """
1112 n = len(data)
1113 if not n:
1114 raise StatisticsError('Empty data sequence')
1115
1116 if not isinstance(data[0], (int, float)):
1117 raise TypeError('Data sequence must contain ints or floats')
1118
1119 if h <= 0.0:
1120 raise StatisticsError(f'Bandwidth h must be positive, not {h=!r}')
1121
1122 kernel_spec = _kernel_specs.get(kernel)
1123 if kernel_spec is None:
1124 raise StatisticsError(f'Unknown kernel name: {kernel!r}')
1125 invcdf = kernel_spec['invcdf']
1126
1127 prng = _random.Random(seed)
1128 random = prng.random
1129 choice = prng.choice
1130
1131 def rand():
1132 return choice(data) + h * invcdf(random())
1133
1134 rand.__doc__ = f'Random KDE selection with {h=!r} and {kernel=!r}'
1135
1136 return rand
1137
1138
1139## Quantiles ###############################################################

Callers 1

test_kde_randomMethod · 0.85

Calls 2

StatisticsErrorClass · 0.85
getMethod · 0.45

Tested by 1

test_kde_randomMethod · 0.68

Used in the wild real call sites across dependent graphs

searching dependent graphs…