Coverage for /usr/lib/python3/dist-packages/scipy/stats/_entropy.py: 14%

86 statements  

« prev     ^ index     » next       coverage.py v7.9.1, created at 2025-06-14 15:55 +0200

1""" 

2Created on Fri Apr 2 09:06:05 2021 

3 

4@author: matth 

5""" 

6 

7from __future__ import annotations 

8import math 

9import numpy as np 

10from scipy import special 

11 

12__all__ = ['entropy', 'differential_entropy'] 

13 

14 

15def entropy(pk: np.typing.ArrayLike, 

16 qk: np.typing.ArrayLike | None = None, 

17 base: float | None = None, 

18 axis: int = 0 

19 ) -> np.number | np.ndarray: 

20 """ 

21 Calculate the Shannon entropy/relative entropy of given distribution(s). 

22 

23 If only probabilities `pk` are given, the Shannon entropy is calculated as 

24 ``H = -sum(pk * log(pk))``. 

25 

26 If `qk` is not None, then compute the relative entropy 

27 ``D = sum(pk * log(pk / qk))``. This quantity is also known 

28 as the Kullback-Leibler divergence. 

29 

30 This routine will normalize `pk` and `qk` if they don't sum to 1. 

31 

32 Parameters 

33 ---------- 

34 pk : array_like 

35 Defines the (discrete) distribution. Along each axis-slice of ``pk``, 

36 element ``i`` is the (possibly unnormalized) probability of event 

37 ``i``. 

38 qk : array_like, optional 

39 Sequence against which the relative entropy is computed. Should be in 

40 the same format as `pk`. 

41 base : float, optional 

42 The logarithmic base to use, defaults to ``e`` (natural logarithm). 

43 axis : int, optional 

44 The axis along which the entropy is calculated. Default is 0. 

45 

46 Returns 

47 ------- 

48 S : {float, array_like} 

49 The calculated entropy. 

50 

51 Notes 

52 ----- 

53 Informally, the Shannon entropy quantifies the expected uncertainty 

54 inherent in the possible outcomes of a discrete random variable. 

55 For example, 

56 if messages consisting of sequences of symbols from a set are to be 

57 encoded and transmitted over a noiseless channel, then the Shannon entropy 

58 ``H(pk)`` gives a tight lower bound for the average number of units of 

59 information needed per symbol if the symbols occur with frequencies 

60 governed by the discrete distribution `pk` [1]_. The choice of base 

61 determines the choice of units; e.g., ``e`` for nats, ``2`` for bits, etc. 

62 

63 The relative entropy, ``D(pk|qk)``, quantifies the increase in the average 

64 number of units of information needed per symbol if the encoding is 

65 optimized for the probability distribution `qk` instead of the true 

66 distribution `pk`. Informally, the relative entropy quantifies the expected 

67 excess in surprise experienced if one believes the true distribution is 

68 `qk` when it is actually `pk`. 

69 

70 A related quantity, the cross entropy ``CE(pk, qk)``, satisfies the 

71 equation ``CE(pk, qk) = H(pk) + D(pk|qk)`` and can also be calculated with 

72 the formula ``CE = -sum(pk * log(qk))``. It gives the average 

73 number of units of information needed per symbol if an encoding is 

74 optimized for the probability distribution `qk` when the true distribution 

75 is `pk`. It is not computed directly by `entropy`, but it can be computed 

76 using two calls to the function (see Examples). 

77 

78 See [2]_ for more information. 

79 

80 References 

81 ---------- 

82 .. [1] Shannon, C.E. (1948), A Mathematical Theory of Communication. 

83 Bell System Technical Journal, 27: 379-423. 

84 https://doi.org/10.1002/j.1538-7305.1948.tb01338.x 

85 .. [2] Thomas M. Cover and Joy A. Thomas. 2006. Elements of Information 

86 Theory (Wiley Series in Telecommunications and Signal Processing). 

87 Wiley-Interscience, USA. 

88 

89 

90 Examples 

91 -------- 

92 The outcome of a fair coin is the most uncertain: 

93 

94 >>> import numpy as np 

95 >>> from scipy.stats import entropy 

96 >>> base = 2 # work in units of bits 

97 >>> pk = np.array([1/2, 1/2]) # fair coin 

98 >>> H = entropy(pk, base=base) 

99 >>> H 

100 1.0 

101 >>> H == -np.sum(pk * np.log(pk)) / np.log(base) 

102 True 

103 

104 The outcome of a biased coin is less uncertain: 

105 

106 >>> qk = np.array([9/10, 1/10]) # biased coin 

107 >>> entropy(qk, base=base) 

108 0.46899559358928117 

109 

110 The relative entropy between the fair coin and biased coin is calculated 

111 as: 

112 

113 >>> D = entropy(pk, qk, base=base) 

114 >>> D 

115 0.7369655941662062 

116 >>> D == np.sum(pk * np.log(pk/qk)) / np.log(base) 

117 True 

118 

119 The cross entropy can be calculated as the sum of the entropy and 

120 relative entropy`: 

121 

122 >>> CE = entropy(pk, base=base) + entropy(pk, qk, base=base) 

123 >>> CE 

124 1.736965594166206 

125 >>> CE == -np.sum(pk * np.log(qk)) / np.log(base) 

126 True 

127 

128 """ 

