Prompt48 commited on
Commit
4489f8b
·
verified ·
1 Parent(s): 8e7f21b

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

Browse files
edit//Qwen3-TTS-test//.venv//Lib//site-packages//sklearn//decomposition//tests//test_sparse_pca.py ADDED
@@ -0,0 +1,350 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Authors: The scikit-learn developers
2
+ # SPDX-License-Identifier: BSD-3-Clause
3
+
4
+
5
+ import numpy as np
6
+ import pytest
7
+ from numpy.testing import assert_array_equal
8
+
9
+ from sklearn.datasets import make_low_rank_matrix
10
+ from sklearn.decomposition import PCA, MiniBatchSparsePCA, SparsePCA
11
+ from sklearn.utils import check_random_state
12
+ from sklearn.utils._testing import (
13
+ assert_allclose,
14
+ assert_array_almost_equal,
15
+ if_safe_multiprocessing_with_blas,
16
+ )
17
+ from sklearn.utils.extmath import svd_flip
18
+
19
+
20
+ def generate_toy_data(n_components, n_samples, image_size, random_state=None):
21
+ n_features = image_size[0] * image_size[1]
22
+
23
+ rng = check_random_state(random_state)
24
+ U = rng.randn(n_samples, n_components)
25
+ V = rng.randn(n_components, n_features)
26
+
27
+ centers = [(3, 3), (6, 7), (8, 1)]
28
+ sz = [1, 2, 1]
29
+ for k in range(n_components):
30
+ img = np.zeros(image_size)
31
+ xmin, xmax = centers[k][0] - sz[k], centers[k][0] + sz[k]
32
+ ymin, ymax = centers[k][1] - sz[k], centers[k][1] + sz[k]
33
+ img[xmin:xmax][:, ymin:ymax] = 1.0
34
+ V[k, :] = img.ravel()
35
+
36
+ # Y is defined by : Y = UV + noise
37
+ Y = np.dot(U, V)
38
+ Y += 0.1 * rng.randn(Y.shape[0], Y.shape[1]) # Add noise
39
+ return Y, U, V
40
+
41
+
42
+ # SparsePCA can be a bit slow. To avoid having test times go up, we
43
+ # test different aspects of the code in the same test
44
+
45
+
46
+ def test_correct_shapes():
47
+ rng = np.random.RandomState(0)
48
+ X = rng.randn(12, 10)
49
+ spca = SparsePCA(n_components=8, random_state=rng)
50
+ U = spca.fit_transform(X)
51
+ assert spca.components_.shape == (8, 10)
52
+ assert U.shape == (12, 8)
53
+ # test overcomplete decomposition
54
+ spca = SparsePCA(n_components=13, random_state=rng)
55
+ U = spca.fit_transform(X)
56
+ assert spca.components_.shape == (13, 10)
57
+ assert U.shape == (12, 13)
58
+
59
+
60
+ def test_fit_transform(global_random_seed):
61
+ alpha = 1
62
+ rng = np.random.RandomState(global_random_seed)
63
+ Y, _, _ = generate_toy_data(3, 10, (8, 8), random_state=rng) # wide array
64
+ spca_lars = SparsePCA(
65
+ n_components=3, method="lars", alpha=alpha, random_state=global_random_seed
66
+ )
67
+ spca_lars.fit(Y)
68
+
69
+ # Test that CD gives similar results
70
+ spca_lasso = SparsePCA(
71
+ n_components=3, method="cd", random_state=global_random_seed, alpha=alpha
72
+ )
73
+ spca_lasso.fit(Y)
74
+ assert_allclose(spca_lasso.components_, spca_lars.components_, rtol=5e-4, atol=2e-4)
75
+
76
+
77
+ # TODO: remove mark once loky bug is fixed:
78
+ # https://github.com/joblib/loky/issues/458
79
+ @pytest.mark.thread_unsafe
80
+ @if_safe_multiprocessing_with_blas
81
+ def test_fit_transform_parallel(global_random_seed):
82
+ alpha = 1
83
+ rng = np.random.RandomState(global_random_seed)
84
+ Y, _, _ = generate_toy_data(3, 10, (8, 8), random_state=rng) # wide array
85
+ spca_lars = SparsePCA(
86
+ n_components=3, method="lars", alpha=alpha, random_state=global_random_seed
87
+ )
88
+ spca_lars.fit(Y)
89
+ U1 = spca_lars.transform(Y)
90
+ # Test multiple CPUs
91
+ spca = SparsePCA(
92
+ n_components=3,
93
+ n_jobs=2,
94
+ method="lars",
95
+ alpha=alpha,
96
+ random_state=global_random_seed,
97
+ ).fit(Y)
98
+ U2 = spca.transform(Y)
99
+ assert not np.all(spca_lars.components_ == 0)
100
+ assert_array_almost_equal(U1, U2)
101
+
102
+
103
+ def test_transform_nan(global_random_seed):
104
+ # Test that SparsePCA won't return NaN when there is 0 feature in all
105
+ # samples.
106
+ rng = np.random.RandomState(global_random_seed)
107
+ Y, _, _ = generate_toy_data(3, 10, (8, 8), random_state=rng) # wide array
108
+ Y[:, 0] = 0
109
+ estimator = SparsePCA(n_components=8, random_state=global_random_seed)
110
+ assert not np.any(np.isnan(estimator.fit_transform(Y)))
111
+
112
+
113
+ def test_fit_transform_tall(global_random_seed):
114
+ rng = np.random.RandomState(global_random_seed)
115
+ Y, _, _ = generate_toy_data(3, 65, (8, 8), random_state=rng) # tall array
116
+ spca_lars = SparsePCA(n_components=3, method="lars", random_state=rng)
117
+ U1 = spca_lars.fit_transform(Y)
118
+ spca_lasso = SparsePCA(n_components=3, method="cd", random_state=rng)
119
+ U2 = spca_lasso.fit(Y).transform(Y)
120
+ assert_allclose(U1, U2, rtol=1e-4, atol=2e-5)
121
+
122
+
123
+ def test_initialization(global_random_seed):
124
+ rng = np.random.RandomState(global_random_seed)
125
+ U_init = rng.randn(5, 3)
126
+ V_init = rng.randn(3, 4)
127
+ model = SparsePCA(
128
+ n_components=3, U_init=U_init, V_init=V_init, max_iter=0, random_state=rng
129
+ )
130
+ model.fit(rng.randn(5, 4))
131
+
132
+ expected_components = V_init / np.linalg.norm(V_init, axis=1, keepdims=True)
133
+ expected_components = svd_flip(u=expected_components.T, v=None)[0].T
134
+ assert_allclose(model.components_, expected_components)
135
+
136
+
137
+ def test_mini_batch_correct_shapes():
138
+ rng = np.random.RandomState(0)
139
+ X = rng.randn(12, 10)
140
+ pca = MiniBatchSparsePCA(n_components=8, max_iter=1, random_state=rng)
141
+ U = pca.fit_transform(X)
142
+ assert pca.components_.shape == (8, 10)
143
+ assert U.shape == (12, 8)
144
+ # test overcomplete decomposition
145
+ pca = MiniBatchSparsePCA(n_components=13, max_iter=1, random_state=rng)
146
+ U = pca.fit_transform(X)
147
+ assert pca.components_.shape == (13, 10)
148
+ assert U.shape == (12, 13)
149
+
150
+
151
+ def test_scaling_fit_transform(global_random_seed):
152
+ alpha = 1
153
+ rng = np.random.RandomState(global_random_seed)
154
+ Y, _, _ = generate_toy_data(3, 1000, (8, 8), random_state=rng)
155
+ spca_lars = SparsePCA(n_components=3, method="lars", alpha=alpha, random_state=rng)
156
+ results_train = spca_lars.fit_transform(Y)
157
+ results_test = spca_lars.transform(Y[:10])
158
+ assert_allclose(results_train[0], results_test[0])
159
+
160
+
161
+ def test_pca_vs_spca(global_random_seed):
162
+ rng = np.random.RandomState(global_random_seed)
163
+ Y, _, _ = generate_toy_data(3, 1000, (8, 8), random_state=rng)
164
+ Z, _, _ = generate_toy_data(3, 10, (8, 8), random_state=rng)
165
+ spca = SparsePCA(alpha=0, ridge_alpha=0, n_components=2, random_state=rng)
166
+ pca = PCA(n_components=2, random_state=rng)
167
+ pca.fit(Y)
168
+ spca.fit(Y)
169
+ results_test_pca = pca.transform(Z)
170
+ results_test_spca = spca.transform(Z)
171
+ assert_allclose(
172
+ np.abs(spca.components_.dot(pca.components_.T)), np.eye(2), atol=1e-4
173
+ )
174
+ results_test_pca *= np.sign(results_test_pca[0, :])
175
+ results_test_spca *= np.sign(results_test_spca[0, :])
176
+ assert_allclose(results_test_pca, results_test_spca, atol=1e-4)
177
+
178
+
179
+ @pytest.mark.parametrize("SPCA", [SparsePCA, MiniBatchSparsePCA])
180
+ @pytest.mark.parametrize("n_components", [None, 3])
181
+ def test_spca_n_components_(SPCA, n_components):
182
+ rng = np.random.RandomState(0)
183
+ n_samples, n_features = 12, 10
184
+ X = rng.randn(n_samples, n_features)
185
+
186
+ model = SPCA(n_components=n_components).fit(X)
187
+
188
+ if n_components is not None:
189
+ assert model.n_components_ == n_components
190
+ else:
191
+ assert model.n_components_ == n_features
192
+
193
+
194
+ @pytest.mark.parametrize("SPCA", (SparsePCA, MiniBatchSparsePCA))
195
+ @pytest.mark.parametrize("method", ("lars", "cd"))
196
+ @pytest.mark.parametrize(
197
+ "data_type, expected_type",
198
+ (
199
+ (np.float32, np.float32),
200
+ (np.float64, np.float64),
201
+ (np.int32, np.float64),
202
+ (np.int64, np.float64),
203
+ ),
204
+ )
205
+ def test_sparse_pca_dtype_match(SPCA, method, data_type, expected_type):
206
+ # Verify output matrix dtype
207
+ n_samples, n_features, n_components = 12, 10, 3
208
+ rng = np.random.RandomState(0)
209
+ input_array = rng.randn(n_samples, n_features).astype(data_type)
210
+ model = SPCA(n_components=n_components, method=method)
211
+ transformed = model.fit_transform(input_array)
212
+
213
+ assert transformed.dtype == expected_type
214
+ assert model.components_.dtype == expected_type
215
+
216
+
217
+ @pytest.mark.parametrize("SPCA", (SparsePCA, MiniBatchSparsePCA))
218
+ @pytest.mark.parametrize("method", ("lars", "cd"))
219
+ def test_sparse_pca_numerical_consistency(SPCA, method, global_random_seed):
220
+ # Verify numericall consistentency among np.float32 and np.float64
221
+ n_samples, n_features, n_components = 20, 20, 5
222
+ input_array = make_low_rank_matrix(
223
+ n_samples=n_samples,
224
+ n_features=n_features,
225
+ effective_rank=n_components,
226
+ random_state=global_random_seed,
227
+ )
228
+
229
+ model_32 = SPCA(
230
+ n_components=n_components,
231
+ method=method,
232
+ random_state=global_random_seed,
233
+ )
234
+ transformed_32 = model_32.fit_transform(input_array.astype(np.float32))
235
+
236
+ model_64 = SPCA(
237
+ n_components=n_components,
238
+ method=method,
239
+ random_state=global_random_seed,
240
+ )
241
+ transformed_64 = model_64.fit_transform(input_array.astype(np.float64))
242
+ assert_allclose(transformed_64, transformed_32)
243
+ assert_allclose(model_64.components_, model_32.components_)
244
+
245
+
246
+ @pytest.mark.parametrize("SPCA", [SparsePCA, MiniBatchSparsePCA])
247
+ def test_spca_feature_names_out(SPCA):
248
+ """Check feature names out for *SparsePCA."""
249
+ rng = np.random.RandomState(0)
250
+ n_samples, n_features = 12, 10
251
+ X = rng.randn(n_samples, n_features)
252
+
253
+ model = SPCA(n_components=4).fit(X)
254
+ names = model.get_feature_names_out()
255
+
256
+ estimator_name = SPCA.__name__.lower()
257
+ assert_array_equal([f"{estimator_name}{i}" for i in range(4)], names)
258
+
259
+
260
+ def test_spca_early_stopping(global_random_seed):
261
+ """Check that `tol` and `max_no_improvement` act as early stopping."""
262
+ rng = np.random.RandomState(global_random_seed)
263
+ n_samples, n_features = 50, 10
264
+ X = rng.randn(n_samples, n_features)
265
+
266
+ # vary the tolerance to force the early stopping of one of the model
267
+ model_early_stopped = MiniBatchSparsePCA(
268
+ max_iter=100, tol=0.5, random_state=global_random_seed
269
+ ).fit(X)
270
+ model_not_early_stopped = MiniBatchSparsePCA(
271
+ max_iter=100, tol=1e-3, random_state=global_random_seed
272
+ ).fit(X)
273
+ assert model_early_stopped.n_iter_ < model_not_early_stopped.n_iter_
274
+
275
+ # force the max number of no improvement to a large value to check that
276
+ # it does help to early stop
277
+ model_early_stopped = MiniBatchSparsePCA(
278
+ max_iter=100, tol=1e-6, max_no_improvement=2, random_state=global_random_seed
279
+ ).fit(X)
280
+ model_not_early_stopped = MiniBatchSparsePCA(
281
+ max_iter=100, tol=1e-6, max_no_improvement=100, random_state=global_random_seed
282
+ ).fit(X)
283
+ assert model_early_stopped.n_iter_ < model_not_early_stopped.n_iter_
284
+
285
+
286
+ def test_equivalence_components_pca_spca(global_random_seed):
287
+ """Check the equivalence of the components found by PCA and SparsePCA.
288
+
289
+ Non-regression test for:
290
+ https://github.com/scikit-learn/scikit-learn/issues/23932
291
+ """
292
+ rng = np.random.RandomState(global_random_seed)
293
+ X = rng.randn(50, 4)
294
+
295
+ n_components = 2
296
+ pca = PCA(
297
+ n_components=n_components,
298
+ svd_solver="randomized",
299
+ random_state=0,
300
+ ).fit(X)
301
+ spca = SparsePCA(
302
+ n_components=n_components,
303
+ method="lars",
304
+ ridge_alpha=0,
305
+ alpha=0,
306
+ random_state=0,
307
+ ).fit(X)
308
+
309
+ assert_allclose(pca.components_, spca.components_)
310
+
311
+
312
+ def test_sparse_pca_inverse_transform(global_random_seed):
313
+ """Check that `inverse_transform` in `SparsePCA` and `PCA` are similar."""
314
+ rng = np.random.RandomState(global_random_seed)
315
+ n_samples, n_features = 10, 5
316
+ X = rng.randn(n_samples, n_features)
317
+
318
+ n_components = 2
319
+ spca = SparsePCA(
320
+ n_components=n_components,
321
+ alpha=1e-12,
322
+ ridge_alpha=1e-12,
323
+ random_state=global_random_seed,
324
+ )
325
+ pca = PCA(n_components=n_components, random_state=global_random_seed)
326
+ X_trans_spca = spca.fit_transform(X)
327
+ X_trans_pca = pca.fit_transform(X)
328
+ assert_allclose(
329
+ spca.inverse_transform(X_trans_spca), pca.inverse_transform(X_trans_pca)
330
+ )
331
+
332
+
333
+ @pytest.mark.parametrize("SPCA", [SparsePCA, MiniBatchSparsePCA])
334
+ def test_transform_inverse_transform_round_trip(SPCA, global_random_seed):
335
+ """Check the `transform` and `inverse_transform` round trip with no loss of
336
+ information.
337
+ """
338
+ rng = np.random.RandomState(global_random_seed)
339
+ n_samples, n_features = 10, 5
340
+ X = rng.randn(n_samples, n_features)
341
+
342
+ n_components = n_features
343
+ spca = SPCA(
344
+ n_components=n_components,
345
+ alpha=1e-12,
346
+ ridge_alpha=1e-12,
347
+ random_state=global_random_seed,
348
+ )
349
+ X_trans_spca = spca.fit_transform(X)
350
+ assert_allclose(spca.inverse_transform(X_trans_spca), X)