Prompt48 commited on
Commit
ec4b898
·
verified ·
1 Parent(s): 09fc2b2

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

Browse files
edit//Qwen3-TTS-test//.venv//Lib//site-packages//sklearn//decomposition//tests//test_fastica.py ADDED
@@ -0,0 +1,457 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Test the fastica algorithm.
3
+ """
4
+
5
+ import itertools
6
+ import os
7
+ import warnings
8
+
9
+ import numpy as np
10
+ import pytest
11
+ from scipy import stats
12
+
13
+ from sklearn.decomposition import PCA, FastICA, fastica
14
+ from sklearn.decomposition._fastica import _gs_decorrelation
15
+ from sklearn.exceptions import ConvergenceWarning
16
+ from sklearn.utils._testing import assert_allclose, ignore_warnings
17
+
18
+
19
+ def center_and_norm(x, axis=-1):
20
+ """Centers and norms x **in place**
21
+
22
+ Parameters
23
+ -----------
24
+ x: ndarray
25
+ Array with an axis of observations (statistical units) measured on
26
+ random variables.
27
+ axis: int, optional
28
+ Axis along which the mean and variance are calculated.
29
+ """
30
+ x = np.rollaxis(x, axis)
31
+ x -= x.mean(axis=0)
32
+ x /= x.std(axis=0)
33
+
34
+
35
+ def test_gs(global_random_seed):
36
+ # Test gram schmidt orthonormalization
37
+ # generate a random orthogonal matrix
38
+ rng = np.random.RandomState(global_random_seed)
39
+ W, _, _ = np.linalg.svd(rng.randn(10, 10))
40
+ w = rng.randn(10)
41
+ _gs_decorrelation(w, W, 10)
42
+ assert (w**2).sum() < 1.0e-10
43
+ w = rng.randn(10)
44
+ u = _gs_decorrelation(w, W, 5)
45
+ tmp = np.dot(u, W.T)
46
+ assert (tmp[:5] ** 2).sum() < 1.0e-10
47
+
48
+
49
+ def test_fastica_attributes_dtypes(global_dtype):
50
+ rng = np.random.RandomState(0)
51
+ X = rng.random_sample((100, 10)).astype(global_dtype, copy=False)
52
+ fica = FastICA(
53
+ n_components=5, max_iter=1000, whiten="unit-variance", random_state=0
54
+ ).fit(X)
55
+ assert fica.components_.dtype == global_dtype
56
+ assert fica.mixing_.dtype == global_dtype
57
+ assert fica.mean_.dtype == global_dtype
58
+ assert fica.whitening_.dtype == global_dtype
59
+
60
+
61
+ def test_fastica_return_dtypes(global_dtype):
62
+ rng = np.random.RandomState(0)
63
+ X = rng.random_sample((100, 10)).astype(global_dtype, copy=False)
64
+ k_, mixing_, s_ = fastica(
65
+ X, max_iter=1000, whiten="unit-variance", random_state=rng
66
+ )
67
+ assert k_.dtype == global_dtype
68
+ assert mixing_.dtype == global_dtype
69
+ assert s_.dtype == global_dtype
70
+
71
+
72
+ @pytest.mark.parametrize("add_noise", [True, False])
73
+ def test_fastica_simple(add_noise, global_random_seed, global_dtype):
74
+ if (
75
+ global_random_seed == 20
76
+ and global_dtype == np.float32
77
+ and not add_noise
78
+ and os.getenv("DISTRIB") == "ubuntu"
79
+ ):
80
+ pytest.xfail(
81
+ "FastICA instability with Ubuntu Atlas build with float32 "
82
+ "global_dtype. For more details, see "
83
+ "https://github.com/scikit-learn/scikit-learn/issues/24131#issuecomment-1208091119"
84
+ )
85
+
86
+ # Test the FastICA algorithm on very simple data.
87
+ rng = np.random.RandomState(global_random_seed)
88
+ n_samples = 1000
89
+ # Generate two sources:
90
+ s1 = (2 * np.sin(np.linspace(0, 100, n_samples)) > 0) - 1
91
+ s2 = stats.t.rvs(1, size=n_samples, random_state=global_random_seed)
92
+ s = np.c_[s1, s2].T
93
+ center_and_norm(s)
94
+ s = s.astype(global_dtype)
95
+ s1, s2 = s
96
+
97
+ # Mixing angle
98
+ phi = 0.6
99
+ mixing = np.array([[np.cos(phi), np.sin(phi)], [np.sin(phi), -np.cos(phi)]])
100
+ mixing = mixing.astype(global_dtype)
101
+ m = np.dot(mixing, s)
102
+
103
+ if add_noise:
104
+ m += 0.1 * rng.randn(2, 1000)
105
+
106
+ center_and_norm(m)
107
+
108
+ # function as fun arg
109
+ def g_test(x):
110
+ return x**3, (3 * x**2).mean(axis=-1)
111
+
112
+ algos = ["parallel", "deflation"]
113
+ nls = ["logcosh", "exp", "cube", g_test]
114
+ whitening = ["arbitrary-variance", "unit-variance", False]
115
+ for algo, nl, whiten in itertools.product(algos, nls, whitening):
116
+ if whiten:
117
+ k_, mixing_, s_ = fastica(
118
+ m.T, fun=nl, whiten=whiten, algorithm=algo, random_state=rng
119
+ )
120
+ with pytest.raises(ValueError):
121
+ fastica(m.T, fun=np.tanh, whiten=whiten, algorithm=algo)
122
+ else:
123
+ pca = PCA(n_components=2, whiten=True, random_state=rng)
124
+ X = pca.fit_transform(m.T)
125
+ k_, mixing_, s_ = fastica(
126
+ X, fun=nl, algorithm=algo, whiten=False, random_state=rng
127
+ )
128
+ with pytest.raises(ValueError):
129
+ fastica(X, fun=np.tanh, algorithm=algo)
130
+ s_ = s_.T
131
+ # Check that the mixing model described in the docstring holds:
132
+ if whiten:
133
+ # XXX: exact reconstruction to standard relative tolerance is not
134
+ # possible. This is probably expected when add_noise is True but we
135
+ # also need a non-trivial atol in float32 when add_noise is False.
136
+ #
137
+ # Note that the 2 sources are non-Gaussian in this test.
138
+ atol = 1e-5 if global_dtype == np.float32 else 0
139
+ assert_allclose(np.dot(np.dot(mixing_, k_), m), s_, atol=atol)
140
+
141
+ center_and_norm(s_)
142
+ s1_, s2_ = s_
143
+ # Check to see if the sources have been estimated
144
+ # in the wrong order
145
+ if abs(np.dot(s1_, s2)) > abs(np.dot(s1_, s1)):
146
+ s2_, s1_ = s_
147
+ s1_ *= np.sign(np.dot(s1_, s1))
148
+ s2_ *= np.sign(np.dot(s2_, s2))
149
+
150
+ # Check that we have estimated the original sources
151
+ if not add_noise:
152
+ assert_allclose(np.dot(s1_, s1) / n_samples, 1, atol=1e-2)
153
+ assert_allclose(np.dot(s2_, s2) / n_samples, 1, atol=1e-2)
154
+ else:
155
+ assert_allclose(np.dot(s1_, s1) / n_samples, 1, atol=1e-1)
156
+ assert_allclose(np.dot(s2_, s2) / n_samples, 1, atol=1e-1)
157
+
158
+ # Test FastICA class
159
+ _, _, sources_fun = fastica(
160
+ m.T, fun=nl, algorithm=algo, random_state=global_random_seed
161
+ )
162
+ ica = FastICA(fun=nl, algorithm=algo, random_state=global_random_seed)
163
+ sources = ica.fit_transform(m.T)
164
+ assert ica.components_.shape == (2, 2)
165
+ assert sources.shape == (1000, 2)
166
+
167
+ assert_allclose(sources_fun, sources)
168
+ # Set atol to account for the different magnitudes of the elements in sources
169
+ # (from 1e-4 to 1e1).
170
+ atol = np.max(np.abs(sources)) * (1e-5 if global_dtype == np.float32 else 1e-7)
171
+ assert_allclose(sources, ica.transform(m.T), atol=atol)
172
+
173
+ assert ica.mixing_.shape == (2, 2)
174
+
175
+ ica = FastICA(fun=np.tanh, algorithm=algo)
176
+ with pytest.raises(ValueError):
177
+ ica.fit(m.T)
178
+
179
+
180
+ def test_fastica_nowhiten():
181
+ m = [[0, 1], [1, 0]]
182
+
183
+ # test for issue #697
184
+ ica = FastICA(n_components=1, whiten=False, random_state=0)
185
+ warn_msg = "Ignoring n_components with whiten=False."
186
+ with pytest.warns(UserWarning, match=warn_msg):
187
+ ica.fit(m)
188
+ assert hasattr(ica, "mixing_")
189
+
190
+
191
+ def test_fastica_convergence_fail(global_random_seed):
192
+ # Test the FastICA algorithm on very simple data
193
+ # (see test_non_square_fastica).
194
+ # Ensure a ConvergenceWarning raised if the tolerance is sufficiently low.
195
+ rng = np.random.RandomState(global_random_seed)
196
+
197
+ n_samples = 1000
198
+ # Generate two sources:
199
+ t = np.linspace(0, 100, n_samples)
200
+ s1 = np.sin(t)
201
+ s2 = np.ceil(np.sin(np.pi * t))
202
+ s = np.c_[s1, s2].T
203
+ center_and_norm(s)
204
+
205
+ # Mixing matrix
206
+ mixing = rng.randn(6, 2)
207
+ m = np.dot(mixing, s)
208
+
209
+ # Do fastICA with tolerance 0. to ensure failing convergence
210
+ warn_msg = (
211
+ "FastICA did not converge. Consider increasing tolerance "
212
+ "or the maximum number of iterations."
213
+ )
214
+ with pytest.warns(ConvergenceWarning, match=warn_msg):
215
+ ica = FastICA(
216
+ algorithm="parallel", n_components=2, random_state=rng, max_iter=2, tol=0.0
217
+ )
218
+ ica.fit(m.T)
219
+
220
+
221
+ @pytest.mark.parametrize("add_noise", [True, False])
222
+ def test_non_square_fastica(global_random_seed, add_noise):
223
+ # Test the FastICA algorithm on very simple data.
224
+ rng = np.random.RandomState(global_random_seed)
225
+
226
+ n_samples = 1000
227
+ # Generate two sources:
228
+ t = np.linspace(0, 100, n_samples)
229
+ s1 = np.sin(t)
230
+ s2 = np.ceil(np.sin(np.pi * t))
231
+ s = np.c_[s1, s2].T
232
+ center_and_norm(s)
233
+ s1, s2 = s
234
+
235
+ # Mixing matrix
236
+ mixing = rng.randn(6, 2)
237
+ m = np.dot(mixing, s)
238
+
239
+ if add_noise:
240
+ m += 0.1 * rng.randn(6, n_samples)
241
+
242
+ center_and_norm(m)
243
+
244
+ k_, mixing_, s_ = fastica(
245
+ m.T, n_components=2, whiten="unit-variance", random_state=rng
246
+ )
247
+ s_ = s_.T
248
+
249
+ # Check that the mixing model described in the docstring holds:
250
+ assert_allclose(s_, np.dot(np.dot(mixing_, k_), m))
251
+
252
+ center_and_norm(s_)
253
+ s1_, s2_ = s_
254
+ # Check to see if the sources have been estimated
255
+ # in the wrong order
256
+ if abs(np.dot(s1_, s2)) > abs(np.dot(s1_, s1)):
257
+ s2_, s1_ = s_
258
+ s1_ *= np.sign(np.dot(s1_, s1))
259
+ s2_ *= np.sign(np.dot(s2_, s2))
260
+
261
+ # Check that we have estimated the original sources
262
+ if not add_noise:
263
+ assert_allclose(np.dot(s1_, s1) / n_samples, 1, atol=1e-3)
264
+ assert_allclose(np.dot(s2_, s2) / n_samples, 1, atol=1e-3)
265
+
266
+
267
+ def test_fit_transform(global_random_seed, global_dtype):
268
+ """Test unit variance of transformed data using FastICA algorithm.
269
+
270
+ Check that `fit_transform` gives the same result as applying
271
+ `fit` and then `transform`.
272
+
273
+ Bug #13056
274
+ """
275
+ # multivariate uniform data in [0, 1]
276
+ rng = np.random.RandomState(global_random_seed)
277
+ X = rng.random_sample((100, 10)).astype(global_dtype)
278
+ max_iter = 300
279
+ for whiten, n_components in [["unit-variance", 5], [False, None]]:
280
+ n_components_ = n_components if n_components is not None else X.shape[1]
281
+
282
+ ica = FastICA(
283
+ n_components=n_components, max_iter=max_iter, whiten=whiten, random_state=0
284
+ )
285
+ with warnings.catch_warnings():
286
+ # make sure that numerical errors do not cause sqrt of negative
287
+ # values
288
+ warnings.simplefilter("error", RuntimeWarning)
289
+ # XXX: for some seeds, the model does not converge.
290
+ # However this is not what we test here.
291
+ warnings.simplefilter("ignore", ConvergenceWarning)
292
+ Xt = ica.fit_transform(X)
293
+ assert ica.components_.shape == (n_components_, 10)
294
+ assert Xt.shape == (X.shape[0], n_components_)
295
+
296
+ ica2 = FastICA(
297
+ n_components=n_components, max_iter=max_iter, whiten=whiten, random_state=0
298
+ )
299
+ with warnings.catch_warnings():
300
+ # make sure that numerical errors do not cause sqrt of negative
301
+ # values
302
+ warnings.simplefilter("error", RuntimeWarning)
303
+ warnings.simplefilter("ignore", ConvergenceWarning)
304
+ ica2.fit(X)
305
+ assert ica2.components_.shape == (n_components_, 10)
306
+ Xt2 = ica2.transform(X)
307
+
308
+ # XXX: we have to set atol for this test to pass for all seeds when
309
+ # fitting with float32 data. Is this revealing a bug?
310
+ if global_dtype:
311
+ atol = np.abs(Xt2).mean() / 1e6
312
+ else:
313
+ atol = 0.0 # the default rtol is enough for float64 data
314
+ assert_allclose(Xt, Xt2, atol=atol)
315
+
316
+
317
+ @pytest.mark.filterwarnings("ignore:Ignoring n_components with whiten=False.")
318
+ @pytest.mark.parametrize(
319
+ "whiten, n_components, expected_mixing_shape",
320
+ [
321
+ ("arbitrary-variance", 5, (10, 5)),
322
+ ("arbitrary-variance", 10, (10, 10)),
323
+ ("unit-variance", 5, (10, 5)),
324
+ ("unit-variance", 10, (10, 10)),
325
+ (False, 5, (10, 10)),
326
+ (False, 10, (10, 10)),
327
+ ],
328
+ )
329
+ def test_inverse_transform(
330
+ whiten, n_components, expected_mixing_shape, global_random_seed, global_dtype
331
+ ):
332
+ # Test FastICA.inverse_transform
333
+ n_samples = 100
334
+ rng = np.random.RandomState(global_random_seed)
335
+ X = rng.random_sample((n_samples, 10)).astype(global_dtype)
336
+
337
+ ica = FastICA(n_components=n_components, random_state=rng, whiten=whiten)
338
+ with warnings.catch_warnings():
339
+ # For some dataset (depending on the value of global_dtype) the model
340
+ # can fail to converge but this should not impact the definition of
341
+ # a valid inverse transform.
342
+ warnings.simplefilter("ignore", ConvergenceWarning)
343
+ Xt = ica.fit_transform(X)
344
+ assert ica.mixing_.shape == expected_mixing_shape
345
+ X2 = ica.inverse_transform(Xt)
346
+ assert X.shape == X2.shape
347
+
348
+ # reversibility test in non-reduction case
349
+ if n_components == X.shape[1]:
350
+ # XXX: we have to set atol for this test to pass for all seeds when
351
+ # fitting with float32 data. Is this revealing a bug?
352
+ if global_dtype:
353
+ # XXX: dividing by a smaller number makes
354
+ # tests fail for some seeds.
355
+ atol = np.abs(X2).mean() / 1e5
356
+ else:
357
+ atol = 0.0 # the default rtol is enough for float64 data
358
+ assert_allclose(X, X2, atol=atol)
359
+
360
+
361
+ def test_fastica_errors():
362
+ n_features = 3
363
+ n_samples = 10
364
+ rng = np.random.RandomState(0)
365
+ X = rng.random_sample((n_samples, n_features))
366
+ w_init = rng.randn(n_features + 1, n_features + 1)
367
+ with pytest.raises(ValueError, match=r"alpha must be in \[1,2\]"):
368
+ fastica(X, fun_args={"alpha": 0})
369
+ with pytest.raises(
370
+ ValueError, match=r"w_init has invalid shape.+should be \(3L?, 3L?\)"
371
+ ):
372
+ fastica(X, w_init=w_init)
373
+
374
+
375
+ def test_fastica_whiten_unit_variance(global_random_seed):
376
+ """Test unit variance of transformed data using FastICA algorithm.
377
+
378
+ Bug #13056
379
+ """
380
+ rng = np.random.RandomState(global_random_seed)
381
+ X = rng.random_sample((100, 10))
382
+ n_components = X.shape[1]
383
+ ica = FastICA(n_components=n_components, whiten="unit-variance", random_state=0)
384
+ Xt = ica.fit_transform(X)
385
+
386
+ assert np.var(Xt) == pytest.approx(1.0)
387
+
388
+
389
+ @pytest.mark.parametrize("whiten", ["arbitrary-variance", "unit-variance", False])
390
+ @pytest.mark.parametrize("return_X_mean", [True, False])
391
+ @pytest.mark.parametrize("return_n_iter", [True, False])
392
+ def test_fastica_output_shape(whiten, return_X_mean, return_n_iter):
393
+ n_features = 3
394
+ n_samples = 10
395
+ rng = np.random.RandomState(0)
396
+ X = rng.random_sample((n_samples, n_features))
397
+
398
+ expected_len = 3 + return_X_mean + return_n_iter
399
+
400
+ out = fastica(
401
+ X, whiten=whiten, return_n_iter=return_n_iter, return_X_mean=return_X_mean
402
+ )
403
+
404
+ assert len(out) == expected_len
405
+ if not whiten:
406
+ assert out[0] is None
407
+
408
+
409
+ @pytest.mark.parametrize("add_noise", [True, False])
410
+ def test_fastica_simple_different_solvers(add_noise, global_random_seed):
411
+ """Test FastICA is consistent between whiten_solvers."""
412
+ rng = np.random.RandomState(global_random_seed)
413
+ n_samples = 1000
414
+ # Generate two sources:
415
+ s1 = (2 * np.sin(np.linspace(0, 100, n_samples)) > 0) - 1
416
+ s2 = stats.t.rvs(1, size=n_samples, random_state=rng)
417
+ s = np.c_[s1, s2].T
418
+ center_and_norm(s)
419
+ s1, s2 = s
420
+
421
+ # Mixing angle
422
+ phi = rng.rand() * 2 * np.pi
423
+ mixing = np.array([[np.cos(phi), np.sin(phi)], [np.sin(phi), -np.cos(phi)]])
424
+ m = np.dot(mixing, s)
425
+
426
+ if add_noise:
427
+ m += 0.1 * rng.randn(2, 1000)
428
+
429
+ center_and_norm(m)
430
+
431
+ outs = {}
432
+ for solver in ("svd", "eigh"):
433
+ ica = FastICA(random_state=0, whiten="unit-variance", whiten_solver=solver)
434
+ sources = ica.fit_transform(m.T)
435
+ outs[solver] = sources
436
+ assert ica.components_.shape == (2, 2)
437
+ assert sources.shape == (1000, 2)
438
+
439
+ # compared numbers are not all on the same magnitude. Using a small atol to
440
+ # make the test less brittle
441
+ assert_allclose(outs["eigh"], outs["svd"], atol=1e-12)
442
+
443
+
444
+ def test_fastica_eigh_low_rank_warning(global_random_seed):
445
+ """Test FastICA eigh solver raises warning for low-rank data."""
446
+ rng = np.random.RandomState(global_random_seed)
447
+ A = rng.randn(10, 2)
448
+ X = A @ A.T
449
+ ica = FastICA(random_state=0, whiten="unit-variance", whiten_solver="eigh")
450
+ msg = "There are some small singular values"
451
+
452
+ with pytest.warns(UserWarning, match=msg):
453
+ with ignore_warnings(category=ConvergenceWarning):
454
+ # The FastICA solver may not converge for some data with specific
455
+ # random seeds but this happens after the whiten step so this is
456
+ # not want we want to test here.
457
+ ica.fit(X)