129 if base is not None and base <= 0: 

130 raise ValueError("`base` must be a positive number or `None`.") 

131 

132 pk = np.asarray(pk) 

133 pk = 1.0*pk / np.sum(pk, axis=axis, keepdims=True) 

134 if qk is None: 

135 vec = special.entr(pk) 

136 else: 

137 qk = np.asarray(qk) 

138 pk, qk = np.broadcast_arrays(pk, qk) 

139 qk = 1.0*qk / np.sum(qk, axis=axis, keepdims=True) 

140 vec = special.rel_entr(pk, qk) 

141 S = np.sum(vec, axis=axis) 

142 if base is not None: 

143 S /= np.log(base) 

144 return S 

145 

146 

147def differential_entropy( 

148 values: np.typing.ArrayLike, 

149 *, 

150 window_length: int | None = None, 

151 base: float | None = None, 

152 axis: int = 0, 

153 method: str = "auto", 

154) -> np.number | np.ndarray: 

155 r"""Given a sample of a distribution, estimate the differential entropy. 

156 

157 Several estimation methods are available using the `method` parameter. By 

158 default, a method is selected based the size of the sample. 

159 

160 Parameters 

161 ---------- 

162 values : sequence 

163 Sample from a continuous distribution. 

164 window_length : int, optional 

165 Window length for computing Vasicek estimate. Must be an integer 

166 between 1 and half of the sample size. If ``None`` (the default), it 

167 uses the heuristic value 

168 

169 .. math:: 

170 \left \lfloor \sqrt{n} + 0.5 \right \rfloor 

171 

172 where :math:`n` is the sample size. This heuristic was originally 

173 proposed in [2]_ and has become common in the literature. 

174 base : float, optional 

175 The logarithmic base to use, defaults to ``e`` (natural logarithm). 

176 axis : int, optional 

177 The axis along which the differential entropy is calculated. 

178 Default is 0. 

179 method : {'vasicek', 'van es', 'ebrahimi', 'correa', 'auto'}, optional 

180 The method used to estimate the differential entropy from the sample. 

181 Default is ``'auto'``. See Notes for more information. 

182 

183 Returns 

184 ------- 

185 entropy : float 

186 The calculated differential entropy. 

187 

188 Notes 

189 ----- 

190 This function will converge to the true differential entropy in the limit 

191 

192 .. math:: 

193 n \to \infty, \quad m \to \infty, \quad \frac{m}{n} \to 0 

194 

195 The optimal choice of ``window_length`` for a given sample size depends on 

196 the (unknown) distribution. Typically, the smoother the density of the 

197 distribution, the larger the optimal value of ``window_length`` [1]_. 

198 

199 The following options are available for the `method` parameter. 

200 

201 * ``'vasicek'`` uses the estimator presented in [1]_. This is 

202 one of the first and most influential estimators of differential entropy. 

203 * ``'van es'`` uses the bias-corrected estimator presented in [3]_, which 

204 is not only consistent but, under some conditions, asymptotically normal. 

205 * ``'ebrahimi'`` uses an estimator presented in [4]_, which was shown 

206 in simulation to have smaller bias and mean squared error than 

207 the Vasicek estimator. 

208 * ``'correa'`` uses the estimator presented in [5]_ based on local linear 

209 regression. In a simulation study, it had consistently smaller mean 

210 square error than the Vasiceck estimator, but it is more expensive to 

211 compute. 

212 * ``'auto'`` selects the method automatically (default). Currently, 

213 this selects ``'van es'`` for very small samples (<10), ``'ebrahimi'`` 

214 for moderate sample sizes (11-1000), and ``'vasicek'`` for larger 

215 samples, but this behavior is subject to change in future versions. 

216 

217 All estimators are implemented as described in [6]_. 

218 

219 References 

220 ---------- 

221 .. [1] Vasicek, O. (1976). A test for normality based on sample entropy. 

222 Journal of the Royal Statistical Society: 

223 Series B (Methodological), 38(1), 54-59. 

224 .. [2] Crzcgorzewski, P., & Wirczorkowski, R. (1999). Entropy-based 

225 goodness-of-fit test for exponentiality. Communications in 

226 Statistics-Theory and Methods, 28(5), 1183-1202. 

227 .. [3] Van Es, B. (1992). Estimating functionals related to a density by a 

228 class of statistics based on spacings. Scandinavian Journal of 

229 Statistics, 61-72. 

230 .. [4] Ebrahimi, N., Pflughoeft, K., & Soofi, E. S. (1994). Two measures 

231 of sample entropy. Statistics & Probability Letters, 20(3), 225-234. 

232 .. [5] Correa, J. C. (1995). A new estimator of entropy. Communications 

233 in Statistics-Theory and Methods, 24(10), 2439-2449. 

234 .. [6] Noughabi, H. A. (2015). Entropy Estimation Using Numerical Methods. 

235 Annals of Data Science, 2(2), 231-241. 

236 https://link.springer.com/article/10.1007/s40745-015-0045-9 

237 

238 Examples 

239 -------- 

240 >>> import numpy as np 

241 >>> from scipy.stats import differential_entropy, norm 

242 

243 Entropy of a standard normal distribution: 

244 

245 >>> rng = np.random.default_rng() 

246 >>> values = rng.standard_normal(100) 

247 >>> differential_entropy(values) 

248 1.3407817436640392 

249 

250 Compare with the true entropy: 

251 

252 >>> float(norm.entropy()) 

253 1.4189385332046727 

254 

255 For several sample sizes between 5 and 1000, compare the accuracy of 

256 the ``'vasicek'``, ``'van es'``, and ``'ebrahimi'`` methods. Specifically, 

257 compare the root mean squared error (over 1000 trials) between the estimate 

258 and the true differential entropy of the distribution. 

259 

260 >>> from scipy import stats 

261 >>> import matplotlib.pyplot as plt 

262 >>> 

263 >>> 

264 >>> def rmse(res, expected): 

265 ... '''Root mean squared error''' 

266 ... return np.sqrt(np.mean((res - expected)**2)) 

267 >>> 

268 >>> 

269 >>> a, b = np.log10(5), np.log10(1000) 

270 >>> ns = np.round(np.logspace(a, b, 10)).astype(int) 

271 >>> reps = 1000 # number of repetitions for each sample size 

272 >>> expected = stats.expon.entropy() 

273 >>> 

274 >>> method_errors = {'vasicek': [], 'van es': [], 'ebrahimi': []} 

275 >>> for method in method_errors: 

276 ... for n in ns: 

277 ... rvs = stats.expon.rvs(size=(reps, n), random_state=rng) 

278 ... res = stats.differential_entropy(rvs, method=method, axis=-1) 

279 ... error = rmse(res, expected) 

280 ... method_errors[method].append(error) 

281 >>> 

282 >>> for method, errors in method_errors.items(): 

283 ... plt.loglog(ns, errors, label=method) 

284 >>> 

285 >>> plt.legend() 

286 >>> plt.xlabel('sample size') 

287 >>> plt.ylabel('RMSE (1000 trials)') 

288 >>> plt.title('Entropy Estimator Error (Exponential Distribution)') 

289 

290 """ 

