Prompt48 commited on
Commit
59582c2
·
verified ·
1 Parent(s): 70266e4

Upload edit\Qwen3-TTS-test\.venv\Lib\site-packages\sklearn\decomposition\tests\test_online_lda.py with huggingface_hub

Browse files
edit//Qwen3-TTS-test//.venv//Lib//site-packages//sklearn//decomposition//tests//test_online_lda.py ADDED
@@ -0,0 +1,489 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ from io import StringIO
3
+
4
+ import numpy as np
5
+ import pytest
6
+ from numpy.testing import assert_array_equal
7
+ from scipy.linalg import block_diag
8
+ from scipy.special import psi
9
+
10
+ from sklearn.decomposition import LatentDirichletAllocation
11
+ from sklearn.decomposition._online_lda_fast import (
12
+ _dirichlet_expectation_1d,
13
+ _dirichlet_expectation_2d,
14
+ )
15
+ from sklearn.exceptions import NotFittedError
16
+ from sklearn.utils._testing import (
17
+ assert_allclose,
18
+ assert_almost_equal,
19
+ assert_array_almost_equal,
20
+ if_safe_multiprocessing_with_blas,
21
+ )
22
+ from sklearn.utils.fixes import CSR_CONTAINERS
23
+
24
+
25
+ def _build_sparse_array(csr_container):
26
+ # Create 3 topics and each topic has 3 distinct words.
27
+ # (Each word only belongs to a single topic.)
28
+ n_components = 3
29
+ block = np.full((3, 3), n_components, dtype=int)
30
+ blocks = [block] * n_components
31
+ X = block_diag(*blocks)
32
+ X = csr_container(X)
33
+ return (n_components, X)
34
+
35
+
36
+ @pytest.mark.parametrize("csr_container", CSR_CONTAINERS)
37
+ def test_lda_default_prior_params(csr_container):
38
+ # default prior parameter should be `1 / topics`
39
+ # and verbose params should not affect result
40
+ n_components, X = _build_sparse_array(csr_container)
41
+ prior = 1.0 / n_components
42
+ lda_1 = LatentDirichletAllocation(
43
+ n_components=n_components,
44
+ doc_topic_prior=prior,
45
+ topic_word_prior=prior,
46
+ random_state=0,
47
+ )
48
+ lda_2 = LatentDirichletAllocation(n_components=n_components, random_state=0)
49
+ topic_distr_1 = lda_1.fit_transform(X)
50
+ topic_distr_2 = lda_2.fit_transform(X)
51
+ assert_almost_equal(topic_distr_1, topic_distr_2)
52
+
53
+
54
+ @pytest.mark.parametrize("csr_container", CSR_CONTAINERS)
55
+ def test_lda_fit_batch(csr_container):
56
+ # Test LDA batch learning_offset (`fit` method with 'batch' learning)
57
+ rng = np.random.RandomState(0)
58
+ n_components, X = _build_sparse_array(csr_container)
59
+ lda = LatentDirichletAllocation(
60
+ n_components=n_components,
61
+ evaluate_every=1,
62
+ learning_method="batch",
63
+ random_state=rng,
64
+ )
65
+ lda.fit(X)
66
+
67
+ correct_idx_grps = [(0, 1, 2), (3, 4, 5), (6, 7, 8)]
68
+ for component in lda.components_:
69
+ # Find top 3 words in each LDA component
70
+ top_idx = set(component.argsort()[-3:][::-1])
71
+ assert tuple(sorted(top_idx)) in correct_idx_grps
72
+
73
+
74
+ @pytest.mark.parametrize("csr_container", CSR_CONTAINERS)
75
+ def test_lda_fit_online(csr_container):
76
+ # Test LDA online learning (`fit` method with 'online' learning)
77
+ rng = np.random.RandomState(0)
78
+ n_components, X = _build_sparse_array(csr_container)
79
+ lda = LatentDirichletAllocation(
80
+ n_components=n_components,
81
+ learning_offset=10.0,
82
+ evaluate_every=1,
83
+ learning_method="online",
84
+ random_state=rng,
85
+ )
86
+ lda.fit(X)
87
+
88
+ correct_idx_grps = [(0, 1, 2), (3, 4, 5), (6, 7, 8)]
89
+ for component in lda.components_:
90
+ # Find top 3 words in each LDA component
91
+ top_idx = set(component.argsort()[-3:][::-1])
92
+ assert tuple(sorted(top_idx)) in correct_idx_grps
93
+
94
+
95
+ @pytest.mark.parametrize("csr_container", CSR_CONTAINERS)
96
+ def test_lda_partial_fit(csr_container):
97
+ # Test LDA online learning (`partial_fit` method)
98
+ # (same as test_lda_batch)
99
+ rng = np.random.RandomState(0)
100
+ n_components, X = _build_sparse_array(csr_container)
101
+ lda = LatentDirichletAllocation(
102
+ n_components=n_components,
103
+ learning_offset=10.0,
104
+ total_samples=100,
105
+ random_state=rng,
106
+ )
107
+ for i in range(3):
108
+ lda.partial_fit(X)
109
+
110
+ correct_idx_grps = [(0, 1, 2), (3, 4, 5), (6, 7, 8)]
111
+ for c in lda.components_:
112
+ top_idx = set(c.argsort()[-3:][::-1])
113
+ assert tuple(sorted(top_idx)) in correct_idx_grps
114
+
115
+
116
+ @pytest.mark.parametrize("csr_container", CSR_CONTAINERS)
117
+ def test_lda_dense_input(csr_container):
118
+ # Test LDA with dense input.
119
+ rng = np.random.RandomState(0)
120
+ n_components, X = _build_sparse_array(csr_container)
121
+ lda = LatentDirichletAllocation(
122
+ n_components=n_components, learning_method="batch", random_state=rng
123
+ )
124
+ lda.fit(X.toarray())
125
+
126
+ correct_idx_grps = [(0, 1, 2), (3, 4, 5), (6, 7, 8)]
127
+ for component in lda.components_:
128
+ # Find top 3 words in each LDA component
129
+ top_idx = set(component.argsort()[-3:][::-1])
130
+ assert tuple(sorted(top_idx)) in correct_idx_grps
131
+
132
+
133
+ def test_lda_transform():
134
+ # Test LDA transform.
135
+ # Transform result cannot be negative and should be normalized by default
136
+ rng = np.random.RandomState(0)
137
+ X = rng.randint(5, size=(20, 10))
138
+ n_components = 3
139
+ lda = LatentDirichletAllocation(n_components=n_components, random_state=rng)
140
+ X_trans = lda.fit_transform(X)
141
+ assert (X_trans > 0.0).any()
142
+ assert_array_almost_equal(np.sum(X_trans, axis=1), np.ones(X_trans.shape[0]))
143
+
144
+ X_trans_unnormalized = lda.transform(X, normalize=False)
145
+ assert_array_almost_equal(
146
+ X_trans, X_trans_unnormalized / X_trans_unnormalized.sum(axis=1)[:, np.newaxis]
147
+ )
148
+
149
+
150
+ @pytest.mark.parametrize("method", ("online", "batch"))
151
+ def test_lda_fit_transform(method):
152
+ # Test LDA fit_transform & transform
153
+ # fit_transform and transform result should be the same
154
+ rng = np.random.RandomState(0)
155
+ X = rng.randint(10, size=(50, 20))
156
+ lda = LatentDirichletAllocation(
157
+ n_components=5, learning_method=method, random_state=rng
158
+ )
159
+ X_fit = lda.fit_transform(X)
160
+ X_trans = lda.transform(X)
161
+ assert_array_almost_equal(X_fit, X_trans, 4)
162
+
163
+
164
+ def test_lda_negative_input():
165
+ # test pass dense matrix with sparse negative input.
166
+ X = np.full((5, 10), -1.0)
167
+ lda = LatentDirichletAllocation()
168
+ regex = r"^Negative values in data passed"
169
+ with pytest.raises(ValueError, match=regex):
170
+ lda.fit(X)
171
+
172
+
173
+ def test_lda_no_component_error():
174
+ # test `perplexity` before `fit`
175
+ rng = np.random.RandomState(0)
176
+ X = rng.randint(4, size=(20, 10))
177
+ lda = LatentDirichletAllocation()
178
+ regex = (
179
+ "This LatentDirichletAllocation instance is not fitted yet. "
180
+ "Call 'fit' with appropriate arguments before using this "
181
+ "estimator."
182
+ )
183
+ with pytest.raises(NotFittedError, match=regex):
184
+ lda.perplexity(X)
185
+
186
+
187
+ # TODO: remove mark once loky bug is fixed:
188
+ # https://github.com/joblib/loky/issues/458
189
+ @pytest.mark.thread_unsafe
190
+ @if_safe_multiprocessing_with_blas
191
+ @pytest.mark.parametrize("csr_container", CSR_CONTAINERS)
192
+ @pytest.mark.parametrize("method", ("online", "batch"))
193
+ def test_lda_multi_jobs(method, csr_container):
194
+ n_components, X = _build_sparse_array(csr_container)
195
+ # Test LDA batch training with multi CPU
196
+ rng = np.random.RandomState(0)
197
+ lda = LatentDirichletAllocation(
198
+ n_components=n_components,
199
+ n_jobs=2,
200
+ learning_method=method,
201
+ evaluate_every=1,
202
+ random_state=rng,
203
+ )
204
+ lda.fit(X)
205
+
206
+ correct_idx_grps = [(0, 1, 2), (3, 4, 5), (6, 7, 8)]
207
+ for c in lda.components_:
208
+ top_idx = set(c.argsort()[-3:][::-1])
209
+ assert tuple(sorted(top_idx)) in correct_idx_grps
210
+
211
+
212
+ # TODO: remove mark once loky bug is fixed:
213
+ # https://github.com/joblib/loky/issues/458
214
+ @pytest.mark.thread_unsafe
215
+ @if_safe_multiprocessing_with_blas
216
+ @pytest.mark.parametrize("csr_container", CSR_CONTAINERS)
217
+ def test_lda_partial_fit_multi_jobs(csr_container):
218
+ # Test LDA online training with multi CPU
219
+ rng = np.random.RandomState(0)
220
+ n_components, X = _build_sparse_array(csr_container)
221
+ lda = LatentDirichletAllocation(
222
+ n_components=n_components,
223
+ n_jobs=2,
224
+ learning_offset=5.0,
225
+ total_samples=30,
226
+ random_state=rng,
227
+ )
228
+ for i in range(2):
229
+ lda.partial_fit(X)
230
+
231
+ correct_idx_grps = [(0, 1, 2), (3, 4, 5), (6, 7, 8)]
232
+ for c in lda.components_:
233
+ top_idx = set(c.argsort()[-3:][::-1])
234
+ assert tuple(sorted(top_idx)) in correct_idx_grps
235
+
236
+
237
+ def test_lda_preplexity_mismatch():
238
+ # test dimension mismatch in `perplexity` method
239
+ rng = np.random.RandomState(0)
240
+ n_components = rng.randint(3, 6)
241
+ n_samples = rng.randint(6, 10)
242
+ X = np.random.randint(4, size=(n_samples, 10))
243
+ lda = LatentDirichletAllocation(
244
+ n_components=n_components,
245
+ learning_offset=5.0,
246
+ total_samples=20,
247
+ random_state=rng,
248
+ )
249
+ lda.fit(X)
250
+ # invalid samples
251
+ invalid_n_samples = rng.randint(4, size=(n_samples + 1, n_components))
252
+ with pytest.raises(ValueError, match=r"Number of samples"):
253
+ lda._perplexity_precomp_distr(X, invalid_n_samples)
254
+ # invalid topic number
255
+ invalid_n_components = rng.randint(4, size=(n_samples, n_components + 1))
256
+ with pytest.raises(ValueError, match=r"Number of topics"):
257
+ lda._perplexity_precomp_distr(X, invalid_n_components)
258
+
259
+
260
+ @pytest.mark.parametrize("method", ("online", "batch"))
261
+ @pytest.mark.parametrize("csr_container", CSR_CONTAINERS)
262
+ def test_lda_perplexity(method, csr_container):
263
+ # Test LDA perplexity for batch training
264
+ # perplexity should be lower after each iteration
265
+ n_components, X = _build_sparse_array(csr_container)
266
+ lda_1 = LatentDirichletAllocation(
267
+ n_components=n_components,
268
+ max_iter=1,
269
+ learning_method=method,
270
+ total_samples=100,
271
+ random_state=0,
272
+ )
273
+ lda_2 = LatentDirichletAllocation(
274
+ n_components=n_components,
275
+ max_iter=10,
276
+ learning_method=method,
277
+ total_samples=100,
278
+ random_state=0,
279
+ )
280
+ lda_1.fit(X)
281
+ perp_1 = lda_1.perplexity(X, sub_sampling=False)
282
+
283
+ lda_2.fit(X)
284
+ perp_2 = lda_2.perplexity(X, sub_sampling=False)
285
+ assert perp_1 >= perp_2
286
+
287
+ perp_1_subsampling = lda_1.perplexity(X, sub_sampling=True)
288
+ perp_2_subsampling = lda_2.perplexity(X, sub_sampling=True)
289
+ assert perp_1_subsampling >= perp_2_subsampling
290
+
291
+
292
+ @pytest.mark.parametrize("method", ("online", "batch"))
293
+ @pytest.mark.parametrize("csr_container", CSR_CONTAINERS)
294
+ def test_lda_score(method, csr_container):
295
+ # Test LDA score for batch training
296
+ # score should be higher after each iteration
297
+ n_components, X = _build_sparse_array(csr_container)
298
+ lda_1 = LatentDirichletAllocation(
299
+ n_components=n_components,
300
+ max_iter=1,
301
+ learning_method=method,
302
+ total_samples=100,
303
+ random_state=0,
304
+ )
305
+ lda_2 = LatentDirichletAllocation(
306
+ n_components=n_components,
307
+ max_iter=10,
308
+ learning_method=method,
309
+ total_samples=100,
310
+ random_state=0,
311
+ )
312
+ lda_1.fit_transform(X)
313
+ score_1 = lda_1.score(X)
314
+
315
+ lda_2.fit_transform(X)
316
+ score_2 = lda_2.score(X)
317
+ assert score_2 >= score_1
318
+
319
+
320
+ @pytest.mark.parametrize("csr_container", CSR_CONTAINERS)
321
+ def test_perplexity_input_format(csr_container):
322
+ # Test LDA perplexity for sparse and dense input
323
+ # score should be the same for both dense and sparse input
324
+ n_components, X = _build_sparse_array(csr_container)
325
+ lda = LatentDirichletAllocation(
326
+ n_components=n_components,
327
+ max_iter=1,
328
+ learning_method="batch",
329
+ total_samples=100,
330
+ random_state=0,
331
+ )
332
+ lda.fit(X)
333
+ perp_1 = lda.perplexity(X)
334
+ perp_2 = lda.perplexity(X.toarray())
335
+ assert_almost_equal(perp_1, perp_2)
336
+
337
+
338
+ @pytest.mark.parametrize("csr_container", CSR_CONTAINERS)
339
+ def test_lda_score_perplexity(csr_container):
340
+ # Test the relationship between LDA score and perplexity
341
+ n_components, X = _build_sparse_array(csr_container)
342
+ lda = LatentDirichletAllocation(
343
+ n_components=n_components, max_iter=10, random_state=0
344
+ )
345
+ lda.fit(X)
346
+ perplexity_1 = lda.perplexity(X, sub_sampling=False)
347
+
348
+ score = lda.score(X)
349
+ perplexity_2 = np.exp(-1.0 * (score / np.sum(X.data)))
350
+ assert_almost_equal(perplexity_1, perplexity_2)
351
+
352
+
353
+ @pytest.mark.parametrize("csr_container", CSR_CONTAINERS)
354
+ def test_lda_fit_perplexity(csr_container):
355
+ # Test that the perplexity computed during fit is consistent with what is
356
+ # returned by the perplexity method
357
+ n_components, X = _build_sparse_array(csr_container)
358
+ lda = LatentDirichletAllocation(
359
+ n_components=n_components,
360
+ max_iter=1,
361
+ learning_method="batch",
362
+ random_state=0,
363
+ evaluate_every=1,
364
+ )
365
+ lda.fit(X)
366
+
367
+ # Perplexity computed at end of fit method
368
+ perplexity1 = lda.bound_
369
+
370
+ # Result of perplexity method on the train set
371
+ perplexity2 = lda.perplexity(X)
372
+
373
+ assert_almost_equal(perplexity1, perplexity2)
374
+
375
+
376
+ @pytest.mark.parametrize("csr_container", CSR_CONTAINERS)
377
+ def test_lda_empty_docs(csr_container):
378
+ """Test LDA on empty document (all-zero rows)."""
379
+ Z = np.zeros((5, 4))
380
+ for X in [Z, csr_container(Z)]:
381
+ lda = LatentDirichletAllocation(max_iter=750).fit(X)
382
+ assert_almost_equal(
383
+ lda.components_.sum(axis=0), np.ones(lda.components_.shape[1])
384
+ )
385
+
386
+
387
+ def test_dirichlet_expectation():
388
+ """Test Cython version of Dirichlet expectation calculation."""
389
+ x = np.logspace(-100, 10, 10000)
390
+ expectation = np.empty_like(x)
391
+ _dirichlet_expectation_1d(x, 0, expectation)
392
+ assert_allclose(expectation, np.exp(psi(x) - psi(np.sum(x))), atol=1e-19)
393
+
394
+ x = x.reshape(100, 100)
395
+ assert_allclose(
396
+ _dirichlet_expectation_2d(x),
397
+ psi(x) - psi(np.sum(x, axis=1)[:, np.newaxis]),
398
+ rtol=1e-11,
399
+ atol=3e-9,
400
+ )
401
+
402
+
403
+ def check_verbosity(
404
+ verbose, evaluate_every, expected_lines, expected_perplexities, csr_container
405
+ ):
406
+ n_components, X = _build_sparse_array(csr_container)
407
+ lda = LatentDirichletAllocation(
408
+ n_components=n_components,
409
+ max_iter=3,
410
+ learning_method="batch",
411
+ verbose=verbose,
412
+ evaluate_every=evaluate_every,
413
+ random_state=0,
414
+ )
415
+ out = StringIO()
416
+ old_out, sys.stdout = sys.stdout, out
417
+ try:
418
+ lda.fit(X)
419
+ finally:
420
+ sys.stdout = old_out
421
+
422
+ n_lines = out.getvalue().count("\n")
423
+ n_perplexity = out.getvalue().count("perplexity")
424
+ assert expected_lines == n_lines
425
+ assert expected_perplexities == n_perplexity
426
+
427
+
428
+ @pytest.mark.parametrize(
429
+ "verbose,evaluate_every,expected_lines,expected_perplexities",
430
+ [
431
+ (False, 1, 0, 0),
432
+ (False, 0, 0, 0),
433
+ (True, 0, 3, 0),
434
+ (True, 1, 3, 3),
435
+ (True, 2, 3, 1),
436
+ ],
437
+ )
438
+ @pytest.mark.parametrize("csr_container", CSR_CONTAINERS)
439
+ @pytest.mark.thread_unsafe # manually captured stdout
440
+ def test_verbosity(
441
+ verbose, evaluate_every, expected_lines, expected_perplexities, csr_container
442
+ ):
443
+ check_verbosity(
444
+ verbose, evaluate_every, expected_lines, expected_perplexities, csr_container
445
+ )
446
+
447
+
448
+ @pytest.mark.parametrize("csr_container", CSR_CONTAINERS)
449
+ def test_lda_feature_names_out(csr_container):
450
+ """Check feature names out for LatentDirichletAllocation."""
451
+ n_components, X = _build_sparse_array(csr_container)
452
+ lda = LatentDirichletAllocation(n_components=n_components).fit(X)
453
+
454
+ names = lda.get_feature_names_out()
455
+ assert_array_equal(
456
+ [f"latentdirichletallocation{i}" for i in range(n_components)], names
457
+ )
458
+
459
+
460
+ @pytest.mark.parametrize("learning_method", ("batch", "online"))
461
+ def test_lda_dtype_match(learning_method, global_dtype):
462
+ """Check data type preservation of fitted attributes."""
463
+ rng = np.random.RandomState(0)
464
+ X = rng.uniform(size=(20, 10)).astype(global_dtype, copy=False)
465
+
466
+ lda = LatentDirichletAllocation(
467
+ n_components=5, random_state=0, learning_method=learning_method
468
+ )
469
+ lda.fit(X)
470
+ assert lda.components_.dtype == global_dtype
471
+ assert lda.exp_dirichlet_component_.dtype == global_dtype
472
+
473
+
474
+ @pytest.mark.parametrize("learning_method", ("batch", "online"))
475
+ def test_lda_numerical_consistency(learning_method, global_random_seed):
476
+ """Check numerical consistency between np.float32 and np.float64."""
477
+ rng = np.random.RandomState(global_random_seed)
478
+ X64 = rng.uniform(size=(20, 10))
479
+ X32 = X64.astype(np.float32)
480
+
481
+ lda_64 = LatentDirichletAllocation(
482
+ n_components=5, random_state=global_random_seed, learning_method=learning_method
483
+ ).fit(X64)
484
+ lda_32 = LatentDirichletAllocation(
485
+ n_components=5, random_state=global_random_seed, learning_method=learning_method
486
+ ).fit(X32)
487
+
488
+ assert_allclose(lda_32.components_, lda_64.components_)
489
+ assert_allclose(lda_32.transform(X32), lda_64.transform(X64))