291 values = np.asarray(values) 

292 values = np.moveaxis(values, axis, -1) 

293 n = values.shape[-1] # number of observations 

294 

295 if window_length is None: 

296 window_length = math.floor(math.sqrt(n) + 0.5) 

297 

298 if not 2 <= 2 * window_length < n: 

299 raise ValueError( 

300 f"Window length ({window_length}) must be positive and less " 

301 f"than half the sample size ({n}).", 

302 ) 

303 

304 if base is not None and base <= 0: 

305 raise ValueError("`base` must be a positive number or `None`.") 

306 

307 sorted_data = np.sort(values, axis=-1) 

308 

309 methods = {"vasicek": _vasicek_entropy, 

310 "van es": _van_es_entropy, 

311 "correa": _correa_entropy, 

312 "ebrahimi": _ebrahimi_entropy, 

313 "auto": _vasicek_entropy} 

314 method = method.lower() 

315 if method not in methods: 

316 message = f"`method` must be one of {set(methods)}" 

317 raise ValueError(message) 

318 

319 if method == "auto": 

320 if n <= 10: 

321 method = 'van es' 

322 elif n <= 1000: 

323 method = 'ebrahimi' 

324 else: 

325 method = 'vasicek' 

326 

327 res = methods[method](sorted_data, window_length) 

328 

329 if base is not None: 

330 res /= np.log(base) 

331 

332 return res 

333 

334 

335def _pad_along_last_axis(X, m): 

336 """Pad the data for computing the rolling window difference.""" 

337 # scales a bit better than method in _vasicek_like_entropy 

338 shape = np.array(X.shape) 

339 shape[-1] = m 

340 Xl = np.broadcast_to(X[..., [0]], shape) # [0] vs 0 to maintain shape 

341 Xr = np.broadcast_to(X[..., [-1]], shape) 

342 return np.concatenate((Xl, X, Xr), axis=-1) 

343 

344 

345def _vasicek_entropy(X, m): 

346 """Compute the Vasicek estimator as described in [6] Eq. 1.3.""" 

347 n = X.shape[-1] 

348 X = _pad_along_last_axis(X, m) 

349 differences = X[..., 2 * m:] - X[..., : -2 * m:] 

350 logs = np.log(n/(2*m) * differences) 

351 return np.mean(logs, axis=-1) 

352 

353 

354def _van_es_entropy(X, m): 

355 """Compute the van Es estimator as described in [6].""" 

356 # No equation number, but referred to as HVE_mn. 

357 # Typo: there should be a log within the summation. 

358 n = X.shape[-1] 

359 difference = X[..., m:] - X[..., :-m] 

360 term1 = 1/(n-m) * np.sum(np.log((n+1)/m * difference), axis=-1) 

361 k = np.arange(m, n+1) 

362 return term1 + np.sum(1/k) + np.log(m) - np.log(n+1) 

363 

364 

365def _ebrahimi_entropy(X, m): 

366 """Compute the Ebrahimi estimator as described in [6].""" 

367 # No equation number, but referred to as HE_mn 

368 n = X.shape[-1] 

369 X = _pad_along_last_axis(X, m) 

370 

371 differences = X[..., 2 * m:] - X[..., : -2 * m:] 

372 

373 i = np.arange(1, n+1).astype(float) 

374 ci = np.ones_like(i)*2 

375 ci[i <= m] = 1 + (i[i <= m] - 1)/m 

376 ci[i >= n - m + 1] = 1 + (n - i[i >= n-m+1])/m 

377 

378 logs = np.log(n * differences / (ci * m)) 

379 return np.mean(logs, axis=-1) 

380 

381 

382def _correa_entropy(X, m): 

383 """Compute the Correa estimator as described in [6].""" 

384 # No equation number, but referred to as HC_mn 

385 n = X.shape[-1] 

386 X = _pad_along_last_axis(X, m) 

387 

388 i = np.arange(1, n+1) 

389 dj = np.arange(-m, m+1)[:, None] 

390 j = i + dj 

391 j0 = j + m - 1 # 0-indexed version of j 

392 

393 Xibar = np.mean(X[..., j0], axis=-2, keepdims=True) 

394 difference = X[..., j0] - Xibar 

395 num = np.sum(difference*dj, axis=-2) # dj is d-i 

396 den = n*np.sum(difference**2, axis=-2) 

397 return -np.mean(np.log(num/den), axis=-1)