jasonfan commited on
Commit
1ac6505
·
verified ·
1 Parent(s): b0ffd55

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. miniconda3/envs/active_proaction/lib/python3.10/site-packages/sklearn/datasets/descr/linnerud.rst +24 -0
  2. miniconda3/envs/active_proaction/lib/python3.10/site-packages/sklearn/datasets/descr/olivetti_faces.rst +44 -0
  3. miniconda3/envs/active_proaction/lib/python3.10/site-packages/sklearn/datasets/descr/rcv1.rst +72 -0
  4. miniconda3/envs/active_proaction/lib/python3.10/site-packages/sklearn/datasets/descr/species_distributions.rst +40 -0
  5. miniconda3/envs/active_proaction/lib/python3.10/site-packages/sklearn/datasets/descr/twenty_newsgroups.rst +248 -0
  6. miniconda3/envs/active_proaction/lib/python3.10/site-packages/sklearn/datasets/descr/wine_data.rst +94 -0
  7. miniconda3/envs/active_proaction/lib/python3.10/site-packages/sklearn/datasets/images/README.txt +18 -0
  8. miniconda3/envs/active_proaction/lib/python3.10/site-packages/sklearn/datasets/images/__init__.py +2 -0
  9. miniconda3/envs/active_proaction/lib/python3.10/site-packages/sklearn/datasets/tests/__init__.py +0 -0
  10. miniconda3/envs/active_proaction/lib/python3.10/site-packages/sklearn/datasets/tests/data/__init__.py +0 -0
  11. miniconda3/envs/active_proaction/lib/python3.10/site-packages/sklearn/datasets/tests/data/openml/__init__.py +0 -0
  12. miniconda3/envs/active_proaction/lib/python3.10/site-packages/sklearn/datasets/tests/data/openml/id_1/__init__.py +0 -0
  13. miniconda3/envs/active_proaction/lib/python3.10/site-packages/sklearn/datasets/tests/data/openml/id_1119/__init__.py +0 -0
  14. miniconda3/envs/active_proaction/lib/python3.10/site-packages/sklearn/datasets/tests/data/openml/id_1590/__init__.py +0 -0
  15. miniconda3/envs/active_proaction/lib/python3.10/site-packages/sklearn/datasets/tests/data/openml/id_2/__init__.py +0 -0
  16. miniconda3/envs/active_proaction/lib/python3.10/site-packages/sklearn/datasets/tests/data/openml/id_292/__init__.py +0 -0
  17. miniconda3/envs/active_proaction/lib/python3.10/site-packages/sklearn/datasets/tests/data/openml/id_3/__init__.py +0 -0
  18. miniconda3/envs/active_proaction/lib/python3.10/site-packages/sklearn/datasets/tests/data/openml/id_40589/__init__.py +0 -0
  19. miniconda3/envs/active_proaction/lib/python3.10/site-packages/sklearn/datasets/tests/data/openml/id_40675/__init__.py +0 -0
  20. miniconda3/envs/active_proaction/lib/python3.10/site-packages/sklearn/datasets/tests/data/openml/id_40945/__init__.py +0 -0
  21. miniconda3/envs/active_proaction/lib/python3.10/site-packages/sklearn/datasets/tests/data/openml/id_40966/__init__.py +0 -0
  22. miniconda3/envs/active_proaction/lib/python3.10/site-packages/sklearn/datasets/tests/data/openml/id_42074/__init__.py +0 -0
  23. miniconda3/envs/active_proaction/lib/python3.10/site-packages/sklearn/datasets/tests/data/openml/id_42585/__init__.py +0 -0
  24. miniconda3/envs/active_proaction/lib/python3.10/site-packages/sklearn/datasets/tests/data/openml/id_561/__init__.py +0 -0
  25. miniconda3/envs/active_proaction/lib/python3.10/site-packages/sklearn/datasets/tests/data/openml/id_61/__init__.py +0 -0
  26. miniconda3/envs/active_proaction/lib/python3.10/site-packages/sklearn/datasets/tests/data/openml/id_62/__init__.py +0 -0
  27. miniconda3/envs/active_proaction/lib/python3.10/site-packages/sklearn/datasets/tests/data/svmlight_classification.txt +9 -0
  28. miniconda3/envs/active_proaction/lib/python3.10/site-packages/sklearn/datasets/tests/data/svmlight_invalid.txt +3 -0
  29. miniconda3/envs/active_proaction/lib/python3.10/site-packages/sklearn/datasets/tests/data/svmlight_invalid_order.txt +1 -0
  30. miniconda3/envs/active_proaction/lib/python3.10/site-packages/sklearn/datasets/tests/data/svmlight_multilabel.txt +5 -0
  31. miniconda3/envs/active_proaction/lib/python3.10/site-packages/sklearn/datasets/tests/test_20news.py +143 -0
  32. miniconda3/envs/active_proaction/lib/python3.10/site-packages/sklearn/datasets/tests/test_arff_parser.py +284 -0
  33. miniconda3/envs/active_proaction/lib/python3.10/site-packages/sklearn/datasets/tests/test_base.py +658 -0
  34. miniconda3/envs/active_proaction/lib/python3.10/site-packages/sklearn/datasets/tests/test_california_housing.py +38 -0
  35. miniconda3/envs/active_proaction/lib/python3.10/site-packages/sklearn/datasets/tests/test_common.py +136 -0
  36. miniconda3/envs/active_proaction/lib/python3.10/site-packages/sklearn/datasets/tests/test_covtype.py +55 -0
  37. miniconda3/envs/active_proaction/lib/python3.10/site-packages/sklearn/datasets/tests/test_kddcup99.py +89 -0
  38. miniconda3/envs/active_proaction/lib/python3.10/site-packages/sklearn/datasets/tests/test_lfw.py +229 -0
  39. miniconda3/envs/active_proaction/lib/python3.10/site-packages/sklearn/datasets/tests/test_olivetti_faces.py +26 -0
  40. miniconda3/envs/active_proaction/lib/python3.10/site-packages/sklearn/datasets/tests/test_openml.py +1636 -0
  41. miniconda3/envs/active_proaction/lib/python3.10/site-packages/sklearn/datasets/tests/test_rcv1.py +71 -0
  42. miniconda3/envs/active_proaction/lib/python3.10/site-packages/sklearn/datasets/tests/test_samples_generator.py +744 -0
  43. miniconda3/envs/active_proaction/lib/python3.10/site-packages/sklearn/datasets/tests/test_svmlight_format.py +613 -0
  44. miniconda3/envs/active_proaction/lib/python3.10/site-packages/sklearn/decomposition/__init__.py +54 -0
  45. miniconda3/envs/active_proaction/lib/python3.10/site-packages/sklearn/decomposition/_base.py +202 -0
  46. miniconda3/envs/active_proaction/lib/python3.10/site-packages/sklearn/decomposition/_cdnmf_fast.pyx +38 -0
  47. miniconda3/envs/active_proaction/lib/python3.10/site-packages/sklearn/decomposition/_dict_learning.py +2329 -0
  48. miniconda3/envs/active_proaction/lib/python3.10/site-packages/sklearn/decomposition/_factor_analysis.py +457 -0
  49. miniconda3/envs/active_proaction/lib/python3.10/site-packages/sklearn/decomposition/_fastica.py +804 -0
  50. miniconda3/envs/active_proaction/lib/python3.10/site-packages/sklearn/decomposition/_incremental_pca.py +426 -0
miniconda3/envs/active_proaction/lib/python3.10/site-packages/sklearn/datasets/descr/linnerud.rst ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .. _linnerrud_dataset:
2
+
3
+ Linnerrud dataset
4
+ -----------------
5
+
6
+ **Data Set Characteristics:**
7
+
8
+ :Number of Instances: 20
9
+ :Number of Attributes: 3
10
+ :Missing Attribute Values: None
11
+
12
+ The Linnerud dataset is a multi-output regression dataset. It consists of three
13
+ exercise (data) and three physiological (target) variables collected from
14
+ twenty middle-aged men in a fitness club:
15
+
16
+ - *physiological* - CSV containing 20 observations on 3 physiological variables:
17
+ Weight, Waist and Pulse.
18
+ - *exercise* - CSV containing 20 observations on 3 exercise variables:
19
+ Chins, Situps and Jumps.
20
+
21
+ .. dropdown:: References
22
+
23
+ * Tenenhaus, M. (1998). La regression PLS: theorie et pratique. Paris:
24
+ Editions Technic.
miniconda3/envs/active_proaction/lib/python3.10/site-packages/sklearn/datasets/descr/olivetti_faces.rst ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .. _olivetti_faces_dataset:
2
+
3
+ The Olivetti faces dataset
4
+ --------------------------
5
+
6
+ `This dataset contains a set of face images`_ taken between April 1992 and
7
+ April 1994 at AT&T Laboratories Cambridge. The
8
+ :func:`sklearn.datasets.fetch_olivetti_faces` function is the data
9
+ fetching / caching function that downloads the data
10
+ archive from AT&T.
11
+
12
+ .. _This dataset contains a set of face images: https://cam-orl.co.uk/facedatabase.html
13
+
14
+ As described on the original website:
15
+
16
+ There are ten different images of each of 40 distinct subjects. For some
17
+ subjects, the images were taken at different times, varying the lighting,
18
+ facial expressions (open / closed eyes, smiling / not smiling) and facial
19
+ details (glasses / no glasses). All the images were taken against a dark
20
+ homogeneous background with the subjects in an upright, frontal position
21
+ (with tolerance for some side movement).
22
+
23
+ **Data Set Characteristics:**
24
+
25
+ ================= =====================
26
+ Classes 40
27
+ Samples total 400
28
+ Dimensionality 4096
29
+ Features real, between 0 and 1
30
+ ================= =====================
31
+
32
+ The image is quantized to 256 grey levels and stored as unsigned 8-bit
33
+ integers; the loader will convert these to floating point values on the
34
+ interval [0, 1], which are easier to work with for many algorithms.
35
+
36
+ The "target" for this database is an integer from 0 to 39 indicating the
37
+ identity of the person pictured; however, with only 10 examples per class, this
38
+ relatively small dataset is more interesting from an unsupervised or
39
+ semi-supervised perspective.
40
+
41
+ The original dataset consisted of 92 x 112, while the version available here
42
+ consists of 64x64 images.
43
+
44
+ When using these images, please give credit to AT&T Laboratories Cambridge.
miniconda3/envs/active_proaction/lib/python3.10/site-packages/sklearn/datasets/descr/rcv1.rst ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .. _rcv1_dataset:
2
+
3
+ RCV1 dataset
4
+ ------------
5
+
6
+ Reuters Corpus Volume I (RCV1) is an archive of over 800,000 manually
7
+ categorized newswire stories made available by Reuters, Ltd. for research
8
+ purposes. The dataset is extensively described in [1]_.
9
+
10
+ **Data Set Characteristics:**
11
+
12
+ ============== =====================
13
+ Classes 103
14
+ Samples total 804414
15
+ Dimensionality 47236
16
+ Features real, between 0 and 1
17
+ ============== =====================
18
+
19
+ :func:`sklearn.datasets.fetch_rcv1` will load the following
20
+ version: RCV1-v2, vectors, full sets, topics multilabels::
21
+
22
+ >>> from sklearn.datasets import fetch_rcv1
23
+ >>> rcv1 = fetch_rcv1()
24
+
25
+ It returns a dictionary-like object, with the following attributes:
26
+
27
+ ``data``:
28
+ The feature matrix is a scipy CSR sparse matrix, with 804414 samples and
29
+ 47236 features. Non-zero values contains cosine-normalized, log TF-IDF vectors.
30
+ A nearly chronological split is proposed in [1]_: The first 23149 samples are
31
+ the training set. The last 781265 samples are the testing set. This follows
32
+ the official LYRL2004 chronological split. The array has 0.16% of non zero
33
+ values::
34
+
35
+ >>> rcv1.data.shape
36
+ (804414, 47236)
37
+
38
+ ``target``:
39
+ The target values are stored in a scipy CSR sparse matrix, with 804414 samples
40
+ and 103 categories. Each sample has a value of 1 in its categories, and 0 in
41
+ others. The array has 3.15% of non zero values::
42
+
43
+ >>> rcv1.target.shape
44
+ (804414, 103)
45
+
46
+ ``sample_id``:
47
+ Each sample can be identified by its ID, ranging (with gaps) from 2286
48
+ to 810596::
49
+
50
+ >>> rcv1.sample_id[:3]
51
+ array([2286, 2287, 2288], dtype=uint32)
52
+
53
+ ``target_names``:
54
+ The target values are the topics of each sample. Each sample belongs to at
55
+ least one topic, and to up to 17 topics. There are 103 topics, each
56
+ represented by a string. Their corpus frequencies span five orders of
57
+ magnitude, from 5 occurrences for 'GMIL', to 381327 for 'CCAT'::
58
+
59
+ >>> rcv1.target_names[:3].tolist() # doctest: +SKIP
60
+ ['E11', 'ECAT', 'M11']
61
+
62
+ The dataset will be downloaded from the `rcv1 homepage`_ if necessary.
63
+ The compressed size is about 656 MB.
64
+
65
+ .. _rcv1 homepage: http://jmlr.csail.mit.edu/papers/volume5/lewis04a/
66
+
67
+
68
+ .. rubric:: References
69
+
70
+ .. [1] Lewis, D. D., Yang, Y., Rose, T. G., & Li, F. (2004).
71
+ RCV1: A new benchmark collection for text categorization research.
72
+ The Journal of Machine Learning Research, 5, 361-397.
miniconda3/envs/active_proaction/lib/python3.10/site-packages/sklearn/datasets/descr/species_distributions.rst ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .. _species_distribution_dataset:
2
+
3
+ Species distribution dataset
4
+ ----------------------------
5
+
6
+ This dataset represents the geographic distribution of two species in Central and
7
+ South America. The two species are:
8
+
9
+ - `"Bradypus variegatus" <http://www.iucnredlist.org/details/3038/0>`_ ,
10
+ the Brown-throated Sloth.
11
+
12
+ - `"Microryzomys minutus" <http://www.iucnredlist.org/details/13408/0>`_ ,
13
+ also known as the Forest Small Rice Rat, a rodent that lives in Peru,
14
+ Colombia, Ecuador, Peru, and Venezuela.
15
+
16
+ The dataset is not a typical dataset since a :class:`~sklearn.datasets.base.Bunch`
17
+ containing the attributes `data` and `target` is not returned. Instead, we have
18
+ information allowing to create a "density" map of the different species.
19
+
20
+ The grid for the map can be built using the attributes `x_left_lower_corner`,
21
+ `y_left_lower_corner`, `Nx`, `Ny` and `grid_size`, which respectively correspond
22
+ to the x and y coordinates of the lower left corner of the grid, the number of
23
+ points along the x- and y-axis and the size of the step on the grid.
24
+
25
+ The density at each location of the grid is contained in the `coverage` attribute.
26
+
27
+ Finally, the `train` and `test` attributes contain information regarding the location
28
+ of a species at a specific location.
29
+
30
+ The dataset is provided by Phillips et. al. (2006).
31
+
32
+ .. rubric:: References
33
+
34
+ * `"Maximum entropy modeling of species geographic distributions"
35
+ <http://rob.schapire.net/papers/ecolmod.pdf>`_ S. J. Phillips,
36
+ R. P. Anderson, R. E. Schapire - Ecological Modelling, 190:231-259, 2006.
37
+
38
+ .. rubric:: Examples
39
+
40
+ * :ref:`sphx_glr_auto_examples_applications_plot_species_distribution_modeling.py`
miniconda3/envs/active_proaction/lib/python3.10/site-packages/sklearn/datasets/descr/twenty_newsgroups.rst ADDED
@@ -0,0 +1,248 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .. _20newsgroups_dataset:
2
+
3
+ The 20 newsgroups text dataset
4
+ ------------------------------
5
+
6
+ The 20 newsgroups dataset comprises around 18000 newsgroups posts on
7
+ 20 topics split in two subsets: one for training (or development)
8
+ and the other one for testing (or for performance evaluation). The split
9
+ between the train and test set is based upon a messages posted before
10
+ and after a specific date.
11
+
12
+ This module contains two loaders. The first one,
13
+ :func:`sklearn.datasets.fetch_20newsgroups`,
14
+ returns a list of the raw texts that can be fed to text feature
15
+ extractors such as :class:`~sklearn.feature_extraction.text.CountVectorizer`
16
+ with custom parameters so as to extract feature vectors.
17
+ The second one, :func:`sklearn.datasets.fetch_20newsgroups_vectorized`,
18
+ returns ready-to-use features, i.e., it is not necessary to use a feature
19
+ extractor.
20
+
21
+ **Data Set Characteristics:**
22
+
23
+ ================= ==========
24
+ Classes 20
25
+ Samples total 18846
26
+ Dimensionality 1
27
+ Features text
28
+ ================= ==========
29
+
30
+ .. dropdown:: Usage
31
+
32
+ The :func:`sklearn.datasets.fetch_20newsgroups` function is a data
33
+ fetching / caching functions that downloads the data archive from
34
+ the original `20 newsgroups website <http://people.csail.mit.edu/jrennie/20Newsgroups/>`__,
35
+ extracts the archive contents
36
+ in the ``~/scikit_learn_data/20news_home`` folder and calls the
37
+ :func:`sklearn.datasets.load_files` on either the training or
38
+ testing set folder, or both of them::
39
+
40
+ >>> from sklearn.datasets import fetch_20newsgroups
41
+ >>> newsgroups_train = fetch_20newsgroups(subset='train')
42
+
43
+ >>> from pprint import pprint
44
+ >>> pprint(list(newsgroups_train.target_names))
45
+ ['alt.atheism',
46
+ 'comp.graphics',
47
+ 'comp.os.ms-windows.misc',
48
+ 'comp.sys.ibm.pc.hardware',
49
+ 'comp.sys.mac.hardware',
50
+ 'comp.windows.x',
51
+ 'misc.forsale',
52
+ 'rec.autos',
53
+ 'rec.motorcycles',
54
+ 'rec.sport.baseball',
55
+ 'rec.sport.hockey',
56
+ 'sci.crypt',
57
+ 'sci.electronics',
58
+ 'sci.med',
59
+ 'sci.space',
60
+ 'soc.religion.christian',
61
+ 'talk.politics.guns',
62
+ 'talk.politics.mideast',
63
+ 'talk.politics.misc',
64
+ 'talk.religion.misc']
65
+
66
+ The real data lies in the ``filenames`` and ``target`` attributes. The target
67
+ attribute is the integer index of the category::
68
+
69
+ >>> newsgroups_train.filenames.shape
70
+ (11314,)
71
+ >>> newsgroups_train.target.shape
72
+ (11314,)
73
+ >>> newsgroups_train.target[:10]
74
+ array([ 7, 4, 4, 1, 14, 16, 13, 3, 2, 4])
75
+
76
+ It is possible to load only a sub-selection of the categories by passing the
77
+ list of the categories to load to the
78
+ :func:`sklearn.datasets.fetch_20newsgroups` function::
79
+
80
+ >>> cats = ['alt.atheism', 'sci.space']
81
+ >>> newsgroups_train = fetch_20newsgroups(subset='train', categories=cats)
82
+
83
+ >>> list(newsgroups_train.target_names)
84
+ ['alt.atheism', 'sci.space']
85
+ >>> newsgroups_train.filenames.shape
86
+ (1073,)
87
+ >>> newsgroups_train.target.shape
88
+ (1073,)
89
+ >>> newsgroups_train.target[:10]
90
+ array([0, 1, 1, 1, 0, 1, 1, 0, 0, 0])
91
+
92
+ .. dropdown:: Converting text to vectors
93
+
94
+ In order to feed predictive or clustering models with the text data,
95
+ one first need to turn the text into vectors of numerical values suitable
96
+ for statistical analysis. This can be achieved with the utilities of the
97
+ ``sklearn.feature_extraction.text`` as demonstrated in the following
98
+ example that extract `TF-IDF <https://en.wikipedia.org/wiki/Tf-idf>`__ vectors
99
+ of unigram tokens from a subset of 20news::
100
+
101
+ >>> from sklearn.feature_extraction.text import TfidfVectorizer
102
+ >>> categories = ['alt.atheism', 'talk.religion.misc',
103
+ ... 'comp.graphics', 'sci.space']
104
+ >>> newsgroups_train = fetch_20newsgroups(subset='train',
105
+ ... categories=categories)
106
+ >>> vectorizer = TfidfVectorizer()
107
+ >>> vectors = vectorizer.fit_transform(newsgroups_train.data)
108
+ >>> vectors.shape
109
+ (2034, 34118)
110
+
111
+ The extracted TF-IDF vectors are very sparse, with an average of 159 non-zero
112
+ components by sample in a more than 30000-dimensional space
113
+ (less than .5% non-zero features)::
114
+
115
+ >>> vectors.nnz / float(vectors.shape[0])
116
+ 159.01327...
117
+
118
+ :func:`sklearn.datasets.fetch_20newsgroups_vectorized` is a function which
119
+ returns ready-to-use token counts features instead of file names.
120
+
121
+ .. dropdown:: Filtering text for more realistic training
122
+
123
+ It is easy for a classifier to overfit on particular things that appear in the
124
+ 20 Newsgroups data, such as newsgroup headers. Many classifiers achieve very
125
+ high F-scores, but their results would not generalize to other documents that
126
+ aren't from this window of time.
127
+
128
+ For example, let's look at the results of a multinomial Naive Bayes classifier,
129
+ which is fast to train and achieves a decent F-score::
130
+
131
+ >>> from sklearn.naive_bayes import MultinomialNB
132
+ >>> from sklearn import metrics
133
+ >>> newsgroups_test = fetch_20newsgroups(subset='test',
134
+ ... categories=categories)
135
+ >>> vectors_test = vectorizer.transform(newsgroups_test.data)
136
+ >>> clf = MultinomialNB(alpha=.01)
137
+ >>> clf.fit(vectors, newsgroups_train.target)
138
+ MultinomialNB(alpha=0.01, class_prior=None, fit_prior=True)
139
+
140
+ >>> pred = clf.predict(vectors_test)
141
+ >>> metrics.f1_score(newsgroups_test.target, pred, average='macro')
142
+ 0.88213...
143
+
144
+ (The example :ref:`sphx_glr_auto_examples_text_plot_document_classification_20newsgroups.py` shuffles
145
+ the training and test data, instead of segmenting by time, and in that case
146
+ multinomial Naive Bayes gets a much higher F-score of 0.88. Are you suspicious
147
+ yet of what's going on inside this classifier?)
148
+
149
+ Let's take a look at what the most informative features are:
150
+
151
+ >>> import numpy as np
152
+ >>> def show_top10(classifier, vectorizer, categories):
153
+ ... feature_names = vectorizer.get_feature_names_out()
154
+ ... for i, category in enumerate(categories):
155
+ ... top10 = np.argsort(classifier.coef_[i])[-10:]
156
+ ... print("%s: %s" % (category, " ".join(feature_names[top10])))
157
+ ...
158
+ >>> show_top10(clf, vectorizer, newsgroups_train.target_names)
159
+ alt.atheism: edu it and in you that is of to the
160
+ comp.graphics: edu in graphics it is for and of to the
161
+ sci.space: edu it that is in and space to of the
162
+ talk.religion.misc: not it you in is that and to of the
163
+
164
+
165
+ You can now see many things that these features have overfit to:
166
+
167
+ - Almost every group is distinguished by whether headers such as
168
+ ``NNTP-Posting-Host:`` and ``Distribution:`` appear more or less often.
169
+ - Another significant feature involves whether the sender is affiliated with
170
+ a university, as indicated either by their headers or their signature.
171
+ - The word "article" is a significant feature, based on how often people quote
172
+ previous posts like this: "In article [article ID], [name] <[e-mail address]>
173
+ wrote:"
174
+ - Other features match the names and e-mail addresses of particular people who
175
+ were posting at the time.
176
+
177
+ With such an abundance of clues that distinguish newsgroups, the classifiers
178
+ barely have to identify topics from text at all, and they all perform at the
179
+ same high level.
180
+
181
+ For this reason, the functions that load 20 Newsgroups data provide a
182
+ parameter called **remove**, telling it what kinds of information to strip out
183
+ of each file. **remove** should be a tuple containing any subset of
184
+ ``('headers', 'footers', 'quotes')``, telling it to remove headers, signature
185
+ blocks, and quotation blocks respectively.
186
+
187
+ >>> newsgroups_test = fetch_20newsgroups(subset='test',
188
+ ... remove=('headers', 'footers', 'quotes'),
189
+ ... categories=categories)
190
+ >>> vectors_test = vectorizer.transform(newsgroups_test.data)
191
+ >>> pred = clf.predict(vectors_test)
192
+ >>> metrics.f1_score(pred, newsgroups_test.target, average='macro')
193
+ 0.77310...
194
+
195
+ This classifier lost over a lot of its F-score, just because we removed
196
+ metadata that has little to do with topic classification.
197
+ It loses even more if we also strip this metadata from the training data:
198
+
199
+ >>> newsgroups_train = fetch_20newsgroups(subset='train',
200
+ ... remove=('headers', 'footers', 'quotes'),
201
+ ... categories=categories)
202
+ >>> vectors = vectorizer.fit_transform(newsgroups_train.data)
203
+ >>> clf = MultinomialNB(alpha=.01)
204
+ >>> clf.fit(vectors, newsgroups_train.target)
205
+ MultinomialNB(alpha=0.01, class_prior=None, fit_prior=True)
206
+
207
+ >>> vectors_test = vectorizer.transform(newsgroups_test.data)
208
+ >>> pred = clf.predict(vectors_test)
209
+ >>> metrics.f1_score(newsgroups_test.target, pred, average='macro')
210
+ 0.76995...
211
+
212
+ Some other classifiers cope better with this harder version of the task. Try the
213
+ :ref:`sphx_glr_auto_examples_model_selection_plot_grid_search_text_feature_extraction.py`
214
+ example with and without the `remove` option to compare the results.
215
+
216
+ .. rubric:: Data Considerations
217
+
218
+ The Cleveland Indians is a major league baseball team based in Cleveland,
219
+ Ohio, USA. In December 2020, it was reported that "After several months of
220
+ discussion sparked by the death of George Floyd and a national reckoning over
221
+ race and colonialism, the Cleveland Indians have decided to change their
222
+ name." Team owner Paul Dolan "did make it clear that the team will not make
223
+ its informal nickname -- the Tribe -- its new team name." "It's not going to
224
+ be a half-step away from the Indians," Dolan said."We will not have a Native
225
+ American-themed name."
226
+
227
+ https://www.mlb.com/news/cleveland-indians-team-name-change
228
+
229
+ .. rubric:: Recommendation
230
+
231
+ - When evaluating text classifiers on the 20 Newsgroups data, you
232
+ should strip newsgroup-related metadata. In scikit-learn, you can do this
233
+ by setting ``remove=('headers', 'footers', 'quotes')``. The F-score will be
234
+ lower because it is more realistic.
235
+ - This text dataset contains data which may be inappropriate for certain NLP
236
+ applications. An example is listed in the "Data Considerations" section
237
+ above. The challenge with using current text datasets in NLP for tasks such
238
+ as sentence completion, clustering, and other applications is that text
239
+ that is culturally biased and inflammatory will propagate biases. This
240
+ should be taken into consideration when using the dataset, reviewing the
241
+ output, and the bias should be documented.
242
+
243
+ .. rubric:: Examples
244
+
245
+ * :ref:`sphx_glr_auto_examples_model_selection_plot_grid_search_text_feature_extraction.py`
246
+ * :ref:`sphx_glr_auto_examples_text_plot_document_classification_20newsgroups.py`
247
+ * :ref:`sphx_glr_auto_examples_text_plot_hashing_vs_dict_vectorizer.py`
248
+ * :ref:`sphx_glr_auto_examples_text_plot_document_clustering.py`
miniconda3/envs/active_proaction/lib/python3.10/site-packages/sklearn/datasets/descr/wine_data.rst ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .. _wine_dataset:
2
+
3
+ Wine recognition dataset
4
+ ------------------------
5
+
6
+ **Data Set Characteristics:**
7
+
8
+ :Number of Instances: 178
9
+ :Number of Attributes: 13 numeric, predictive attributes and the class
10
+ :Attribute Information:
11
+ - Alcohol
12
+ - Malic acid
13
+ - Ash
14
+ - Alcalinity of ash
15
+ - Magnesium
16
+ - Total phenols
17
+ - Flavanoids
18
+ - Nonflavanoid phenols
19
+ - Proanthocyanins
20
+ - Color intensity
21
+ - Hue
22
+ - OD280/OD315 of diluted wines
23
+ - Proline
24
+ - class:
25
+ - class_0
26
+ - class_1
27
+ - class_2
28
+
29
+ :Summary Statistics:
30
+
31
+ ============================= ==== ===== ======= =====
32
+ Min Max Mean SD
33
+ ============================= ==== ===== ======= =====
34
+ Alcohol: 11.0 14.8 13.0 0.8
35
+ Malic Acid: 0.74 5.80 2.34 1.12
36
+ Ash: 1.36 3.23 2.36 0.27
37
+ Alcalinity of Ash: 10.6 30.0 19.5 3.3
38
+ Magnesium: 70.0 162.0 99.7 14.3
39
+ Total Phenols: 0.98 3.88 2.29 0.63
40
+ Flavanoids: 0.34 5.08 2.03 1.00
41
+ Nonflavanoid Phenols: 0.13 0.66 0.36 0.12
42
+ Proanthocyanins: 0.41 3.58 1.59 0.57
43
+ Colour Intensity: 1.3 13.0 5.1 2.3
44
+ Hue: 0.48 1.71 0.96 0.23
45
+ OD280/OD315 of diluted wines: 1.27 4.00 2.61 0.71
46
+ Proline: 278 1680 746 315
47
+ ============================= ==== ===== ======= =====
48
+
49
+ :Missing Attribute Values: None
50
+ :Class Distribution: class_0 (59), class_1 (71), class_2 (48)
51
+ :Creator: R.A. Fisher
52
+ :Donor: Michael Marshall (MARSHALL%PLU@io.arc.nasa.gov)
53
+ :Date: July, 1988
54
+
55
+ This is a copy of UCI ML Wine recognition datasets.
56
+ https://archive.ics.uci.edu/ml/machine-learning-databases/wine/wine.data
57
+
58
+ The data is the results of a chemical analysis of wines grown in the same
59
+ region in Italy by three different cultivators. There are thirteen different
60
+ measurements taken for different constituents found in the three types of
61
+ wine.
62
+
63
+ Original Owners:
64
+
65
+ Forina, M. et al, PARVUS -
66
+ An Extendible Package for Data Exploration, Classification and Correlation.
67
+ Institute of Pharmaceutical and Food Analysis and Technologies,
68
+ Via Brigata Salerno, 16147 Genoa, Italy.
69
+
70
+ Citation:
71
+
72
+ Lichman, M. (2013). UCI Machine Learning Repository
73
+ [https://archive.ics.uci.edu/ml]. Irvine, CA: University of California,
74
+ School of Information and Computer Science.
75
+
76
+ .. dropdown:: References
77
+
78
+ (1) S. Aeberhard, D. Coomans and O. de Vel,
79
+ Comparison of Classifiers in High Dimensional Settings,
80
+ Tech. Rep. no. 92-02, (1992), Dept. of Computer Science and Dept. of
81
+ Mathematics and Statistics, James Cook University of North Queensland.
82
+ (Also submitted to Technometrics).
83
+
84
+ The data was used with many others for comparing various
85
+ classifiers. The classes are separable, though only RDA
86
+ has achieved 100% correct classification.
87
+ (RDA : 100%, QDA 99.4%, LDA 98.9%, 1NN 96.1% (z-transformed data))
88
+ (All results using the leave-one-out technique)
89
+
90
+ (2) S. Aeberhard, D. Coomans and O. de Vel,
91
+ "THE CLASSIFICATION PERFORMANCE OF RDA"
92
+ Tech. Rep. no. 92-01, (1992), Dept. of Computer Science and Dept. of
93
+ Mathematics and Statistics, James Cook University of North Queensland.
94
+ (Also submitted to Journal of Chemometrics).
miniconda3/envs/active_proaction/lib/python3.10/site-packages/sklearn/datasets/images/README.txt ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Image: china.jpg
2
+ Released under a creative commons license. [1]
3
+ Attribution: Some rights reserved by danielbuechele [2]
4
+ Retrieved 21st August, 2011 from [3] by Robert Layton
5
+
6
+ [1] https://creativecommons.org/licenses/by/2.0/
7
+ [2] https://www.flickr.com/photos/danielbuechele/
8
+ [3] https://www.flickr.com/photos/danielbuechele/6061409035/sizes/z/in/photostream/
9
+
10
+
11
+ Image: flower.jpg
12
+ Released under a creative commons license. [1]
13
+ Attribution: Some rights reserved by danielbuechele [2]
14
+ Retrieved 21st August, 2011 from [3] by Robert Layton
15
+
16
+ [1] https://creativecommons.org/licenses/by/2.0/
17
+ [2] https://www.flickr.com/photos/vultilion/
18
+ [3] https://www.flickr.com/photos/vultilion/6056698931/sizes/z/in/photostream/
miniconda3/envs/active_proaction/lib/python3.10/site-packages/sklearn/datasets/images/__init__.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ # Authors: The scikit-learn developers
2
+ # SPDX-License-Identifier: BSD-3-Clause
miniconda3/envs/active_proaction/lib/python3.10/site-packages/sklearn/datasets/tests/__init__.py ADDED
File without changes
miniconda3/envs/active_proaction/lib/python3.10/site-packages/sklearn/datasets/tests/data/__init__.py ADDED
File without changes
miniconda3/envs/active_proaction/lib/python3.10/site-packages/sklearn/datasets/tests/data/openml/__init__.py ADDED
File without changes
miniconda3/envs/active_proaction/lib/python3.10/site-packages/sklearn/datasets/tests/data/openml/id_1/__init__.py ADDED
File without changes
miniconda3/envs/active_proaction/lib/python3.10/site-packages/sklearn/datasets/tests/data/openml/id_1119/__init__.py ADDED
File without changes
miniconda3/envs/active_proaction/lib/python3.10/site-packages/sklearn/datasets/tests/data/openml/id_1590/__init__.py ADDED
File without changes
miniconda3/envs/active_proaction/lib/python3.10/site-packages/sklearn/datasets/tests/data/openml/id_2/__init__.py ADDED
File without changes
miniconda3/envs/active_proaction/lib/python3.10/site-packages/sklearn/datasets/tests/data/openml/id_292/__init__.py ADDED
File without changes
miniconda3/envs/active_proaction/lib/python3.10/site-packages/sklearn/datasets/tests/data/openml/id_3/__init__.py ADDED
File without changes
miniconda3/envs/active_proaction/lib/python3.10/site-packages/sklearn/datasets/tests/data/openml/id_40589/__init__.py ADDED
File without changes
miniconda3/envs/active_proaction/lib/python3.10/site-packages/sklearn/datasets/tests/data/openml/id_40675/__init__.py ADDED
File without changes
miniconda3/envs/active_proaction/lib/python3.10/site-packages/sklearn/datasets/tests/data/openml/id_40945/__init__.py ADDED
File without changes
miniconda3/envs/active_proaction/lib/python3.10/site-packages/sklearn/datasets/tests/data/openml/id_40966/__init__.py ADDED
File without changes
miniconda3/envs/active_proaction/lib/python3.10/site-packages/sklearn/datasets/tests/data/openml/id_42074/__init__.py ADDED
File without changes
miniconda3/envs/active_proaction/lib/python3.10/site-packages/sklearn/datasets/tests/data/openml/id_42585/__init__.py ADDED
File without changes
miniconda3/envs/active_proaction/lib/python3.10/site-packages/sklearn/datasets/tests/data/openml/id_561/__init__.py ADDED
File without changes
miniconda3/envs/active_proaction/lib/python3.10/site-packages/sklearn/datasets/tests/data/openml/id_61/__init__.py ADDED
File without changes
miniconda3/envs/active_proaction/lib/python3.10/site-packages/sklearn/datasets/tests/data/openml/id_62/__init__.py ADDED
File without changes
miniconda3/envs/active_proaction/lib/python3.10/site-packages/sklearn/datasets/tests/data/svmlight_classification.txt ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ # comment
2
+ # note: the next line contains a tab
3
+ 1.0 3:2.5 11:-5.2 16:1.5 # and an inline comment
4
+ 2.0 6:1.0 13:-3
5
+ # another comment
6
+ 3.0 21:27
7
+ 4.0 2:1.234567890123456e10 # double precision value
8
+ 1.0 # empty line, all zeros
9
+ 2.0 3:0 # explicit zeros
miniconda3/envs/active_proaction/lib/python3.10/site-packages/sklearn/datasets/tests/data/svmlight_invalid.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ python 2:2.5 10:-5.2 15:1.5
2
+ 2.0 5:1.0 12:-3
3
+ 3.0 20:27
miniconda3/envs/active_proaction/lib/python3.10/site-packages/sklearn/datasets/tests/data/svmlight_invalid_order.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ -1 5:2.5 2:-5.2 15:1.5
miniconda3/envs/active_proaction/lib/python3.10/site-packages/sklearn/datasets/tests/data/svmlight_multilabel.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ # multilabel dataset in SVMlight format
2
+ 1,0 2:2.5 10:-5.2 15:1.5
3
+ 2 5:1.0 12:-3
4
+ 2:3.5 11:26
5
+ 1,2 20:27
miniconda3/envs/active_proaction/lib/python3.10/site-packages/sklearn/datasets/tests/test_20news.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Test the 20news downloader, if the data is available,
2
+ or if specifically requested via environment variable
3
+ (e.g. for CI jobs)."""
4
+
5
+ from functools import partial
6
+ from unittest.mock import patch
7
+
8
+ import numpy as np
9
+ import pytest
10
+ import scipy.sparse as sp
11
+
12
+ from sklearn.datasets.tests.test_common import (
13
+ check_as_frame,
14
+ check_pandas_dependency_message,
15
+ check_return_X_y,
16
+ )
17
+ from sklearn.preprocessing import normalize
18
+ from sklearn.utils._testing import assert_allclose_dense_sparse
19
+
20
+
21
+ def test_20news(fetch_20newsgroups_fxt):
22
+ data = fetch_20newsgroups_fxt(subset="all", shuffle=False)
23
+ assert data.DESCR.startswith(".. _20newsgroups_dataset:")
24
+
25
+ # Extract a reduced dataset
26
+ data2cats = fetch_20newsgroups_fxt(
27
+ subset="all", categories=data.target_names[-1:-3:-1], shuffle=False
28
+ )
29
+ # Check that the ordering of the target_names is the same
30
+ # as the ordering in the full dataset
31
+ assert data2cats.target_names == data.target_names[-2:]
32
+ # Assert that we have only 0 and 1 as labels
33
+ assert np.unique(data2cats.target).tolist() == [0, 1]
34
+
35
+ # Check that the number of filenames is consistent with data/target
36
+ assert len(data2cats.filenames) == len(data2cats.target)
37
+ assert len(data2cats.filenames) == len(data2cats.data)
38
+
39
+ # Check that the first entry of the reduced dataset corresponds to
40
+ # the first entry of the corresponding category in the full dataset
41
+ entry1 = data2cats.data[0]
42
+ category = data2cats.target_names[data2cats.target[0]]
43
+ label = data.target_names.index(category)
44
+ entry2 = data.data[np.where(data.target == label)[0][0]]
45
+ assert entry1 == entry2
46
+
47
+ # check that return_X_y option
48
+ X, y = fetch_20newsgroups_fxt(subset="all", shuffle=False, return_X_y=True)
49
+ assert len(X) == len(data.data)
50
+ assert y.shape == data.target.shape
51
+
52
+
53
+ def test_20news_length_consistency(fetch_20newsgroups_fxt):
54
+ """Checks the length consistencies within the bunch
55
+
56
+ This is a non-regression test for a bug present in 0.16.1.
57
+ """
58
+ # Extract the full dataset
59
+ data = fetch_20newsgroups_fxt(subset="all")
60
+ assert len(data["data"]) == len(data.data)
61
+ assert len(data["target"]) == len(data.target)
62
+ assert len(data["filenames"]) == len(data.filenames)
63
+
64
+
65
+ def test_20news_vectorized(fetch_20newsgroups_vectorized_fxt):
66
+ # test subset = train
67
+ bunch = fetch_20newsgroups_vectorized_fxt(subset="train")
68
+ assert sp.issparse(bunch.data) and bunch.data.format == "csr"
69
+ assert bunch.data.shape == (11314, 130107)
70
+ assert bunch.target.shape[0] == 11314
71
+ assert bunch.data.dtype == np.float64
72
+ assert bunch.DESCR.startswith(".. _20newsgroups_dataset:")
73
+
74
+ # test subset = test
75
+ bunch = fetch_20newsgroups_vectorized_fxt(subset="test")
76
+ assert sp.issparse(bunch.data) and bunch.data.format == "csr"
77
+ assert bunch.data.shape == (7532, 130107)
78
+ assert bunch.target.shape[0] == 7532
79
+ assert bunch.data.dtype == np.float64
80
+ assert bunch.DESCR.startswith(".. _20newsgroups_dataset:")
81
+
82
+ # test return_X_y option
83
+ fetch_func = partial(fetch_20newsgroups_vectorized_fxt, subset="test")
84
+ check_return_X_y(bunch, fetch_func)
85
+
86
+ # test subset = all
87
+ bunch = fetch_20newsgroups_vectorized_fxt(subset="all")
88
+ assert sp.issparse(bunch.data) and bunch.data.format == "csr"
89
+ assert bunch.data.shape == (11314 + 7532, 130107)
90
+ assert bunch.target.shape[0] == 11314 + 7532
91
+ assert bunch.data.dtype == np.float64
92
+ assert bunch.DESCR.startswith(".. _20newsgroups_dataset:")
93
+
94
+
95
+ def test_20news_normalization(fetch_20newsgroups_vectorized_fxt):
96
+ X = fetch_20newsgroups_vectorized_fxt(normalize=False)
97
+ X_ = fetch_20newsgroups_vectorized_fxt(normalize=True)
98
+ X_norm = X_["data"][:100]
99
+ X = X["data"][:100]
100
+
101
+ assert_allclose_dense_sparse(X_norm, normalize(X))
102
+ assert np.allclose(np.linalg.norm(X_norm.todense(), axis=1), 1)
103
+
104
+
105
+ def test_20news_as_frame(fetch_20newsgroups_vectorized_fxt):
106
+ pd = pytest.importorskip("pandas")
107
+
108
+ bunch = fetch_20newsgroups_vectorized_fxt(as_frame=True)
109
+ check_as_frame(bunch, fetch_20newsgroups_vectorized_fxt)
110
+
111
+ frame = bunch.frame
112
+ assert frame.shape == (11314, 130108)
113
+ assert all([isinstance(col, pd.SparseDtype) for col in bunch.data.dtypes])
114
+
115
+ # Check a small subset of features
116
+ for expected_feature in [
117
+ "beginner",
118
+ "beginners",
119
+ "beginning",
120
+ "beginnings",
121
+ "begins",
122
+ "begley",
123
+ "begone",
124
+ ]:
125
+ assert expected_feature in frame.keys()
126
+ assert "category_class" in frame.keys()
127
+ assert bunch.target.name == "category_class"
128
+
129
+
130
+ def test_as_frame_no_pandas(fetch_20newsgroups_vectorized_fxt, hide_available_pandas):
131
+ check_pandas_dependency_message(fetch_20newsgroups_vectorized_fxt)
132
+
133
+
134
+ def test_outdated_pickle(fetch_20newsgroups_vectorized_fxt):
135
+ with patch("os.path.exists") as mock_is_exist:
136
+ with patch("joblib.load") as mock_load:
137
+ # mock that the dataset was cached
138
+ mock_is_exist.return_value = True
139
+ # mock that we have an outdated pickle with only X and y returned
140
+ mock_load.return_value = ("X", "y")
141
+ err_msg = "The cached dataset located in"
142
+ with pytest.raises(ValueError, match=err_msg):
143
+ fetch_20newsgroups_vectorized_fxt(as_frame=True)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/sklearn/datasets/tests/test_arff_parser.py ADDED
@@ -0,0 +1,284 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import textwrap
2
+ from io import BytesIO
3
+
4
+ import pytest
5
+
6
+ from sklearn.datasets._arff_parser import (
7
+ _liac_arff_parser,
8
+ _pandas_arff_parser,
9
+ _post_process_frame,
10
+ load_arff_from_gzip_file,
11
+ )
12
+
13
+
14
+ @pytest.mark.parametrize(
15
+ "feature_names, target_names",
16
+ [
17
+ (
18
+ [
19
+ "col_int_as_integer",
20
+ "col_int_as_numeric",
21
+ "col_float_as_real",
22
+ "col_float_as_numeric",
23
+ ],
24
+ ["col_categorical", "col_string"],
25
+ ),
26
+ (
27
+ [
28
+ "col_int_as_integer",
29
+ "col_int_as_numeric",
30
+ "col_float_as_real",
31
+ "col_float_as_numeric",
32
+ ],
33
+ ["col_categorical"],
34
+ ),
35
+ (
36
+ [
37
+ "col_int_as_integer",
38
+ "col_int_as_numeric",
39
+ "col_float_as_real",
40
+ "col_float_as_numeric",
41
+ ],
42
+ [],
43
+ ),
44
+ ],
45
+ )
46
+ def test_post_process_frame(feature_names, target_names):
47
+ """Check the behaviour of the post-processing function for splitting a dataframe."""
48
+ pd = pytest.importorskip("pandas")
49
+
50
+ X_original = pd.DataFrame(
51
+ {
52
+ "col_int_as_integer": [1, 2, 3],
53
+ "col_int_as_numeric": [1, 2, 3],
54
+ "col_float_as_real": [1.0, 2.0, 3.0],
55
+ "col_float_as_numeric": [1.0, 2.0, 3.0],
56
+ "col_categorical": ["a", "b", "c"],
57
+ "col_string": ["a", "b", "c"],
58
+ }
59
+ )
60
+
61
+ X, y = _post_process_frame(X_original, feature_names, target_names)
62
+ assert isinstance(X, pd.DataFrame)
63
+ if len(target_names) >= 2:
64
+ assert isinstance(y, pd.DataFrame)
65
+ elif len(target_names) == 1:
66
+ assert isinstance(y, pd.Series)
67
+ else:
68
+ assert y is None
69
+
70
+
71
+ def test_load_arff_from_gzip_file_error_parser():
72
+ """An error will be raised if the parser is not known."""
73
+ # None of the input parameters are required to be accurate since the check
74
+ # of the parser will be carried out first.
75
+
76
+ err_msg = "Unknown parser: 'xxx'. Should be 'liac-arff' or 'pandas'"
77
+ with pytest.raises(ValueError, match=err_msg):
78
+ load_arff_from_gzip_file("xxx", "xxx", "xxx", "xxx", "xxx", "xxx")
79
+
80
+
81
+ @pytest.mark.parametrize("parser_func", [_liac_arff_parser, _pandas_arff_parser])
82
+ def test_pandas_arff_parser_strip_single_quotes(parser_func):
83
+ """Check that we properly strip single quotes from the data."""
84
+ pd = pytest.importorskip("pandas")
85
+
86
+ arff_file = BytesIO(
87
+ textwrap.dedent(
88
+ """
89
+ @relation 'toy'
90
+ @attribute 'cat_single_quote' {'A', 'B', 'C'}
91
+ @attribute 'str_single_quote' string
92
+ @attribute 'str_nested_quote' string
93
+ @attribute 'class' numeric
94
+ @data
95
+ 'A','some text','\"expect double quotes\"',0
96
+ """
97
+ ).encode("utf-8")
98
+ )
99
+
100
+ columns_info = {
101
+ "cat_single_quote": {
102
+ "data_type": "nominal",
103
+ "name": "cat_single_quote",
104
+ },
105
+ "str_single_quote": {
106
+ "data_type": "string",
107
+ "name": "str_single_quote",
108
+ },
109
+ "str_nested_quote": {
110
+ "data_type": "string",
111
+ "name": "str_nested_quote",
112
+ },
113
+ "class": {
114
+ "data_type": "numeric",
115
+ "name": "class",
116
+ },
117
+ }
118
+
119
+ feature_names = [
120
+ "cat_single_quote",
121
+ "str_single_quote",
122
+ "str_nested_quote",
123
+ ]
124
+ target_names = ["class"]
125
+
126
+ # We don't strip single quotes for string columns with the pandas parser.
127
+ expected_values = {
128
+ "cat_single_quote": "A",
129
+ "str_single_quote": (
130
+ "some text" if parser_func is _liac_arff_parser else "'some text'"
131
+ ),
132
+ "str_nested_quote": (
133
+ '"expect double quotes"'
134
+ if parser_func is _liac_arff_parser
135
+ else "'\"expect double quotes\"'"
136
+ ),
137
+ "class": 0,
138
+ }
139
+
140
+ _, _, frame, _ = parser_func(
141
+ arff_file,
142
+ output_arrays_type="pandas",
143
+ openml_columns_info=columns_info,
144
+ feature_names_to_select=feature_names,
145
+ target_names_to_select=target_names,
146
+ )
147
+
148
+ assert frame.columns.tolist() == feature_names + target_names
149
+ pd.testing.assert_series_equal(frame.iloc[0], pd.Series(expected_values, name=0))
150
+
151
+
152
+ @pytest.mark.parametrize("parser_func", [_liac_arff_parser, _pandas_arff_parser])
153
+ def test_pandas_arff_parser_strip_double_quotes(parser_func):
154
+ """Check that we properly strip double quotes from the data."""
155
+ pd = pytest.importorskip("pandas")
156
+
157
+ arff_file = BytesIO(
158
+ textwrap.dedent(
159
+ """
160
+ @relation 'toy'
161
+ @attribute 'cat_double_quote' {"A", "B", "C"}
162
+ @attribute 'str_double_quote' string
163
+ @attribute 'str_nested_quote' string
164
+ @attribute 'class' numeric
165
+ @data
166
+ "A","some text","\'expect double quotes\'",0
167
+ """
168
+ ).encode("utf-8")
169
+ )
170
+
171
+ columns_info = {
172
+ "cat_double_quote": {
173
+ "data_type": "nominal",
174
+ "name": "cat_double_quote",
175
+ },
176
+ "str_double_quote": {
177
+ "data_type": "string",
178
+ "name": "str_double_quote",
179
+ },
180
+ "str_nested_quote": {
181
+ "data_type": "string",
182
+ "name": "str_nested_quote",
183
+ },
184
+ "class": {
185
+ "data_type": "numeric",
186
+ "name": "class",
187
+ },
188
+ }
189
+
190
+ feature_names = [
191
+ "cat_double_quote",
192
+ "str_double_quote",
193
+ "str_nested_quote",
194
+ ]
195
+ target_names = ["class"]
196
+
197
+ expected_values = {
198
+ "cat_double_quote": "A",
199
+ "str_double_quote": "some text",
200
+ "str_nested_quote": "'expect double quotes'",
201
+ "class": 0,
202
+ }
203
+
204
+ _, _, frame, _ = parser_func(
205
+ arff_file,
206
+ output_arrays_type="pandas",
207
+ openml_columns_info=columns_info,
208
+ feature_names_to_select=feature_names,
209
+ target_names_to_select=target_names,
210
+ )
211
+
212
+ assert frame.columns.tolist() == feature_names + target_names
213
+ pd.testing.assert_series_equal(frame.iloc[0], pd.Series(expected_values, name=0))
214
+
215
+
216
+ @pytest.mark.parametrize(
217
+ "parser_func",
218
+ [
219
+ # internal quotes are not considered to follow the ARFF spec in LIAC ARFF
220
+ pytest.param(_liac_arff_parser, marks=pytest.mark.xfail),
221
+ _pandas_arff_parser,
222
+ ],
223
+ )
224
+ def test_pandas_arff_parser_strip_no_quotes(parser_func):
225
+ """Check that we properly parse with no quotes characters."""
226
+ pd = pytest.importorskip("pandas")
227
+
228
+ arff_file = BytesIO(
229
+ textwrap.dedent(
230
+ """
231
+ @relation 'toy'
232
+ @attribute 'cat_without_quote' {A, B, C}
233
+ @attribute 'str_without_quote' string
234
+ @attribute 'str_internal_quote' string
235
+ @attribute 'class' numeric
236
+ @data
237
+ A,some text,'internal' quote,0
238
+ """
239
+ ).encode("utf-8")
240
+ )
241
+
242
+ columns_info = {
243
+ "cat_without_quote": {
244
+ "data_type": "nominal",
245
+ "name": "cat_without_quote",
246
+ },
247
+ "str_without_quote": {
248
+ "data_type": "string",
249
+ "name": "str_without_quote",
250
+ },
251
+ "str_internal_quote": {
252
+ "data_type": "string",
253
+ "name": "str_internal_quote",
254
+ },
255
+ "class": {
256
+ "data_type": "numeric",
257
+ "name": "class",
258
+ },
259
+ }
260
+
261
+ feature_names = [
262
+ "cat_without_quote",
263
+ "str_without_quote",
264
+ "str_internal_quote",
265
+ ]
266
+ target_names = ["class"]
267
+
268
+ expected_values = {
269
+ "cat_without_quote": "A",
270
+ "str_without_quote": "some text",
271
+ "str_internal_quote": "'internal' quote",
272
+ "class": 0,
273
+ }
274
+
275
+ _, _, frame, _ = parser_func(
276
+ arff_file,
277
+ output_arrays_type="pandas",
278
+ openml_columns_info=columns_info,
279
+ feature_names_to_select=feature_names,
280
+ target_names_to_select=target_names,
281
+ )
282
+
283
+ assert frame.columns.tolist() == feature_names + target_names
284
+ pd.testing.assert_series_equal(frame.iloc[0], pd.Series(expected_values, name=0))
miniconda3/envs/active_proaction/lib/python3.10/site-packages/sklearn/datasets/tests/test_base.py ADDED
@@ -0,0 +1,658 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import hashlib
2
+ import io
3
+ import os
4
+ import re
5
+ import shutil
6
+ import tempfile
7
+ import warnings
8
+ from functools import partial
9
+ from importlib import resources
10
+ from pathlib import Path
11
+ from pickle import dumps, loads
12
+ from unittest.mock import Mock
13
+ from urllib.error import HTTPError
14
+ from urllib.parse import urlparse
15
+
16
+ import numpy as np
17
+ import pytest
18
+
19
+ from sklearn.datasets import (
20
+ clear_data_home,
21
+ fetch_file,
22
+ get_data_home,
23
+ load_breast_cancer,
24
+ load_diabetes,
25
+ load_digits,
26
+ load_files,
27
+ load_iris,
28
+ load_linnerud,
29
+ load_sample_image,
30
+ load_sample_images,
31
+ load_wine,
32
+ )
33
+ from sklearn.datasets._base import (
34
+ RemoteFileMetadata,
35
+ _derive_folder_and_filename_from_url,
36
+ _fetch_remote,
37
+ load_csv_data,
38
+ load_gzip_compressed_csv_data,
39
+ )
40
+ from sklearn.datasets.tests.test_common import check_as_frame
41
+ from sklearn.preprocessing import scale
42
+ from sklearn.utils import Bunch
43
+
44
+
45
+ class _DummyPath:
46
+ """Minimal class that implements the os.PathLike interface."""
47
+
48
+ def __init__(self, path):
49
+ self.path = path
50
+
51
+ def __fspath__(self):
52
+ return self.path
53
+
54
+
55
+ def _remove_dir(path):
56
+ if os.path.isdir(path):
57
+ shutil.rmtree(path)
58
+
59
+
60
+ @pytest.fixture(scope="module")
61
+ def data_home(tmpdir_factory):
62
+ tmp_file = str(tmpdir_factory.mktemp("scikit_learn_data_home_test"))
63
+ yield tmp_file
64
+ _remove_dir(tmp_file)
65
+
66
+
67
+ @pytest.fixture(scope="module")
68
+ def load_files_root(tmpdir_factory):
69
+ tmp_file = str(tmpdir_factory.mktemp("scikit_learn_load_files_test"))
70
+ yield tmp_file
71
+ _remove_dir(tmp_file)
72
+
73
+
74
+ @pytest.fixture
75
+ def test_category_dir_1(load_files_root):
76
+ test_category_dir1 = tempfile.mkdtemp(dir=load_files_root)
77
+ sample_file = tempfile.NamedTemporaryFile(dir=test_category_dir1, delete=False)
78
+ sample_file.write(b"Hello World!\n")
79
+ sample_file.close()
80
+ yield str(test_category_dir1)
81
+ _remove_dir(test_category_dir1)
82
+
83
+
84
+ @pytest.fixture
85
+ def test_category_dir_2(load_files_root):
86
+ test_category_dir2 = tempfile.mkdtemp(dir=load_files_root)
87
+ yield str(test_category_dir2)
88
+ _remove_dir(test_category_dir2)
89
+
90
+
91
+ @pytest.mark.parametrize("path_container", [None, Path, _DummyPath])
92
+ def test_data_home(path_container, data_home):
93
+ # get_data_home will point to a pre-existing folder
94
+ if path_container is not None:
95
+ data_home = path_container(data_home)
96
+ data_home = get_data_home(data_home=data_home)
97
+ assert data_home == data_home
98
+ assert os.path.exists(data_home)
99
+
100
+ # clear_data_home will delete both the content and the folder it-self
101
+ if path_container is not None:
102
+ data_home = path_container(data_home)
103
+ clear_data_home(data_home=data_home)
104
+ assert not os.path.exists(data_home)
105
+
106
+ # if the folder is missing it will be created again
107
+ data_home = get_data_home(data_home=data_home)
108
+ assert os.path.exists(data_home)
109
+
110
+
111
+ def test_default_empty_load_files(load_files_root):
112
+ res = load_files(load_files_root)
113
+ assert len(res.filenames) == 0
114
+ assert len(res.target_names) == 0
115
+ assert res.DESCR is None
116
+
117
+
118
+ def test_default_load_files(test_category_dir_1, test_category_dir_2, load_files_root):
119
+ res = load_files(load_files_root)
120
+ assert len(res.filenames) == 1
121
+ assert len(res.target_names) == 2
122
+ assert res.DESCR is None
123
+ assert res.data == [b"Hello World!\n"]
124
+
125
+
126
+ def test_load_files_w_categories_desc_and_encoding(
127
+ test_category_dir_1, test_category_dir_2, load_files_root
128
+ ):
129
+ category = os.path.abspath(test_category_dir_1).split(os.sep).pop()
130
+ res = load_files(
131
+ load_files_root, description="test", categories=[category], encoding="utf-8"
132
+ )
133
+
134
+ assert len(res.filenames) == 1
135
+ assert len(res.target_names) == 1
136
+ assert res.DESCR == "test"
137
+ assert res.data == ["Hello World!\n"]
138
+
139
+
140
+ def test_load_files_wo_load_content(
141
+ test_category_dir_1, test_category_dir_2, load_files_root
142
+ ):
143
+ res = load_files(load_files_root, load_content=False)
144
+ assert len(res.filenames) == 1
145
+ assert len(res.target_names) == 2
146
+ assert res.DESCR is None
147
+ assert res.get("data") is None
148
+
149
+
150
+ @pytest.mark.parametrize("allowed_extensions", ([".txt"], [".txt", ".json"]))
151
+ def test_load_files_allowed_extensions(tmp_path, allowed_extensions):
152
+ """Check the behaviour of `allowed_extension` in `load_files`."""
153
+ d = tmp_path / "sub"
154
+ d.mkdir()
155
+ files = ("file1.txt", "file2.json", "file3.json", "file4.md")
156
+ paths = [d / f for f in files]
157
+ for p in paths:
158
+ p.write_bytes(b"hello")
159
+ res = load_files(tmp_path, allowed_extensions=allowed_extensions)
160
+ assert set([str(p) for p in paths if p.suffix in allowed_extensions]) == set(
161
+ res.filenames
162
+ )
163
+
164
+
165
+ @pytest.mark.parametrize(
166
+ "filename, expected_n_samples, expected_n_features, expected_target_names",
167
+ [
168
+ ("wine_data.csv", 178, 13, ["class_0", "class_1", "class_2"]),
169
+ ("iris.csv", 150, 4, ["setosa", "versicolor", "virginica"]),
170
+ ("breast_cancer.csv", 569, 30, ["malignant", "benign"]),
171
+ ],
172
+ )
173
+ def test_load_csv_data(
174
+ filename, expected_n_samples, expected_n_features, expected_target_names
175
+ ):
176
+ actual_data, actual_target, actual_target_names = load_csv_data(filename)
177
+ assert actual_data.shape[0] == expected_n_samples
178
+ assert actual_data.shape[1] == expected_n_features
179
+ assert actual_target.shape[0] == expected_n_samples
180
+ np.testing.assert_array_equal(actual_target_names, expected_target_names)
181
+
182
+
183
+ def test_load_csv_data_with_descr():
184
+ data_file_name = "iris.csv"
185
+ descr_file_name = "iris.rst"
186
+
187
+ res_without_descr = load_csv_data(data_file_name=data_file_name)
188
+ res_with_descr = load_csv_data(
189
+ data_file_name=data_file_name, descr_file_name=descr_file_name
190
+ )
191
+ assert len(res_with_descr) == 4
192
+ assert len(res_without_descr) == 3
193
+
194
+ np.testing.assert_array_equal(res_with_descr[0], res_without_descr[0])
195
+ np.testing.assert_array_equal(res_with_descr[1], res_without_descr[1])
196
+ np.testing.assert_array_equal(res_with_descr[2], res_without_descr[2])
197
+
198
+ assert res_with_descr[-1].startswith(".. _iris_dataset:")
199
+
200
+
201
+ @pytest.mark.parametrize(
202
+ "filename, kwargs, expected_shape",
203
+ [
204
+ ("diabetes_data_raw.csv.gz", {}, [442, 10]),
205
+ ("diabetes_target.csv.gz", {}, [442]),
206
+ ("digits.csv.gz", {"delimiter": ","}, [1797, 65]),
207
+ ],
208
+ )
209
+ def test_load_gzip_compressed_csv_data(filename, kwargs, expected_shape):
210
+ actual_data = load_gzip_compressed_csv_data(filename, **kwargs)
211
+ assert actual_data.shape == tuple(expected_shape)
212
+
213
+
214
+ def test_load_gzip_compressed_csv_data_with_descr():
215
+ data_file_name = "diabetes_target.csv.gz"
216
+ descr_file_name = "diabetes.rst"
217
+
218
+ expected_data = load_gzip_compressed_csv_data(data_file_name=data_file_name)
219
+ actual_data, descr = load_gzip_compressed_csv_data(
220
+ data_file_name=data_file_name,
221
+ descr_file_name=descr_file_name,
222
+ )
223
+
224
+ np.testing.assert_array_equal(actual_data, expected_data)
225
+ assert descr.startswith(".. _diabetes_dataset:")
226
+
227
+
228
+ def test_load_sample_images():
229
+ try:
230
+ res = load_sample_images()
231
+ assert len(res.images) == 2
232
+ assert len(res.filenames) == 2
233
+ images = res.images
234
+
235
+ # assert is china image
236
+ assert np.all(images[0][0, 0, :] == np.array([174, 201, 231], dtype=np.uint8))
237
+ # assert is flower image
238
+ assert np.all(images[1][0, 0, :] == np.array([2, 19, 13], dtype=np.uint8))
239
+ assert res.DESCR
240
+ except ImportError:
241
+ warnings.warn("Could not load sample images, PIL is not available.")
242
+
243
+
244
+ def test_load_sample_image():
245
+ try:
246
+ china = load_sample_image("china.jpg")
247
+ assert china.dtype == "uint8"
248
+ assert china.shape == (427, 640, 3)
249
+ except ImportError:
250
+ warnings.warn("Could not load sample images, PIL is not available.")
251
+
252
+
253
+ def test_load_diabetes_raw():
254
+ """Test to check that we load a scaled version by default but that we can
255
+ get an unscaled version when setting `scaled=False`."""
256
+ diabetes_raw = load_diabetes(scaled=False)
257
+ assert diabetes_raw.data.shape == (442, 10)
258
+ assert diabetes_raw.target.size == 442
259
+ assert len(diabetes_raw.feature_names) == 10
260
+ assert diabetes_raw.DESCR
261
+
262
+ diabetes_default = load_diabetes()
263
+
264
+ np.testing.assert_allclose(
265
+ scale(diabetes_raw.data) / (442**0.5), diabetes_default.data, atol=1e-04
266
+ )
267
+
268
+
269
+ @pytest.mark.parametrize(
270
+ "loader_func, data_shape, target_shape, n_target, has_descr, filenames",
271
+ [
272
+ (load_breast_cancer, (569, 30), (569,), 2, True, ["filename"]),
273
+ (load_wine, (178, 13), (178,), 3, True, []),
274
+ (load_iris, (150, 4), (150,), 3, True, ["filename"]),
275
+ (
276
+ load_linnerud,
277
+ (20, 3),
278
+ (20, 3),
279
+ 3,
280
+ True,
281
+ ["data_filename", "target_filename"],
282
+ ),
283
+ (load_diabetes, (442, 10), (442,), None, True, []),
284
+ (load_digits, (1797, 64), (1797,), 10, True, []),
285
+ (partial(load_digits, n_class=9), (1617, 64), (1617,), 10, True, []),
286
+ ],
287
+ )
288
+ def test_loader(loader_func, data_shape, target_shape, n_target, has_descr, filenames):
289
+ bunch = loader_func()
290
+
291
+ assert isinstance(bunch, Bunch)
292
+ assert bunch.data.shape == data_shape
293
+ assert bunch.target.shape == target_shape
294
+ if hasattr(bunch, "feature_names"):
295
+ assert len(bunch.feature_names) == data_shape[1]
296
+ if n_target is not None:
297
+ assert len(bunch.target_names) == n_target
298
+ if has_descr:
299
+ assert bunch.DESCR
300
+ if filenames:
301
+ assert "data_module" in bunch
302
+ assert all(
303
+ [
304
+ f in bunch
305
+ and (resources.files(bunch["data_module"]) / bunch[f]).is_file()
306
+ for f in filenames
307
+ ]
308
+ )
309
+
310
+
311
+ @pytest.mark.parametrize(
312
+ "loader_func, data_dtype, target_dtype",
313
+ [
314
+ (load_breast_cancer, np.float64, int),
315
+ (load_diabetes, np.float64, np.float64),
316
+ (load_digits, np.float64, int),
317
+ (load_iris, np.float64, int),
318
+ (load_linnerud, np.float64, np.float64),
319
+ (load_wine, np.float64, int),
320
+ ],
321
+ )
322
+ def test_toy_dataset_frame_dtype(loader_func, data_dtype, target_dtype):
323
+ default_result = loader_func()
324
+ check_as_frame(
325
+ default_result,
326
+ loader_func,
327
+ expected_data_dtype=data_dtype,
328
+ expected_target_dtype=target_dtype,
329
+ )
330
+
331
+
332
+ def test_loads_dumps_bunch():
333
+ bunch = Bunch(x="x")
334
+ bunch_from_pkl = loads(dumps(bunch))
335
+ bunch_from_pkl.x = "y"
336
+ assert bunch_from_pkl["x"] == bunch_from_pkl.x
337
+
338
+
339
+ def test_bunch_pickle_generated_with_0_16_and_read_with_0_17():
340
+ bunch = Bunch(key="original")
341
+ # This reproduces a problem when Bunch pickles have been created
342
+ # with scikit-learn 0.16 and are read with 0.17. Basically there
343
+ # is a surprising behaviour because reading bunch.key uses
344
+ # bunch.__dict__ (which is non empty for 0.16 Bunch objects)
345
+ # whereas assigning into bunch.key uses bunch.__setattr__. See
346
+ # https://github.com/scikit-learn/scikit-learn/issues/6196 for
347
+ # more details
348
+ bunch.__dict__["key"] = "set from __dict__"
349
+ bunch_from_pkl = loads(dumps(bunch))
350
+ # After loading from pickle the __dict__ should have been ignored
351
+ assert bunch_from_pkl.key == "original"
352
+ assert bunch_from_pkl["key"] == "original"
353
+ # Making sure that changing the attr does change the value
354
+ # associated with __getitem__ as well
355
+ bunch_from_pkl.key = "changed"
356
+ assert bunch_from_pkl.key == "changed"
357
+ assert bunch_from_pkl["key"] == "changed"
358
+
359
+
360
+ def test_bunch_dir():
361
+ # check that dir (important for autocomplete) shows attributes
362
+ data = load_iris()
363
+ assert "data" in dir(data)
364
+
365
+
366
+ def test_load_boston_error():
367
+ """Check that we raise the ethical warning when trying to import `load_boston`."""
368
+ msg = "The Boston housing prices dataset has an ethical problem"
369
+ with pytest.raises(ImportError, match=msg):
370
+ from sklearn.datasets import load_boston # noqa: F401
371
+
372
+ # other non-existing function should raise the usual import error
373
+ msg = "cannot import name 'non_existing_function' from 'sklearn.datasets'"
374
+ with pytest.raises(ImportError, match=msg):
375
+ from sklearn.datasets import non_existing_function # noqa: F401
376
+
377
+
378
+ def test_fetch_remote_raise_warnings_with_invalid_url(monkeypatch):
379
+ """Check retry mechanism in _fetch_remote."""
380
+
381
+ url = "https://scikit-learn.org/this_file_does_not_exist.tar.gz"
382
+ invalid_remote_file = RemoteFileMetadata("invalid_file", url, None)
383
+ urlretrieve_mock = Mock(
384
+ side_effect=HTTPError(
385
+ url=url, code=404, msg="Not Found", hdrs=None, fp=io.BytesIO()
386
+ )
387
+ )
388
+ monkeypatch.setattr("sklearn.datasets._base.urlretrieve", urlretrieve_mock)
389
+
390
+ with pytest.warns(UserWarning, match="Retry downloading") as record:
391
+ with pytest.raises(HTTPError, match="HTTP Error 404"):
392
+ _fetch_remote(invalid_remote_file, n_retries=3, delay=0)
393
+
394
+ assert urlretrieve_mock.call_count == 4
395
+
396
+ for r in record:
397
+ assert str(r.message) == f"Retry downloading from url: {url}"
398
+ assert len(record) == 3
399
+
400
+
401
+ def test_derive_folder_and_filename_from_url():
402
+ folder, filename = _derive_folder_and_filename_from_url(
403
+ "https://example.com/file.tar.gz"
404
+ )
405
+ assert folder == "example.com"
406
+ assert filename == "file.tar.gz"
407
+
408
+ folder, filename = _derive_folder_and_filename_from_url(
409
+ "https://example.com/نمونه نماینده.data"
410
+ )
411
+ assert folder == "example.com"
412
+ assert filename == "نمونه-نماینده.data"
413
+
414
+ folder, filename = _derive_folder_and_filename_from_url(
415
+ "https://example.com/path/to-/.file.tar.gz"
416
+ )
417
+ assert folder == "example.com/path_to"
418
+ assert filename == "file.tar.gz"
419
+
420
+ folder, filename = _derive_folder_and_filename_from_url("https://example.com/")
421
+ assert folder == "example.com"
422
+ assert filename == "downloaded_file"
423
+
424
+ folder, filename = _derive_folder_and_filename_from_url("https://example.com")
425
+ assert folder == "example.com"
426
+ assert filename == "downloaded_file"
427
+
428
+ folder, filename = _derive_folder_and_filename_from_url(
429
+ "https://example.com/path/@to/data.json?param=value"
430
+ )
431
+ assert folder == "example.com/path_to"
432
+ assert filename == "data.json"
433
+
434
+ folder, filename = _derive_folder_and_filename_from_url(
435
+ "https://example.com/path/@@to._/-_.data.json.#anchor"
436
+ )
437
+ assert folder == "example.com/path_to"
438
+ assert filename == "data.json"
439
+
440
+ folder, filename = _derive_folder_and_filename_from_url(
441
+ "https://example.com//some_file.txt"
442
+ )
443
+ assert folder == "example.com"
444
+ assert filename == "some_file.txt"
445
+
446
+ folder, filename = _derive_folder_and_filename_from_url(
447
+ "http://example/../some_file.txt"
448
+ )
449
+ assert folder == "example"
450
+ assert filename == "some_file.txt"
451
+
452
+ folder, filename = _derive_folder_and_filename_from_url(
453
+ "https://example.com/!.'.,/some_file.txt"
454
+ )
455
+ assert folder == "example.com"
456
+ assert filename == "some_file.txt"
457
+
458
+ folder, filename = _derive_folder_and_filename_from_url(
459
+ "https://example.com/a/!.'.,/b/some_file.txt"
460
+ )
461
+ assert folder == "example.com/a_b"
462
+ assert filename == "some_file.txt"
463
+
464
+ folder, filename = _derive_folder_and_filename_from_url("https://example.com/!.'.,")
465
+ assert folder == "example.com"
466
+ assert filename == "downloaded_file"
467
+
468
+ with pytest.raises(ValueError, match="Invalid URL"):
469
+ _derive_folder_and_filename_from_url("https:/../")
470
+
471
+
472
+ def _mock_urlretrieve(server_side):
473
+ def _urlretrieve_mock(url, local_path):
474
+ server_root = Path(server_side)
475
+ file_path = urlparse(url).path.strip("/")
476
+ if not (server_root / file_path).exists():
477
+ raise HTTPError(url, 404, "Not Found", None, None)
478
+ shutil.copy(server_root / file_path, local_path)
479
+
480
+ return Mock(side_effect=_urlretrieve_mock)
481
+
482
+
483
+ def test_fetch_file_using_data_home(monkeypatch, tmpdir):
484
+ tmpdir = Path(tmpdir)
485
+ server_side = tmpdir / "server_side"
486
+ server_side.mkdir()
487
+ data_file = server_side / "data.jsonl"
488
+ server_data = '{"a": 1, "b": 2}\n'
489
+ data_file.write_text(server_data, encoding="utf-8")
490
+
491
+ server_subfolder = server_side / "subfolder"
492
+ server_subfolder.mkdir()
493
+ other_data_file = server_subfolder / "other_file.txt"
494
+ other_data_file.write_text("Some important text data.", encoding="utf-8")
495
+
496
+ data_home = tmpdir / "data_home"
497
+ data_home.mkdir()
498
+
499
+ urlretrieve_mock = _mock_urlretrieve(server_side)
500
+ monkeypatch.setattr("sklearn.datasets._base.urlretrieve", urlretrieve_mock)
501
+
502
+ monkeypatch.setattr(
503
+ "sklearn.datasets._base.get_data_home", Mock(return_value=data_home)
504
+ )
505
+ fetched_file_path = fetch_file(
506
+ "https://example.com/data.jsonl",
507
+ )
508
+ assert fetched_file_path == data_home / "example.com" / "data.jsonl"
509
+ assert fetched_file_path.read_text(encoding="utf-8") == server_data
510
+
511
+ fetched_file_path = fetch_file(
512
+ "https://example.com/subfolder/other_file.txt",
513
+ )
514
+ assert (
515
+ fetched_file_path == data_home / "example.com" / "subfolder" / "other_file.txt"
516
+ )
517
+ assert fetched_file_path.read_text(encoding="utf-8") == other_data_file.read_text(
518
+ "utf-8"
519
+ )
520
+
521
+ expected_warning_msg = re.escape(
522
+ "Retry downloading from url: https://example.com/subfolder/invalid.txt"
523
+ )
524
+ with pytest.raises(HTTPError):
525
+ with pytest.warns(match=expected_warning_msg):
526
+ fetch_file(
527
+ "https://example.com/subfolder/invalid.txt",
528
+ delay=0,
529
+ )
530
+
531
+ local_subfolder = data_home / "example.com" / "subfolder"
532
+ assert sorted(local_subfolder.iterdir()) == [local_subfolder / "other_file.txt"]
533
+
534
+
535
+ def test_fetch_file_without_sha256(monkeypatch, tmpdir):
536
+ server_side = tmpdir.mkdir("server_side")
537
+ data_file = Path(server_side / "data.jsonl")
538
+ server_data = '{"a": 1, "b": 2}\n'
539
+ data_file.write_text(server_data, encoding="utf-8")
540
+
541
+ client_side = tmpdir.mkdir("client_side")
542
+
543
+ urlretrieve_mock = _mock_urlretrieve(server_side)
544
+ monkeypatch.setattr("sklearn.datasets._base.urlretrieve", urlretrieve_mock)
545
+
546
+ # The first call should trigger a download:
547
+ fetched_file_path = fetch_file(
548
+ "https://example.com/data.jsonl",
549
+ folder=client_side,
550
+ )
551
+ assert fetched_file_path == client_side / "data.jsonl"
552
+ assert fetched_file_path.read_text(encoding="utf-8") == server_data
553
+ assert urlretrieve_mock.call_count == 1
554
+
555
+ # Fetching again the same file to the same folder should do nothing:
556
+ fetched_file_path = fetch_file(
557
+ "https://example.com/data.jsonl",
558
+ folder=client_side,
559
+ )
560
+ assert fetched_file_path == client_side / "data.jsonl"
561
+ assert fetched_file_path.read_text(encoding="utf-8") == server_data
562
+ assert urlretrieve_mock.call_count == 1
563
+
564
+ # Deleting and calling again should re-download
565
+ fetched_file_path.unlink()
566
+ fetched_file_path = fetch_file(
567
+ "https://example.com/data.jsonl",
568
+ folder=client_side,
569
+ )
570
+ assert fetched_file_path == client_side / "data.jsonl"
571
+ assert fetched_file_path.read_text(encoding="utf-8") == server_data
572
+ assert urlretrieve_mock.call_count == 2
573
+
574
+
575
+ def test_fetch_file_with_sha256(monkeypatch, tmpdir):
576
+ server_side = tmpdir.mkdir("server_side")
577
+ data_file = Path(server_side / "data.jsonl")
578
+ server_data = '{"a": 1, "b": 2}\n'
579
+ data_file.write_text(server_data, encoding="utf-8")
580
+ expected_sha256 = hashlib.sha256(data_file.read_bytes()).hexdigest()
581
+
582
+ client_side = tmpdir.mkdir("client_side")
583
+
584
+ urlretrieve_mock = _mock_urlretrieve(server_side)
585
+ monkeypatch.setattr("sklearn.datasets._base.urlretrieve", urlretrieve_mock)
586
+
587
+ # The first call should trigger a download.
588
+ fetched_file_path = fetch_file(
589
+ "https://example.com/data.jsonl", folder=client_side, sha256=expected_sha256
590
+ )
591
+ assert fetched_file_path == client_side / "data.jsonl"
592
+ assert fetched_file_path.read_text(encoding="utf-8") == server_data
593
+ assert urlretrieve_mock.call_count == 1
594
+
595
+ # Fetching again the same file to the same folder should do nothing when
596
+ # the sha256 match:
597
+ fetched_file_path = fetch_file(
598
+ "https://example.com/data.jsonl", folder=client_side, sha256=expected_sha256
599
+ )
600
+ assert fetched_file_path == client_side / "data.jsonl"
601
+ assert fetched_file_path.read_text(encoding="utf-8") == server_data
602
+ assert urlretrieve_mock.call_count == 1
603
+
604
+ # Corrupting the local data should yield a warning and trigger a new download:
605
+ fetched_file_path.write_text("corrupted contents", encoding="utf-8")
606
+ expected_msg = (
607
+ r"SHA256 checksum of existing local file data.jsonl "
608
+ rf"\(.*\) differs from expected \({expected_sha256}\): "
609
+ r"re-downloading from https://example.com/data.jsonl \."
610
+ )
611
+ with pytest.warns(match=expected_msg):
612
+ fetched_file_path = fetch_file(
613
+ "https://example.com/data.jsonl", folder=client_side, sha256=expected_sha256
614
+ )
615
+ assert fetched_file_path == client_side / "data.jsonl"
616
+ assert fetched_file_path.read_text(encoding="utf-8") == server_data
617
+ assert urlretrieve_mock.call_count == 2
618
+
619
+ # Calling again should do nothing:
620
+ fetched_file_path = fetch_file(
621
+ "https://example.com/data.jsonl", folder=client_side, sha256=expected_sha256
622
+ )
623
+ assert fetched_file_path == client_side / "data.jsonl"
624
+ assert fetched_file_path.read_text(encoding="utf-8") == server_data
625
+ assert urlretrieve_mock.call_count == 2
626
+
627
+ # Deleting the local file and calling again should redownload without warning:
628
+ fetched_file_path.unlink()
629
+ fetched_file_path = fetch_file(
630
+ "https://example.com/data.jsonl", folder=client_side, sha256=expected_sha256
631
+ )
632
+ assert fetched_file_path == client_side / "data.jsonl"
633
+ assert fetched_file_path.read_text(encoding="utf-8") == server_data
634
+ assert urlretrieve_mock.call_count == 3
635
+
636
+ # Calling without a sha256 should also work without redownloading:
637
+ fetched_file_path = fetch_file(
638
+ "https://example.com/data.jsonl",
639
+ folder=client_side,
640
+ )
641
+ assert fetched_file_path == client_side / "data.jsonl"
642
+ assert fetched_file_path.read_text(encoding="utf-8") == server_data
643
+ assert urlretrieve_mock.call_count == 3
644
+
645
+ # Calling with a wrong sha256 should raise an informative exception:
646
+ non_matching_sha256 = "deadbabecafebeef"
647
+ expected_warning_msg = "differs from expected"
648
+ expected_error_msg = re.escape(
649
+ f"The SHA256 checksum of data.jsonl ({expected_sha256}) differs from "
650
+ f"expected ({non_matching_sha256})."
651
+ )
652
+ with pytest.raises(OSError, match=expected_error_msg):
653
+ with pytest.warns(match=expected_warning_msg):
654
+ fetch_file(
655
+ "https://example.com/data.jsonl",
656
+ folder=client_side,
657
+ sha256=non_matching_sha256,
658
+ )
miniconda3/envs/active_proaction/lib/python3.10/site-packages/sklearn/datasets/tests/test_california_housing.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Test the california_housing loader, if the data is available,
2
+ or if specifically requested via environment variable
3
+ (e.g. for CI jobs)."""
4
+
5
+ from functools import partial
6
+
7
+ import pytest
8
+
9
+ from sklearn.datasets.tests.test_common import check_return_X_y
10
+
11
+
12
+ def test_fetch(fetch_california_housing_fxt):
13
+ data = fetch_california_housing_fxt()
14
+ assert (20640, 8) == data.data.shape
15
+ assert (20640,) == data.target.shape
16
+ assert data.DESCR.startswith(".. _california_housing_dataset:")
17
+
18
+ # test return_X_y option
19
+ fetch_func = partial(fetch_california_housing_fxt)
20
+ check_return_X_y(data, fetch_func)
21
+
22
+
23
+ def test_fetch_asframe(fetch_california_housing_fxt):
24
+ pd = pytest.importorskip("pandas")
25
+ bunch = fetch_california_housing_fxt(as_frame=True)
26
+ frame = bunch.frame
27
+ assert hasattr(bunch, "frame") is True
28
+ assert frame.shape == (20640, 9)
29
+ assert isinstance(bunch.data, pd.DataFrame)
30
+ assert isinstance(bunch.target, pd.Series)
31
+
32
+
33
+ def test_pandas_dependency_message(fetch_california_housing_fxt, hide_available_pandas):
34
+ # Check that pandas is imported lazily and that an informative error
35
+ # message is raised when pandas is missing:
36
+ expected_msg = "fetch_california_housing with as_frame=True requires pandas"
37
+ with pytest.raises(ImportError, match=expected_msg):
38
+ fetch_california_housing_fxt(as_frame=True)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/sklearn/datasets/tests/test_common.py ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Test loaders for common functionality."""
2
+
3
+ import inspect
4
+ import os
5
+
6
+ import numpy as np
7
+ import pytest
8
+
9
+ import sklearn.datasets
10
+
11
+
12
+ def is_pillow_installed():
13
+ try:
14
+ import PIL # noqa: F401
15
+
16
+ return True
17
+ except ImportError:
18
+ return False
19
+
20
+
21
+ FETCH_PYTEST_MARKERS = {
22
+ "return_X_y": {
23
+ "fetch_20newsgroups": pytest.mark.xfail(
24
+ reason="X is a list and does not have a shape argument"
25
+ ),
26
+ "fetch_openml": pytest.mark.xfail(
27
+ reason="fetch_opeml requires a dataset name or id"
28
+ ),
29
+ "fetch_lfw_people": pytest.mark.skipif(
30
+ not is_pillow_installed(), reason="pillow is not installed"
31
+ ),
32
+ },
33
+ "as_frame": {
34
+ "fetch_openml": pytest.mark.xfail(
35
+ reason="fetch_opeml requires a dataset name or id"
36
+ ),
37
+ },
38
+ }
39
+
40
+
41
+ def check_pandas_dependency_message(fetch_func):
42
+ try:
43
+ import pandas # noqa: F401
44
+
45
+ pytest.skip("This test requires pandas to not be installed")
46
+ except ImportError:
47
+ # Check that pandas is imported lazily and that an informative error
48
+ # message is raised when pandas is missing:
49
+ name = fetch_func.__name__
50
+ expected_msg = f"{name} with as_frame=True requires pandas"
51
+ with pytest.raises(ImportError, match=expected_msg):
52
+ fetch_func(as_frame=True)
53
+
54
+
55
+ def check_return_X_y(bunch, dataset_func):
56
+ X_y_tuple = dataset_func(return_X_y=True)
57
+ assert isinstance(X_y_tuple, tuple)
58
+ assert X_y_tuple[0].shape == bunch.data.shape
59
+ assert X_y_tuple[1].shape == bunch.target.shape
60
+
61
+
62
+ def check_as_frame(
63
+ bunch, dataset_func, expected_data_dtype=None, expected_target_dtype=None
64
+ ):
65
+ pd = pytest.importorskip("pandas")
66
+ frame_bunch = dataset_func(as_frame=True)
67
+ assert hasattr(frame_bunch, "frame")
68
+ assert isinstance(frame_bunch.frame, pd.DataFrame)
69
+ assert isinstance(frame_bunch.data, pd.DataFrame)
70
+ assert frame_bunch.data.shape == bunch.data.shape
71
+ if frame_bunch.target.ndim > 1:
72
+ assert isinstance(frame_bunch.target, pd.DataFrame)
73
+ else:
74
+ assert isinstance(frame_bunch.target, pd.Series)
75
+ assert frame_bunch.target.shape[0] == bunch.target.shape[0]
76
+ if expected_data_dtype is not None:
77
+ assert np.all(frame_bunch.data.dtypes == expected_data_dtype)
78
+ if expected_target_dtype is not None:
79
+ assert np.all(frame_bunch.target.dtypes == expected_target_dtype)
80
+
81
+ # Test for return_X_y and as_frame=True
82
+ frame_X, frame_y = dataset_func(as_frame=True, return_X_y=True)
83
+ assert isinstance(frame_X, pd.DataFrame)
84
+ if frame_y.ndim > 1:
85
+ assert isinstance(frame_X, pd.DataFrame)
86
+ else:
87
+ assert isinstance(frame_y, pd.Series)
88
+
89
+
90
+ def _skip_network_tests():
91
+ return os.environ.get("SKLEARN_SKIP_NETWORK_TESTS", "1") == "1"
92
+
93
+
94
+ def _generate_func_supporting_param(param, dataset_type=("load", "fetch")):
95
+ markers_fetch = FETCH_PYTEST_MARKERS.get(param, {})
96
+ for name, obj in inspect.getmembers(sklearn.datasets):
97
+ if not inspect.isfunction(obj):
98
+ continue
99
+
100
+ is_dataset_type = any([name.startswith(t) for t in dataset_type])
101
+ is_support_param = param in inspect.signature(obj).parameters
102
+ if is_dataset_type and is_support_param:
103
+ # check if we should skip if we don't have network support
104
+ marks = [
105
+ pytest.mark.skipif(
106
+ condition=name.startswith("fetch") and _skip_network_tests(),
107
+ reason="Skip because fetcher requires internet network",
108
+ )
109
+ ]
110
+ if name in markers_fetch:
111
+ marks.append(markers_fetch[name])
112
+
113
+ yield pytest.param(name, obj, marks=marks)
114
+
115
+
116
+ @pytest.mark.parametrize(
117
+ "name, dataset_func", _generate_func_supporting_param("return_X_y")
118
+ )
119
+ def test_common_check_return_X_y(name, dataset_func):
120
+ bunch = dataset_func()
121
+ check_return_X_y(bunch, dataset_func)
122
+
123
+
124
+ @pytest.mark.parametrize(
125
+ "name, dataset_func", _generate_func_supporting_param("as_frame")
126
+ )
127
+ def test_common_check_as_frame(name, dataset_func):
128
+ bunch = dataset_func()
129
+ check_as_frame(bunch, dataset_func)
130
+
131
+
132
+ @pytest.mark.parametrize(
133
+ "name, dataset_func", _generate_func_supporting_param("as_frame")
134
+ )
135
+ def test_common_check_pandas_dependency(name, dataset_func):
136
+ check_pandas_dependency_message(dataset_func)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/sklearn/datasets/tests/test_covtype.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Test the covtype loader, if the data is available,
2
+ or if specifically requested via environment variable
3
+ (e.g. for CI jobs)."""
4
+
5
+ from functools import partial
6
+
7
+ import pytest
8
+
9
+ from sklearn.datasets.tests.test_common import check_return_X_y
10
+
11
+
12
+ def test_fetch(fetch_covtype_fxt, global_random_seed):
13
+ data1 = fetch_covtype_fxt(shuffle=True, random_state=global_random_seed)
14
+ data2 = fetch_covtype_fxt(shuffle=True, random_state=global_random_seed + 1)
15
+
16
+ X1, X2 = data1["data"], data2["data"]
17
+ assert (581012, 54) == X1.shape
18
+ assert X1.shape == X2.shape
19
+
20
+ assert X1.sum() == X2.sum()
21
+
22
+ y1, y2 = data1["target"], data2["target"]
23
+ assert (X1.shape[0],) == y1.shape
24
+ assert (X1.shape[0],) == y2.shape
25
+
26
+ descr_prefix = ".. _covtype_dataset:"
27
+ assert data1.DESCR.startswith(descr_prefix)
28
+ assert data2.DESCR.startswith(descr_prefix)
29
+
30
+ # test return_X_y option
31
+ fetch_func = partial(fetch_covtype_fxt)
32
+ check_return_X_y(data1, fetch_func)
33
+
34
+
35
+ def test_fetch_asframe(fetch_covtype_fxt):
36
+ pytest.importorskip("pandas")
37
+
38
+ bunch = fetch_covtype_fxt(as_frame=True)
39
+ assert hasattr(bunch, "frame")
40
+ frame = bunch.frame
41
+ assert frame.shape == (581012, 55)
42
+ assert bunch.data.shape == (581012, 54)
43
+ assert bunch.target.shape == (581012,)
44
+
45
+ column_names = set(frame.columns)
46
+
47
+ # enumerated names are added correctly
48
+ assert set(f"Wilderness_Area_{i}" for i in range(4)) < column_names
49
+ assert set(f"Soil_Type_{i}" for i in range(40)) < column_names
50
+
51
+
52
+ def test_pandas_dependency_message(fetch_covtype_fxt, hide_available_pandas):
53
+ expected_msg = "fetch_covtype with as_frame=True requires pandas"
54
+ with pytest.raises(ImportError, match=expected_msg):
55
+ fetch_covtype_fxt(as_frame=True)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/sklearn/datasets/tests/test_kddcup99.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Test kddcup99 loader, if the data is available,
2
+ or if specifically requested via environment variable
3
+ (e.g. for CI jobs).
4
+
5
+ Only 'percent10' mode is tested, as the full data
6
+ is too big to use in unit-testing.
7
+ """
8
+
9
+ from functools import partial
10
+
11
+ import pytest
12
+
13
+ from sklearn.datasets.tests.test_common import (
14
+ check_as_frame,
15
+ check_pandas_dependency_message,
16
+ check_return_X_y,
17
+ )
18
+
19
+
20
+ @pytest.mark.parametrize("as_frame", [True, False])
21
+ @pytest.mark.parametrize(
22
+ "subset, n_samples, n_features",
23
+ [
24
+ (None, 494021, 41),
25
+ ("SA", 100655, 41),
26
+ ("SF", 73237, 4),
27
+ ("http", 58725, 3),
28
+ ("smtp", 9571, 3),
29
+ ],
30
+ )
31
+ def test_fetch_kddcup99_percent10(
32
+ fetch_kddcup99_fxt, as_frame, subset, n_samples, n_features
33
+ ):
34
+ data = fetch_kddcup99_fxt(subset=subset, as_frame=as_frame)
35
+ assert data.data.shape == (n_samples, n_features)
36
+ assert data.target.shape == (n_samples,)
37
+ if as_frame:
38
+ assert data.frame.shape == (n_samples, n_features + 1)
39
+ assert data.DESCR.startswith(".. _kddcup99_dataset:")
40
+
41
+
42
+ def test_fetch_kddcup99_return_X_y(fetch_kddcup99_fxt):
43
+ fetch_func = partial(fetch_kddcup99_fxt, subset="smtp")
44
+ data = fetch_func()
45
+ check_return_X_y(data, fetch_func)
46
+
47
+
48
+ def test_fetch_kddcup99_as_frame(fetch_kddcup99_fxt):
49
+ bunch = fetch_kddcup99_fxt()
50
+ check_as_frame(bunch, fetch_kddcup99_fxt)
51
+
52
+
53
+ def test_fetch_kddcup99_shuffle(fetch_kddcup99_fxt):
54
+ dataset = fetch_kddcup99_fxt(
55
+ random_state=0,
56
+ subset="SA",
57
+ percent10=True,
58
+ )
59
+ dataset_shuffled = fetch_kddcup99_fxt(
60
+ random_state=0,
61
+ subset="SA",
62
+ shuffle=True,
63
+ percent10=True,
64
+ )
65
+ assert set(dataset["target"]) == set(dataset_shuffled["target"])
66
+ assert dataset_shuffled.data.shape == dataset.data.shape
67
+ assert dataset_shuffled.target.shape == dataset.target.shape
68
+
69
+
70
+ def test_pandas_dependency_message(fetch_kddcup99_fxt, hide_available_pandas):
71
+ check_pandas_dependency_message(fetch_kddcup99_fxt)
72
+
73
+
74
+ def test_corrupted_file_error_message(fetch_kddcup99_fxt, tmp_path):
75
+ """Check that a nice error message is raised when cache is corrupted."""
76
+ kddcup99_dir = tmp_path / "kddcup99_10-py3"
77
+ kddcup99_dir.mkdir()
78
+ samples_path = kddcup99_dir / "samples"
79
+
80
+ with samples_path.open("wb") as f:
81
+ f.write(b"THIS IS CORRUPTED")
82
+
83
+ msg = (
84
+ "The cache for fetch_kddcup99 is invalid, please "
85
+ f"delete {kddcup99_dir} and run the fetch_kddcup99 again"
86
+ )
87
+
88
+ with pytest.raises(OSError, match=msg):
89
+ fetch_kddcup99_fxt(data_home=str(tmp_path))
miniconda3/envs/active_proaction/lib/python3.10/site-packages/sklearn/datasets/tests/test_lfw.py ADDED
@@ -0,0 +1,229 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """This test for the LFW require medium-size data downloading and processing
2
+
3
+ If the data has not been already downloaded by running the examples,
4
+ the tests won't run (skipped).
5
+
6
+ If the test are run, the first execution will be long (typically a bit
7
+ more than a couple of minutes) but as the dataset loader is leveraging
8
+ joblib, successive runs will be fast (less than 200ms).
9
+ """
10
+
11
+ import random
12
+ from functools import partial
13
+
14
+ import numpy as np
15
+ import pytest
16
+
17
+ from sklearn.datasets import fetch_lfw_pairs, fetch_lfw_people
18
+ from sklearn.datasets.tests.test_common import check_return_X_y
19
+ from sklearn.utils._testing import assert_array_equal
20
+
21
+ FAKE_NAMES = [
22
+ "Abdelatif_Smith",
23
+ "Abhati_Kepler",
24
+ "Camara_Alvaro",
25
+ "Chen_Dupont",
26
+ "John_Lee",
27
+ "Lin_Bauman",
28
+ "Onur_Lopez",
29
+ ]
30
+
31
+
32
+ @pytest.fixture(scope="module")
33
+ def mock_empty_data_home(tmp_path_factory):
34
+ data_dir = tmp_path_factory.mktemp("scikit_learn_empty_test")
35
+
36
+ yield data_dir
37
+
38
+
39
+ @pytest.fixture(scope="module")
40
+ def mock_data_home(tmp_path_factory):
41
+ """Test fixture run once and common to all tests of this module"""
42
+ Image = pytest.importorskip("PIL.Image")
43
+
44
+ data_dir = tmp_path_factory.mktemp("scikit_learn_lfw_test")
45
+ lfw_home = data_dir / "lfw_home"
46
+ lfw_home.mkdir(parents=True, exist_ok=True)
47
+
48
+ random_state = random.Random(42)
49
+ np_rng = np.random.RandomState(42)
50
+
51
+ # generate some random jpeg files for each person
52
+ counts = {}
53
+ for name in FAKE_NAMES:
54
+ folder_name = lfw_home / "lfw_funneled" / name
55
+ folder_name.mkdir(parents=True, exist_ok=True)
56
+
57
+ n_faces = np_rng.randint(1, 5)
58
+ counts[name] = n_faces
59
+ for i in range(n_faces):
60
+ file_path = folder_name / (name + "_%04d.jpg" % i)
61
+ uniface = np_rng.randint(0, 255, size=(250, 250, 3))
62
+ img = Image.fromarray(uniface.astype(np.uint8))
63
+ img.save(file_path)
64
+
65
+ # add some random file pollution to test robustness
66
+ (lfw_home / "lfw_funneled" / ".test.swp").write_bytes(
67
+ b"Text file to be ignored by the dataset loader."
68
+ )
69
+
70
+ # generate some pairing metadata files using the same format as LFW
71
+ with open(lfw_home / "pairsDevTrain.txt", "wb") as f:
72
+ f.write(b"10\n")
73
+ more_than_two = [name for name, count in counts.items() if count >= 2]
74
+ for i in range(5):
75
+ name = random_state.choice(more_than_two)
76
+ first, second = random_state.sample(range(counts[name]), 2)
77
+ f.write(("%s\t%d\t%d\n" % (name, first, second)).encode())
78
+
79
+ for i in range(5):
80
+ first_name, second_name = random_state.sample(FAKE_NAMES, 2)
81
+ first_index = np_rng.choice(np.arange(counts[first_name]))
82
+ second_index = np_rng.choice(np.arange(counts[second_name]))
83
+ f.write(
84
+ (
85
+ "%s\t%d\t%s\t%d\n"
86
+ % (first_name, first_index, second_name, second_index)
87
+ ).encode()
88
+ )
89
+
90
+ (lfw_home / "pairsDevTest.txt").write_bytes(
91
+ b"Fake place holder that won't be tested"
92
+ )
93
+ (lfw_home / "pairs.txt").write_bytes(b"Fake place holder that won't be tested")
94
+
95
+ yield data_dir
96
+
97
+
98
+ def test_load_empty_lfw_people(mock_empty_data_home):
99
+ with pytest.raises(OSError):
100
+ fetch_lfw_people(data_home=mock_empty_data_home, download_if_missing=False)
101
+
102
+
103
+ def test_load_fake_lfw_people(mock_data_home):
104
+ lfw_people = fetch_lfw_people(
105
+ data_home=mock_data_home, min_faces_per_person=3, download_if_missing=False
106
+ )
107
+
108
+ # The data is croped around the center as a rectangular bounding box
109
+ # around the face. Colors are converted to gray levels:
110
+ assert lfw_people.images.shape == (10, 62, 47)
111
+ assert lfw_people.data.shape == (10, 2914)
112
+
113
+ # the target is array of person integer ids
114
+ assert_array_equal(lfw_people.target, [2, 0, 1, 0, 2, 0, 2, 1, 1, 2])
115
+
116
+ # names of the persons can be found using the target_names array
117
+ expected_classes = ["Abdelatif Smith", "Abhati Kepler", "Onur Lopez"]
118
+ assert_array_equal(lfw_people.target_names, expected_classes)
119
+
120
+ # It is possible to ask for the original data without any croping or color
121
+ # conversion and not limit on the number of picture per person
122
+ lfw_people = fetch_lfw_people(
123
+ data_home=mock_data_home,
124
+ resize=None,
125
+ slice_=None,
126
+ color=True,
127
+ download_if_missing=False,
128
+ )
129
+ assert lfw_people.images.shape == (17, 250, 250, 3)
130
+ assert lfw_people.DESCR.startswith(".. _labeled_faces_in_the_wild_dataset:")
131
+
132
+ # the ids and class names are the same as previously
133
+ assert_array_equal(
134
+ lfw_people.target, [0, 0, 1, 6, 5, 6, 3, 6, 0, 3, 6, 1, 2, 4, 5, 1, 2]
135
+ )
136
+ assert_array_equal(
137
+ lfw_people.target_names,
138
+ [
139
+ "Abdelatif Smith",
140
+ "Abhati Kepler",
141
+ "Camara Alvaro",
142
+ "Chen Dupont",
143
+ "John Lee",
144
+ "Lin Bauman",
145
+ "Onur Lopez",
146
+ ],
147
+ )
148
+
149
+ # test return_X_y option
150
+ fetch_func = partial(
151
+ fetch_lfw_people,
152
+ data_home=mock_data_home,
153
+ resize=None,
154
+ slice_=None,
155
+ color=True,
156
+ download_if_missing=False,
157
+ )
158
+ check_return_X_y(lfw_people, fetch_func)
159
+
160
+
161
+ def test_load_fake_lfw_people_too_restrictive(mock_data_home):
162
+ with pytest.raises(ValueError):
163
+ fetch_lfw_people(
164
+ data_home=mock_data_home,
165
+ min_faces_per_person=100,
166
+ download_if_missing=False,
167
+ )
168
+
169
+
170
+ def test_load_empty_lfw_pairs(mock_empty_data_home):
171
+ with pytest.raises(OSError):
172
+ fetch_lfw_pairs(data_home=mock_empty_data_home, download_if_missing=False)
173
+
174
+
175
+ def test_load_fake_lfw_pairs(mock_data_home):
176
+ lfw_pairs_train = fetch_lfw_pairs(
177
+ data_home=mock_data_home, download_if_missing=False
178
+ )
179
+
180
+ # The data is croped around the center as a rectangular bounding box
181
+ # around the face. Colors are converted to gray levels:
182
+ assert lfw_pairs_train.pairs.shape == (10, 2, 62, 47)
183
+
184
+ # the target is whether the person is the same or not
185
+ assert_array_equal(lfw_pairs_train.target, [1, 1, 1, 1, 1, 0, 0, 0, 0, 0])
186
+
187
+ # names of the persons can be found using the target_names array
188
+ expected_classes = ["Different persons", "Same person"]
189
+ assert_array_equal(lfw_pairs_train.target_names, expected_classes)
190
+
191
+ # It is possible to ask for the original data without any croping or color
192
+ # conversion
193
+ lfw_pairs_train = fetch_lfw_pairs(
194
+ data_home=mock_data_home,
195
+ resize=None,
196
+ slice_=None,
197
+ color=True,
198
+ download_if_missing=False,
199
+ )
200
+ assert lfw_pairs_train.pairs.shape == (10, 2, 250, 250, 3)
201
+
202
+ # the ids and class names are the same as previously
203
+ assert_array_equal(lfw_pairs_train.target, [1, 1, 1, 1, 1, 0, 0, 0, 0, 0])
204
+ assert_array_equal(lfw_pairs_train.target_names, expected_classes)
205
+
206
+ assert lfw_pairs_train.DESCR.startswith(".. _labeled_faces_in_the_wild_dataset:")
207
+
208
+
209
+ def test_fetch_lfw_people_internal_cropping(mock_data_home):
210
+ """Check that we properly crop the images.
211
+
212
+ Non-regression test for:
213
+ https://github.com/scikit-learn/scikit-learn/issues/24942
214
+ """
215
+ # If cropping was not done properly and we don't resize the images, the images would
216
+ # have their original size (250x250) and the image would not fit in the NumPy array
217
+ # pre-allocated based on `slice_` parameter.
218
+ slice_ = (slice(70, 195), slice(78, 172))
219
+ lfw = fetch_lfw_people(
220
+ data_home=mock_data_home,
221
+ min_faces_per_person=3,
222
+ download_if_missing=False,
223
+ resize=None,
224
+ slice_=slice_,
225
+ )
226
+ assert lfw.images[0].shape == (
227
+ slice_[0].stop - slice_[0].start,
228
+ slice_[1].stop - slice_[1].start,
229
+ )
miniconda3/envs/active_proaction/lib/python3.10/site-packages/sklearn/datasets/tests/test_olivetti_faces.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Test Olivetti faces fetcher, if the data is available,
2
+ or if specifically requested via environment variable
3
+ (e.g. for CI jobs)."""
4
+
5
+ import numpy as np
6
+
7
+ from sklearn.datasets.tests.test_common import check_return_X_y
8
+ from sklearn.utils import Bunch
9
+ from sklearn.utils._testing import assert_array_equal
10
+
11
+
12
+ def test_olivetti_faces(fetch_olivetti_faces_fxt):
13
+ data = fetch_olivetti_faces_fxt(shuffle=True, random_state=0)
14
+
15
+ assert isinstance(data, Bunch)
16
+ for expected_keys in ("data", "images", "target", "DESCR"):
17
+ assert expected_keys in data.keys()
18
+
19
+ assert data.data.shape == (400, 4096)
20
+ assert data.images.shape == (400, 64, 64)
21
+ assert data.target.shape == (400,)
22
+ assert_array_equal(np.unique(np.sort(data.target)), np.arange(40))
23
+ assert data.DESCR.startswith(".. _olivetti_faces_dataset:")
24
+
25
+ # test the return_X_y option
26
+ check_return_X_y(data, fetch_olivetti_faces_fxt)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/sklearn/datasets/tests/test_openml.py ADDED
@@ -0,0 +1,1636 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Test the openml loader."""
2
+
3
+ import gzip
4
+ import json
5
+ import os
6
+ import re
7
+ from functools import partial
8
+ from importlib import resources
9
+ from io import BytesIO
10
+ from urllib.error import HTTPError
11
+
12
+ import numpy as np
13
+ import pytest
14
+ import scipy.sparse
15
+
16
+ import sklearn
17
+ from sklearn import config_context
18
+ from sklearn.datasets import fetch_openml as fetch_openml_orig
19
+ from sklearn.datasets._openml import (
20
+ _get_local_path,
21
+ _open_openml_url,
22
+ _retry_with_clean_cache,
23
+ )
24
+ from sklearn.utils import Bunch
25
+ from sklearn.utils._optional_dependencies import check_pandas_support
26
+ from sklearn.utils._testing import (
27
+ SkipTest,
28
+ assert_allclose,
29
+ assert_array_equal,
30
+ )
31
+
32
+ OPENML_TEST_DATA_MODULE = "sklearn.datasets.tests.data.openml"
33
+ # if True, urlopen will be monkey patched to only use local files
34
+ test_offline = True
35
+ _MONKEY_PATCH_LOCAL_OPENML_PATH = "data/v1/download/{}"
36
+
37
+
38
+ class _MockHTTPResponse:
39
+ def __init__(self, data, is_gzip):
40
+ self.data = data
41
+ self.is_gzip = is_gzip
42
+
43
+ def read(self, amt=-1):
44
+ return self.data.read(amt)
45
+
46
+ def close(self):
47
+ self.data.close()
48
+
49
+ def info(self):
50
+ if self.is_gzip:
51
+ return {"Content-Encoding": "gzip"}
52
+ return {}
53
+
54
+ def __iter__(self):
55
+ return iter(self.data)
56
+
57
+ def __enter__(self):
58
+ return self
59
+
60
+ def __exit__(self, exc_type, exc_val, exc_tb):
61
+ return False
62
+
63
+
64
+ # Disable the disk-based cache when testing `fetch_openml`:
65
+ # the mock data in sklearn/datasets/tests/data/openml/ is not always consistent
66
+ # with the version on openml.org. If one were to load the dataset outside of
67
+ # the tests, it may result in data that does not represent openml.org.
68
+ fetch_openml = partial(fetch_openml_orig, data_home=None)
69
+
70
+
71
+ def _monkey_patch_webbased_functions(context, data_id, gzip_response):
72
+ # monkey patches the urlopen function. Important note: Do NOT use this
73
+ # in combination with a regular cache directory, as the files that are
74
+ # stored as cache should not be mixed up with real openml datasets
75
+ url_prefix_data_description = "https://api.openml.org/api/v1/json/data/"
76
+ url_prefix_data_features = "https://api.openml.org/api/v1/json/data/features/"
77
+ url_prefix_download_data = "https://www.openml.org/data/v1/download"
78
+ url_prefix_data_list = "https://api.openml.org/api/v1/json/data/list/"
79
+
80
+ path_suffix = ".gz"
81
+ read_fn = gzip.open
82
+
83
+ data_module = OPENML_TEST_DATA_MODULE + "." + f"id_{data_id}"
84
+
85
+ def _file_name(url, suffix):
86
+ output = (
87
+ re.sub(r"\W", "-", url[len("https://api.openml.org/") :])
88
+ + suffix
89
+ + path_suffix
90
+ )
91
+ # Shorten the filenames to have better compatibility with windows 10
92
+ # and filenames > 260 characters
93
+ return (
94
+ output.replace("-json-data-list", "-jdl")
95
+ .replace("-json-data-features", "-jdf")
96
+ .replace("-json-data-qualities", "-jdq")
97
+ .replace("-json-data", "-jd")
98
+ .replace("-data_name", "-dn")
99
+ .replace("-download", "-dl")
100
+ .replace("-limit", "-l")
101
+ .replace("-data_version", "-dv")
102
+ .replace("-status", "-s")
103
+ .replace("-deactivated", "-dact")
104
+ .replace("-active", "-act")
105
+ )
106
+
107
+ def _mock_urlopen_shared(url, has_gzip_header, expected_prefix, suffix):
108
+ assert url.startswith(expected_prefix), (
109
+ f"{expected_prefix!r} does not match {url!r}"
110
+ )
111
+
112
+ data_file_name = _file_name(url, suffix)
113
+ data_file_path = resources.files(data_module) / data_file_name
114
+
115
+ with data_file_path.open("rb") as f:
116
+ if has_gzip_header and gzip_response:
117
+ fp = BytesIO(f.read())
118
+ return _MockHTTPResponse(fp, True)
119
+ else:
120
+ decompressed_f = read_fn(f, "rb")
121
+ fp = BytesIO(decompressed_f.read())
122
+ return _MockHTTPResponse(fp, False)
123
+
124
+ def _mock_urlopen_data_description(url, has_gzip_header):
125
+ return _mock_urlopen_shared(
126
+ url=url,
127
+ has_gzip_header=has_gzip_header,
128
+ expected_prefix=url_prefix_data_description,
129
+ suffix=".json",
130
+ )
131
+
132
+ def _mock_urlopen_data_features(url, has_gzip_header):
133
+ return _mock_urlopen_shared(
134
+ url=url,
135
+ has_gzip_header=has_gzip_header,
136
+ expected_prefix=url_prefix_data_features,
137
+ suffix=".json",
138
+ )
139
+
140
+ def _mock_urlopen_download_data(url, has_gzip_header):
141
+ # For simplicity the mock filenames don't contain the filename, i.e.
142
+ # the last part of the data description url after the last /.
143
+ # For example for id_1, data description download url is:
144
+ # gunzip -c sklearn/datasets/tests/data/openml/id_1/api-v1-jd-1.json.gz | grep '"url" # noqa: E501
145
+ # "https:\/\/www.openml.org\/data\/v1\/download\/1\/anneal.arff"
146
+ # but the mock filename does not contain anneal.arff and is:
147
+ # sklearn/datasets/tests/data/openml/id_1/data-v1-dl-1.arff.gz.
148
+ # We only keep the part of the url before the last /
149
+ url_without_filename = url.rsplit("/", 1)[0]
150
+
151
+ return _mock_urlopen_shared(
152
+ url=url_without_filename,
153
+ has_gzip_header=has_gzip_header,
154
+ expected_prefix=url_prefix_download_data,
155
+ suffix=".arff",
156
+ )
157
+
158
+ def _mock_urlopen_data_list(url, has_gzip_header):
159
+ assert url.startswith(url_prefix_data_list), (
160
+ f"{url_prefix_data_list!r} does not match {url!r}"
161
+ )
162
+
163
+ data_file_name = _file_name(url, ".json")
164
+ data_file_path = resources.files(data_module) / data_file_name
165
+
166
+ # load the file itself, to simulate a http error
167
+ with data_file_path.open("rb") as f:
168
+ decompressed_f = read_fn(f, "rb")
169
+ decoded_s = decompressed_f.read().decode("utf-8")
170
+ json_data = json.loads(decoded_s)
171
+ if "error" in json_data:
172
+ raise HTTPError(
173
+ url=None, code=412, msg="Simulated mock error", hdrs=None, fp=BytesIO()
174
+ )
175
+
176
+ with data_file_path.open("rb") as f:
177
+ if has_gzip_header:
178
+ fp = BytesIO(f.read())
179
+ return _MockHTTPResponse(fp, True)
180
+ else:
181
+ decompressed_f = read_fn(f, "rb")
182
+ fp = BytesIO(decompressed_f.read())
183
+ return _MockHTTPResponse(fp, False)
184
+
185
+ def _mock_urlopen(request, *args, **kwargs):
186
+ url = request.get_full_url()
187
+ has_gzip_header = request.get_header("Accept-encoding") == "gzip"
188
+ if url.startswith(url_prefix_data_list):
189
+ return _mock_urlopen_data_list(url, has_gzip_header)
190
+ elif url.startswith(url_prefix_data_features):
191
+ return _mock_urlopen_data_features(url, has_gzip_header)
192
+ elif url.startswith(url_prefix_download_data):
193
+ return _mock_urlopen_download_data(url, has_gzip_header)
194
+ elif url.startswith(url_prefix_data_description):
195
+ return _mock_urlopen_data_description(url, has_gzip_header)
196
+ else:
197
+ raise ValueError("Unknown mocking URL pattern: %s" % url)
198
+
199
+ # XXX: Global variable
200
+ if test_offline:
201
+ context.setattr(sklearn.datasets._openml, "urlopen", _mock_urlopen)
202
+
203
+
204
+ ###############################################################################
205
+ # Test the behaviour of `fetch_openml` depending of the input parameters.
206
+
207
+
208
+ @pytest.mark.parametrize(
209
+ "data_id, dataset_params, n_samples, n_features, n_targets",
210
+ [
211
+ # iris
212
+ (61, {"data_id": 61}, 150, 4, 1),
213
+ (61, {"name": "iris", "version": 1}, 150, 4, 1),
214
+ # anneal
215
+ (2, {"data_id": 2}, 11, 38, 1),
216
+ (2, {"name": "anneal", "version": 1}, 11, 38, 1),
217
+ # cpu
218
+ (561, {"data_id": 561}, 209, 7, 1),
219
+ (561, {"name": "cpu", "version": 1}, 209, 7, 1),
220
+ # emotions
221
+ (40589, {"data_id": 40589}, 13, 72, 6),
222
+ # adult-census
223
+ (1119, {"data_id": 1119}, 10, 14, 1),
224
+ (1119, {"name": "adult-census"}, 10, 14, 1),
225
+ # miceprotein
226
+ (40966, {"data_id": 40966}, 7, 77, 1),
227
+ (40966, {"name": "MiceProtein"}, 7, 77, 1),
228
+ # titanic
229
+ (40945, {"data_id": 40945}, 1309, 13, 1),
230
+ ],
231
+ )
232
+ @pytest.mark.parametrize("parser", ["liac-arff", "pandas"])
233
+ @pytest.mark.parametrize("gzip_response", [True, False])
234
+ def test_fetch_openml_as_frame_true(
235
+ monkeypatch,
236
+ data_id,
237
+ dataset_params,
238
+ n_samples,
239
+ n_features,
240
+ n_targets,
241
+ parser,
242
+ gzip_response,
243
+ ):
244
+ """Check the behaviour of `fetch_openml` with `as_frame=True`.
245
+
246
+ Fetch by ID and/or name (depending if the file was previously cached).
247
+ """
248
+ pd = pytest.importorskip("pandas")
249
+
250
+ _monkey_patch_webbased_functions(monkeypatch, data_id, gzip_response=gzip_response)
251
+ bunch = fetch_openml(
252
+ as_frame=True,
253
+ cache=False,
254
+ parser=parser,
255
+ **dataset_params,
256
+ )
257
+
258
+ assert int(bunch.details["id"]) == data_id
259
+ assert isinstance(bunch, Bunch)
260
+
261
+ assert isinstance(bunch.frame, pd.DataFrame)
262
+ assert bunch.frame.shape == (n_samples, n_features + n_targets)
263
+
264
+ assert isinstance(bunch.data, pd.DataFrame)
265
+ assert bunch.data.shape == (n_samples, n_features)
266
+
267
+ if n_targets == 1:
268
+ assert isinstance(bunch.target, pd.Series)
269
+ assert bunch.target.shape == (n_samples,)
270
+ else:
271
+ assert isinstance(bunch.target, pd.DataFrame)
272
+ assert bunch.target.shape == (n_samples, n_targets)
273
+
274
+ assert bunch.categories is None
275
+
276
+
277
+ @pytest.mark.parametrize(
278
+ "data_id, dataset_params, n_samples, n_features, n_targets",
279
+ [
280
+ # iris
281
+ (61, {"data_id": 61}, 150, 4, 1),
282
+ (61, {"name": "iris", "version": 1}, 150, 4, 1),
283
+ # anneal
284
+ (2, {"data_id": 2}, 11, 38, 1),
285
+ (2, {"name": "anneal", "version": 1}, 11, 38, 1),
286
+ # cpu
287
+ (561, {"data_id": 561}, 209, 7, 1),
288
+ (561, {"name": "cpu", "version": 1}, 209, 7, 1),
289
+ # emotions
290
+ (40589, {"data_id": 40589}, 13, 72, 6),
291
+ # adult-census
292
+ (1119, {"data_id": 1119}, 10, 14, 1),
293
+ (1119, {"name": "adult-census"}, 10, 14, 1),
294
+ # miceprotein
295
+ (40966, {"data_id": 40966}, 7, 77, 1),
296
+ (40966, {"name": "MiceProtein"}, 7, 77, 1),
297
+ ],
298
+ )
299
+ @pytest.mark.parametrize("parser", ["liac-arff", "pandas"])
300
+ def test_fetch_openml_as_frame_false(
301
+ monkeypatch,
302
+ data_id,
303
+ dataset_params,
304
+ n_samples,
305
+ n_features,
306
+ n_targets,
307
+ parser,
308
+ ):
309
+ """Check the behaviour of `fetch_openml` with `as_frame=False`.
310
+
311
+ Fetch both by ID and/or name + version.
312
+ """
313
+ pytest.importorskip("pandas")
314
+
315
+ _monkey_patch_webbased_functions(monkeypatch, data_id, gzip_response=True)
316
+ bunch = fetch_openml(
317
+ as_frame=False,
318
+ cache=False,
319
+ parser=parser,
320
+ **dataset_params,
321
+ )
322
+ assert int(bunch.details["id"]) == data_id
323
+ assert isinstance(bunch, Bunch)
324
+
325
+ assert bunch.frame is None
326
+
327
+ assert isinstance(bunch.data, np.ndarray)
328
+ assert bunch.data.shape == (n_samples, n_features)
329
+
330
+ assert isinstance(bunch.target, np.ndarray)
331
+ if n_targets == 1:
332
+ assert bunch.target.shape == (n_samples,)
333
+ else:
334
+ assert bunch.target.shape == (n_samples, n_targets)
335
+
336
+ assert isinstance(bunch.categories, dict)
337
+
338
+
339
+ @pytest.mark.parametrize("data_id", [61, 1119, 40945])
340
+ def test_fetch_openml_consistency_parser(monkeypatch, data_id):
341
+ """Check the consistency of the LIAC-ARFF and pandas parsers."""
342
+ pd = pytest.importorskip("pandas")
343
+
344
+ _monkey_patch_webbased_functions(monkeypatch, data_id, gzip_response=True)
345
+ bunch_liac = fetch_openml(
346
+ data_id=data_id,
347
+ as_frame=True,
348
+ cache=False,
349
+ parser="liac-arff",
350
+ )
351
+ bunch_pandas = fetch_openml(
352
+ data_id=data_id,
353
+ as_frame=True,
354
+ cache=False,
355
+ parser="pandas",
356
+ )
357
+
358
+ # The data frames for the input features should match up to some numerical
359
+ # dtype conversions (e.g. float64 <=> Int64) due to limitations of the
360
+ # LIAC-ARFF parser.
361
+ data_liac, data_pandas = bunch_liac.data, bunch_pandas.data
362
+
363
+ def convert_numerical_dtypes(series):
364
+ pandas_series = data_pandas[series.name]
365
+ if pd.api.types.is_numeric_dtype(pandas_series):
366
+ return series.astype(pandas_series.dtype)
367
+ else:
368
+ return series
369
+
370
+ data_liac_with_fixed_dtypes = data_liac.apply(convert_numerical_dtypes)
371
+ pd.testing.assert_frame_equal(data_liac_with_fixed_dtypes, data_pandas)
372
+
373
+ # Let's also check that the .frame attributes also match
374
+ frame_liac, frame_pandas = bunch_liac.frame, bunch_pandas.frame
375
+
376
+ # Note that the .frame attribute is a superset of the .data attribute:
377
+ pd.testing.assert_frame_equal(frame_pandas[bunch_pandas.feature_names], data_pandas)
378
+
379
+ # However the remaining columns, typically the target(s), are not necessarily
380
+ # dtyped similarly by both parsers due to limitations of the LIAC-ARFF parser.
381
+ # Therefore, extra dtype conversions are required for those columns:
382
+
383
+ def convert_numerical_and_categorical_dtypes(series):
384
+ pandas_series = frame_pandas[series.name]
385
+ if pd.api.types.is_numeric_dtype(pandas_series):
386
+ return series.astype(pandas_series.dtype)
387
+ elif isinstance(pandas_series.dtype, pd.CategoricalDtype):
388
+ # Compare categorical features by converting categorical liac uses
389
+ # strings to denote the categories, we rename the categories to make
390
+ # them comparable to the pandas parser. Fixing this behavior in
391
+ # LIAC-ARFF would allow to check the consistency in the future but
392
+ # we do not plan to maintain the LIAC-ARFF on the long term.
393
+ return series.cat.rename_categories(pandas_series.cat.categories)
394
+ else:
395
+ return series
396
+
397
+ frame_liac_with_fixed_dtypes = frame_liac.apply(
398
+ convert_numerical_and_categorical_dtypes
399
+ )
400
+ pd.testing.assert_frame_equal(frame_liac_with_fixed_dtypes, frame_pandas)
401
+
402
+
403
+ @pytest.mark.parametrize("parser", ["liac-arff", "pandas"])
404
+ def test_fetch_openml_equivalence_array_dataframe(monkeypatch, parser):
405
+ """Check the equivalence of the dataset when using `as_frame=False` and
406
+ `as_frame=True`.
407
+ """
408
+ pytest.importorskip("pandas")
409
+
410
+ data_id = 61
411
+ _monkey_patch_webbased_functions(monkeypatch, data_id, gzip_response=True)
412
+ bunch_as_frame_true = fetch_openml(
413
+ data_id=data_id,
414
+ as_frame=True,
415
+ cache=False,
416
+ parser=parser,
417
+ )
418
+
419
+ bunch_as_frame_false = fetch_openml(
420
+ data_id=data_id,
421
+ as_frame=False,
422
+ cache=False,
423
+ parser=parser,
424
+ )
425
+
426
+ assert_allclose(bunch_as_frame_false.data, bunch_as_frame_true.data)
427
+ assert_array_equal(bunch_as_frame_false.target, bunch_as_frame_true.target)
428
+
429
+
430
+ @pytest.mark.parametrize("parser", ["liac-arff", "pandas"])
431
+ def test_fetch_openml_iris_pandas(monkeypatch, parser):
432
+ """Check fetching on a numerical only dataset with string labels."""
433
+ pd = pytest.importorskip("pandas")
434
+ CategoricalDtype = pd.api.types.CategoricalDtype
435
+ data_id = 61
436
+ data_shape = (150, 4)
437
+ target_shape = (150,)
438
+ frame_shape = (150, 5)
439
+
440
+ target_dtype = CategoricalDtype(
441
+ ["Iris-setosa", "Iris-versicolor", "Iris-virginica"]
442
+ )
443
+ data_dtypes = [np.float64] * 4
444
+ data_names = ["sepallength", "sepalwidth", "petallength", "petalwidth"]
445
+ target_name = "class"
446
+
447
+ _monkey_patch_webbased_functions(monkeypatch, data_id, True)
448
+
449
+ bunch = fetch_openml(
450
+ data_id=data_id,
451
+ as_frame=True,
452
+ cache=False,
453
+ parser=parser,
454
+ )
455
+ data = bunch.data
456
+ target = bunch.target
457
+ frame = bunch.frame
458
+
459
+ assert isinstance(data, pd.DataFrame)
460
+ assert np.all(data.dtypes == data_dtypes)
461
+ assert data.shape == data_shape
462
+ assert np.all(data.columns == data_names)
463
+ assert np.all(bunch.feature_names == data_names)
464
+ assert bunch.target_names == [target_name]
465
+
466
+ assert isinstance(target, pd.Series)
467
+ assert target.dtype == target_dtype
468
+ assert target.shape == target_shape
469
+ assert target.name == target_name
470
+ assert target.index.is_unique
471
+
472
+ assert isinstance(frame, pd.DataFrame)
473
+ assert frame.shape == frame_shape
474
+ assert np.all(frame.dtypes == data_dtypes + [target_dtype])
475
+ assert frame.index.is_unique
476
+
477
+
478
+ @pytest.mark.parametrize("parser", ["liac-arff", "pandas"])
479
+ @pytest.mark.parametrize("target_column", ["petalwidth", ["petalwidth", "petallength"]])
480
+ def test_fetch_openml_forcing_targets(monkeypatch, parser, target_column):
481
+ """Check that we can force the target to not be the default target."""
482
+ pd = pytest.importorskip("pandas")
483
+
484
+ data_id = 61
485
+ _monkey_patch_webbased_functions(monkeypatch, data_id, True)
486
+ bunch_forcing_target = fetch_openml(
487
+ data_id=data_id,
488
+ as_frame=True,
489
+ cache=False,
490
+ target_column=target_column,
491
+ parser=parser,
492
+ )
493
+ bunch_default = fetch_openml(
494
+ data_id=data_id,
495
+ as_frame=True,
496
+ cache=False,
497
+ parser=parser,
498
+ )
499
+
500
+ pd.testing.assert_frame_equal(bunch_forcing_target.frame, bunch_default.frame)
501
+ if isinstance(target_column, list):
502
+ pd.testing.assert_index_equal(
503
+ bunch_forcing_target.target.columns, pd.Index(target_column)
504
+ )
505
+ assert bunch_forcing_target.data.shape == (150, 3)
506
+ else:
507
+ assert bunch_forcing_target.target.name == target_column
508
+ assert bunch_forcing_target.data.shape == (150, 4)
509
+
510
+
511
+ @pytest.mark.parametrize("data_id", [61, 2, 561, 40589, 1119])
512
+ @pytest.mark.parametrize("parser", ["liac-arff", "pandas"])
513
+ def test_fetch_openml_equivalence_frame_return_X_y(monkeypatch, data_id, parser):
514
+ """Check the behaviour of `return_X_y=True` when `as_frame=True`."""
515
+ pd = pytest.importorskip("pandas")
516
+
517
+ _monkey_patch_webbased_functions(monkeypatch, data_id, gzip_response=True)
518
+ bunch = fetch_openml(
519
+ data_id=data_id,
520
+ as_frame=True,
521
+ cache=False,
522
+ return_X_y=False,
523
+ parser=parser,
524
+ )
525
+ X, y = fetch_openml(
526
+ data_id=data_id,
527
+ as_frame=True,
528
+ cache=False,
529
+ return_X_y=True,
530
+ parser=parser,
531
+ )
532
+
533
+ pd.testing.assert_frame_equal(bunch.data, X)
534
+ if isinstance(y, pd.Series):
535
+ pd.testing.assert_series_equal(bunch.target, y)
536
+ else:
537
+ pd.testing.assert_frame_equal(bunch.target, y)
538
+
539
+
540
+ @pytest.mark.parametrize("data_id", [61, 561, 40589, 1119])
541
+ @pytest.mark.parametrize("parser", ["liac-arff", "pandas"])
542
+ def test_fetch_openml_equivalence_array_return_X_y(monkeypatch, data_id, parser):
543
+ """Check the behaviour of `return_X_y=True` when `as_frame=False`."""
544
+ pytest.importorskip("pandas")
545
+
546
+ _monkey_patch_webbased_functions(monkeypatch, data_id, gzip_response=True)
547
+ bunch = fetch_openml(
548
+ data_id=data_id,
549
+ as_frame=False,
550
+ cache=False,
551
+ return_X_y=False,
552
+ parser=parser,
553
+ )
554
+ X, y = fetch_openml(
555
+ data_id=data_id,
556
+ as_frame=False,
557
+ cache=False,
558
+ return_X_y=True,
559
+ parser=parser,
560
+ )
561
+
562
+ assert_array_equal(bunch.data, X)
563
+ assert_array_equal(bunch.target, y)
564
+
565
+
566
+ def test_fetch_openml_difference_parsers(monkeypatch):
567
+ """Check the difference between liac-arff and pandas parser."""
568
+ pytest.importorskip("pandas")
569
+
570
+ data_id = 1119
571
+ _monkey_patch_webbased_functions(monkeypatch, data_id, gzip_response=True)
572
+ # When `as_frame=False`, the categories will be ordinally encoded with
573
+ # liac-arff parser while this is not the case with pandas parser.
574
+ as_frame = False
575
+ bunch_liac_arff = fetch_openml(
576
+ data_id=data_id,
577
+ as_frame=as_frame,
578
+ cache=False,
579
+ parser="liac-arff",
580
+ )
581
+ bunch_pandas = fetch_openml(
582
+ data_id=data_id,
583
+ as_frame=as_frame,
584
+ cache=False,
585
+ parser="pandas",
586
+ )
587
+
588
+ assert bunch_liac_arff.data.dtype.kind == "f"
589
+ assert bunch_pandas.data.dtype == "O"
590
+
591
+
592
+ ###############################################################################
593
+ # Test the ARFF parsing on several dataset to check if detect the correct
594
+ # types (categories, integers, floats).
595
+
596
+
597
+ @pytest.fixture(scope="module")
598
+ def datasets_column_names():
599
+ """Returns the columns names for each dataset."""
600
+ return {
601
+ 61: ["sepallength", "sepalwidth", "petallength", "petalwidth", "class"],
602
+ 2: [
603
+ "family",
604
+ "product-type",
605
+ "steel",
606
+ "carbon",
607
+ "hardness",
608
+ "temper_rolling",
609
+ "condition",
610
+ "formability",
611
+ "strength",
612
+ "non-ageing",
613
+ "surface-finish",
614
+ "surface-quality",
615
+ "enamelability",
616
+ "bc",
617
+ "bf",
618
+ "bt",
619
+ "bw%2Fme",
620
+ "bl",
621
+ "m",
622
+ "chrom",
623
+ "phos",
624
+ "cbond",
625
+ "marvi",
626
+ "exptl",
627
+ "ferro",
628
+ "corr",
629
+ "blue%2Fbright%2Fvarn%2Fclean",
630
+ "lustre",
631
+ "jurofm",
632
+ "s",
633
+ "p",
634
+ "shape",
635
+ "thick",
636
+ "width",
637
+ "len",
638
+ "oil",
639
+ "bore",
640
+ "packing",
641
+ "class",
642
+ ],
643
+ 561: ["vendor", "MYCT", "MMIN", "MMAX", "CACH", "CHMIN", "CHMAX", "class"],
644
+ 40589: [
645
+ "Mean_Acc1298_Mean_Mem40_Centroid",
646
+ "Mean_Acc1298_Mean_Mem40_Rolloff",
647
+ "Mean_Acc1298_Mean_Mem40_Flux",
648
+ "Mean_Acc1298_Mean_Mem40_MFCC_0",
649
+ "Mean_Acc1298_Mean_Mem40_MFCC_1",
650
+ "Mean_Acc1298_Mean_Mem40_MFCC_2",
651
+ "Mean_Acc1298_Mean_Mem40_MFCC_3",
652
+ "Mean_Acc1298_Mean_Mem40_MFCC_4",
653
+ "Mean_Acc1298_Mean_Mem40_MFCC_5",
654
+ "Mean_Acc1298_Mean_Mem40_MFCC_6",
655
+ "Mean_Acc1298_Mean_Mem40_MFCC_7",
656
+ "Mean_Acc1298_Mean_Mem40_MFCC_8",
657
+ "Mean_Acc1298_Mean_Mem40_MFCC_9",
658
+ "Mean_Acc1298_Mean_Mem40_MFCC_10",
659
+ "Mean_Acc1298_Mean_Mem40_MFCC_11",
660
+ "Mean_Acc1298_Mean_Mem40_MFCC_12",
661
+ "Mean_Acc1298_Std_Mem40_Centroid",
662
+ "Mean_Acc1298_Std_Mem40_Rolloff",
663
+ "Mean_Acc1298_Std_Mem40_Flux",
664
+ "Mean_Acc1298_Std_Mem40_MFCC_0",
665
+ "Mean_Acc1298_Std_Mem40_MFCC_1",
666
+ "Mean_Acc1298_Std_Mem40_MFCC_2",
667
+ "Mean_Acc1298_Std_Mem40_MFCC_3",
668
+ "Mean_Acc1298_Std_Mem40_MFCC_4",
669
+ "Mean_Acc1298_Std_Mem40_MFCC_5",
670
+ "Mean_Acc1298_Std_Mem40_MFCC_6",
671
+ "Mean_Acc1298_Std_Mem40_MFCC_7",
672
+ "Mean_Acc1298_Std_Mem40_MFCC_8",
673
+ "Mean_Acc1298_Std_Mem40_MFCC_9",
674
+ "Mean_Acc1298_Std_Mem40_MFCC_10",
675
+ "Mean_Acc1298_Std_Mem40_MFCC_11",
676
+ "Mean_Acc1298_Std_Mem40_MFCC_12",
677
+ "Std_Acc1298_Mean_Mem40_Centroid",
678
+ "Std_Acc1298_Mean_Mem40_Rolloff",
679
+ "Std_Acc1298_Mean_Mem40_Flux",
680
+ "Std_Acc1298_Mean_Mem40_MFCC_0",
681
+ "Std_Acc1298_Mean_Mem40_MFCC_1",
682
+ "Std_Acc1298_Mean_Mem40_MFCC_2",
683
+ "Std_Acc1298_Mean_Mem40_MFCC_3",
684
+ "Std_Acc1298_Mean_Mem40_MFCC_4",
685
+ "Std_Acc1298_Mean_Mem40_MFCC_5",
686
+ "Std_Acc1298_Mean_Mem40_MFCC_6",
687
+ "Std_Acc1298_Mean_Mem40_MFCC_7",
688
+ "Std_Acc1298_Mean_Mem40_MFCC_8",
689
+ "Std_Acc1298_Mean_Mem40_MFCC_9",
690
+ "Std_Acc1298_Mean_Mem40_MFCC_10",
691
+ "Std_Acc1298_Mean_Mem40_MFCC_11",
692
+ "Std_Acc1298_Mean_Mem40_MFCC_12",
693
+ "Std_Acc1298_Std_Mem40_Centroid",
694
+ "Std_Acc1298_Std_Mem40_Rolloff",
695
+ "Std_Acc1298_Std_Mem40_Flux",
696
+ "Std_Acc1298_Std_Mem40_MFCC_0",
697
+ "Std_Acc1298_Std_Mem40_MFCC_1",
698
+ "Std_Acc1298_Std_Mem40_MFCC_2",
699
+ "Std_Acc1298_Std_Mem40_MFCC_3",
700
+ "Std_Acc1298_Std_Mem40_MFCC_4",
701
+ "Std_Acc1298_Std_Mem40_MFCC_5",
702
+ "Std_Acc1298_Std_Mem40_MFCC_6",
703
+ "Std_Acc1298_Std_Mem40_MFCC_7",
704
+ "Std_Acc1298_Std_Mem40_MFCC_8",
705
+ "Std_Acc1298_Std_Mem40_MFCC_9",
706
+ "Std_Acc1298_Std_Mem40_MFCC_10",
707
+ "Std_Acc1298_Std_Mem40_MFCC_11",
708
+ "Std_Acc1298_Std_Mem40_MFCC_12",
709
+ "BH_LowPeakAmp",
710
+ "BH_LowPeakBPM",
711
+ "BH_HighPeakAmp",
712
+ "BH_HighPeakBPM",
713
+ "BH_HighLowRatio",
714
+ "BHSUM1",
715
+ "BHSUM2",
716
+ "BHSUM3",
717
+ "amazed.suprised",
718
+ "happy.pleased",
719
+ "relaxing.calm",
720
+ "quiet.still",
721
+ "sad.lonely",
722
+ "angry.aggresive",
723
+ ],
724
+ 1119: [
725
+ "age",
726
+ "workclass",
727
+ "fnlwgt:",
728
+ "education:",
729
+ "education-num:",
730
+ "marital-status:",
731
+ "occupation:",
732
+ "relationship:",
733
+ "race:",
734
+ "sex:",
735
+ "capital-gain:",
736
+ "capital-loss:",
737
+ "hours-per-week:",
738
+ "native-country:",
739
+ "class",
740
+ ],
741
+ 40966: [
742
+ "DYRK1A_N",
743
+ "ITSN1_N",
744
+ "BDNF_N",
745
+ "NR1_N",
746
+ "NR2A_N",
747
+ "pAKT_N",
748
+ "pBRAF_N",
749
+ "pCAMKII_N",
750
+ "pCREB_N",
751
+ "pELK_N",
752
+ "pERK_N",
753
+ "pJNK_N",
754
+ "PKCA_N",
755
+ "pMEK_N",
756
+ "pNR1_N",
757
+ "pNR2A_N",
758
+ "pNR2B_N",
759
+ "pPKCAB_N",
760
+ "pRSK_N",
761
+ "AKT_N",
762
+ "BRAF_N",
763
+ "CAMKII_N",
764
+ "CREB_N",
765
+ "ELK_N",
766
+ "ERK_N",
767
+ "GSK3B_N",
768
+ "JNK_N",
769
+ "MEK_N",
770
+ "TRKA_N",
771
+ "RSK_N",
772
+ "APP_N",
773
+ "Bcatenin_N",
774
+ "SOD1_N",
775
+ "MTOR_N",
776
+ "P38_N",
777
+ "pMTOR_N",
778
+ "DSCR1_N",
779
+ "AMPKA_N",
780
+ "NR2B_N",
781
+ "pNUMB_N",
782
+ "RAPTOR_N",
783
+ "TIAM1_N",
784
+ "pP70S6_N",
785
+ "NUMB_N",
786
+ "P70S6_N",
787
+ "pGSK3B_N",
788
+ "pPKCG_N",
789
+ "CDK5_N",
790
+ "S6_N",
791
+ "ADARB1_N",
792
+ "AcetylH3K9_N",
793
+ "RRP1_N",
794
+ "BAX_N",
795
+ "ARC_N",
796
+ "ERBB4_N",
797
+ "nNOS_N",
798
+ "Tau_N",
799
+ "GFAP_N",
800
+ "GluR3_N",
801
+ "GluR4_N",
802
+ "IL1B_N",
803
+ "P3525_N",
804
+ "pCASP9_N",
805
+ "PSD95_N",
806
+ "SNCA_N",
807
+ "Ubiquitin_N",
808
+ "pGSK3B_Tyr216_N",
809
+ "SHH_N",
810
+ "BAD_N",
811
+ "BCL2_N",
812
+ "pS6_N",
813
+ "pCFOS_N",
814
+ "SYP_N",
815
+ "H3AcK18_N",
816
+ "EGR1_N",
817
+ "H3MeK4_N",
818
+ "CaNA_N",
819
+ "class",
820
+ ],
821
+ 40945: [
822
+ "pclass",
823
+ "survived",
824
+ "name",
825
+ "sex",
826
+ "age",
827
+ "sibsp",
828
+ "parch",
829
+ "ticket",
830
+ "fare",
831
+ "cabin",
832
+ "embarked",
833
+ "boat",
834
+ "body",
835
+ "home.dest",
836
+ ],
837
+ }
838
+
839
+
840
+ @pytest.fixture(scope="module")
841
+ def datasets_missing_values():
842
+ return {
843
+ 61: {},
844
+ 2: {
845
+ "family": 11,
846
+ "temper_rolling": 9,
847
+ "condition": 2,
848
+ "formability": 4,
849
+ "non-ageing": 10,
850
+ "surface-finish": 11,
851
+ "enamelability": 11,
852
+ "bc": 11,
853
+ "bf": 10,
854
+ "bt": 11,
855
+ "bw%2Fme": 8,
856
+ "bl": 9,
857
+ "m": 11,
858
+ "chrom": 11,
859
+ "phos": 11,
860
+ "cbond": 10,
861
+ "marvi": 11,
862
+ "exptl": 11,
863
+ "ferro": 11,
864
+ "corr": 11,
865
+ "blue%2Fbright%2Fvarn%2Fclean": 11,
866
+ "lustre": 8,
867
+ "jurofm": 11,
868
+ "s": 11,
869
+ "p": 11,
870
+ "oil": 10,
871
+ "packing": 11,
872
+ },
873
+ 561: {},
874
+ 40589: {},
875
+ 1119: {},
876
+ 40966: {"BCL2_N": 7},
877
+ 40945: {
878
+ "age": 263,
879
+ "fare": 1,
880
+ "cabin": 1014,
881
+ "embarked": 2,
882
+ "boat": 823,
883
+ "body": 1188,
884
+ "home.dest": 564,
885
+ },
886
+ }
887
+
888
+
889
+ @pytest.mark.parametrize(
890
+ "data_id, parser, expected_n_categories, expected_n_floats, expected_n_ints",
891
+ [
892
+ # iris dataset
893
+ (61, "liac-arff", 1, 4, 0),
894
+ (61, "pandas", 1, 4, 0),
895
+ # anneal dataset
896
+ (2, "liac-arff", 33, 6, 0),
897
+ (2, "pandas", 33, 2, 4),
898
+ # cpu dataset
899
+ (561, "liac-arff", 1, 7, 0),
900
+ (561, "pandas", 1, 0, 7),
901
+ # emotions dataset
902
+ (40589, "liac-arff", 6, 72, 0),
903
+ (40589, "pandas", 6, 69, 3),
904
+ # adult-census dataset
905
+ (1119, "liac-arff", 9, 6, 0),
906
+ (1119, "pandas", 9, 0, 6),
907
+ # miceprotein
908
+ (40966, "liac-arff", 1, 77, 0),
909
+ (40966, "pandas", 1, 77, 0),
910
+ # titanic
911
+ (40945, "liac-arff", 3, 6, 0),
912
+ (40945, "pandas", 3, 3, 3),
913
+ ],
914
+ )
915
+ @pytest.mark.parametrize("gzip_response", [True, False])
916
+ def test_fetch_openml_types_inference(
917
+ monkeypatch,
918
+ data_id,
919
+ parser,
920
+ expected_n_categories,
921
+ expected_n_floats,
922
+ expected_n_ints,
923
+ gzip_response,
924
+ datasets_column_names,
925
+ datasets_missing_values,
926
+ ):
927
+ """Check that `fetch_openml` infer the right number of categories, integers, and
928
+ floats."""
929
+ pd = pytest.importorskip("pandas")
930
+ CategoricalDtype = pd.api.types.CategoricalDtype
931
+
932
+ _monkey_patch_webbased_functions(monkeypatch, data_id, gzip_response=gzip_response)
933
+
934
+ bunch = fetch_openml(
935
+ data_id=data_id,
936
+ as_frame=True,
937
+ cache=False,
938
+ parser=parser,
939
+ )
940
+ frame = bunch.frame
941
+
942
+ n_categories = len(
943
+ [dtype for dtype in frame.dtypes if isinstance(dtype, CategoricalDtype)]
944
+ )
945
+ n_floats = len([dtype for dtype in frame.dtypes if dtype.kind == "f"])
946
+ n_ints = len([dtype for dtype in frame.dtypes if dtype.kind == "i"])
947
+
948
+ assert n_categories == expected_n_categories
949
+ assert n_floats == expected_n_floats
950
+ assert n_ints == expected_n_ints
951
+
952
+ assert frame.columns.tolist() == datasets_column_names[data_id]
953
+
954
+ frame_feature_to_n_nan = frame.isna().sum().to_dict()
955
+ for name, n_missing in frame_feature_to_n_nan.items():
956
+ expected_missing = datasets_missing_values[data_id].get(name, 0)
957
+ assert n_missing == expected_missing
958
+
959
+
960
+ ###############################################################################
961
+ # Test some more specific behaviour
962
+
963
+
964
+ @pytest.mark.parametrize(
965
+ "params, err_msg",
966
+ [
967
+ (
968
+ {"parser": "unknown"},
969
+ "The 'parser' parameter of fetch_openml must be a str among",
970
+ ),
971
+ (
972
+ {"as_frame": "unknown"},
973
+ "The 'as_frame' parameter of fetch_openml must be an instance",
974
+ ),
975
+ ],
976
+ )
977
+ def test_fetch_openml_validation_parameter(monkeypatch, params, err_msg):
978
+ data_id = 1119
979
+ _monkey_patch_webbased_functions(monkeypatch, data_id, True)
980
+ with pytest.raises(ValueError, match=err_msg):
981
+ fetch_openml(data_id=data_id, **params)
982
+
983
+
984
+ @pytest.mark.parametrize(
985
+ "params",
986
+ [
987
+ {"as_frame": True, "parser": "auto"},
988
+ {"as_frame": "auto", "parser": "auto"},
989
+ {"as_frame": False, "parser": "pandas"},
990
+ {"as_frame": False, "parser": "auto"},
991
+ ],
992
+ )
993
+ def test_fetch_openml_requires_pandas_error(monkeypatch, params):
994
+ """Check that we raise the proper errors when we require pandas."""
995
+ data_id = 1119
996
+ try:
997
+ check_pandas_support("test_fetch_openml_requires_pandas")
998
+ except ImportError:
999
+ _monkey_patch_webbased_functions(monkeypatch, data_id, True)
1000
+ err_msg = "requires pandas to be installed. Alternatively, explicitly"
1001
+ with pytest.raises(ImportError, match=err_msg):
1002
+ fetch_openml(data_id=data_id, **params)
1003
+ else:
1004
+ raise SkipTest("This test requires pandas to not be installed.")
1005
+
1006
+
1007
+ @pytest.mark.filterwarnings("ignore:Version 1 of dataset Australian is inactive")
1008
+ @pytest.mark.parametrize(
1009
+ "params, err_msg",
1010
+ [
1011
+ (
1012
+ {"parser": "pandas"},
1013
+ "Sparse ARFF datasets cannot be loaded with parser='pandas'",
1014
+ ),
1015
+ (
1016
+ {"as_frame": True},
1017
+ "Sparse ARFF datasets cannot be loaded with as_frame=True.",
1018
+ ),
1019
+ (
1020
+ {"parser": "pandas", "as_frame": True},
1021
+ "Sparse ARFF datasets cannot be loaded with as_frame=True.",
1022
+ ),
1023
+ ],
1024
+ )
1025
+ def test_fetch_openml_sparse_arff_error(monkeypatch, params, err_msg):
1026
+ """Check that we raise the expected error for sparse ARFF datasets and
1027
+ a wrong set of incompatible parameters.
1028
+ """
1029
+ pytest.importorskip("pandas")
1030
+ data_id = 292
1031
+
1032
+ _monkey_patch_webbased_functions(monkeypatch, data_id, True)
1033
+ with pytest.raises(ValueError, match=err_msg):
1034
+ fetch_openml(
1035
+ data_id=data_id,
1036
+ cache=False,
1037
+ **params,
1038
+ )
1039
+
1040
+
1041
+ @pytest.mark.filterwarnings("ignore:Version 1 of dataset Australian is inactive")
1042
+ @pytest.mark.parametrize(
1043
+ "data_id, data_type",
1044
+ [
1045
+ (61, "dataframe"), # iris dataset version 1
1046
+ (292, "sparse"), # Australian dataset version 1
1047
+ ],
1048
+ )
1049
+ def test_fetch_openml_auto_mode(monkeypatch, data_id, data_type):
1050
+ """Check the auto mode of `fetch_openml`."""
1051
+ pd = pytest.importorskip("pandas")
1052
+
1053
+ _monkey_patch_webbased_functions(monkeypatch, data_id, True)
1054
+ data = fetch_openml(data_id=data_id, as_frame="auto", cache=False)
1055
+ klass = pd.DataFrame if data_type == "dataframe" else scipy.sparse.csr_matrix
1056
+ assert isinstance(data.data, klass)
1057
+
1058
+
1059
+ def test_convert_arff_data_dataframe_warning_low_memory_pandas(monkeypatch):
1060
+ """Check that we raise a warning regarding the working memory when using
1061
+ LIAC-ARFF parser."""
1062
+ pytest.importorskip("pandas")
1063
+
1064
+ data_id = 1119
1065
+ _monkey_patch_webbased_functions(monkeypatch, data_id, True)
1066
+
1067
+ msg = "Could not adhere to working_memory config."
1068
+ with pytest.warns(UserWarning, match=msg):
1069
+ with config_context(working_memory=1e-6):
1070
+ fetch_openml(
1071
+ data_id=data_id,
1072
+ as_frame=True,
1073
+ cache=False,
1074
+ parser="liac-arff",
1075
+ )
1076
+
1077
+
1078
+ @pytest.mark.parametrize("gzip_response", [True, False])
1079
+ def test_fetch_openml_iris_warn_multiple_version(monkeypatch, gzip_response):
1080
+ """Check that a warning is raised when multiple versions exist and no version is
1081
+ requested."""
1082
+ data_id = 61
1083
+ data_name = "iris"
1084
+
1085
+ _monkey_patch_webbased_functions(monkeypatch, data_id, gzip_response)
1086
+
1087
+ msg = re.escape(
1088
+ "Multiple active versions of the dataset matching the name"
1089
+ " iris exist. Versions may be fundamentally different, "
1090
+ "returning version 1. Available versions:\n"
1091
+ "- version 1, status: active\n"
1092
+ " url: https://www.openml.org/search?type=data&id=61\n"
1093
+ "- version 3, status: active\n"
1094
+ " url: https://www.openml.org/search?type=data&id=969\n"
1095
+ )
1096
+ with pytest.warns(UserWarning, match=msg):
1097
+ fetch_openml(
1098
+ name=data_name,
1099
+ as_frame=False,
1100
+ cache=False,
1101
+ parser="liac-arff",
1102
+ )
1103
+
1104
+
1105
+ @pytest.mark.parametrize("gzip_response", [True, False])
1106
+ def test_fetch_openml_no_target(monkeypatch, gzip_response):
1107
+ """Check that we can get a dataset without target."""
1108
+ data_id = 61
1109
+ target_column = None
1110
+ expected_observations = 150
1111
+ expected_features = 5
1112
+
1113
+ _monkey_patch_webbased_functions(monkeypatch, data_id, gzip_response)
1114
+ data = fetch_openml(
1115
+ data_id=data_id,
1116
+ target_column=target_column,
1117
+ cache=False,
1118
+ as_frame=False,
1119
+ parser="liac-arff",
1120
+ )
1121
+ assert data.data.shape == (expected_observations, expected_features)
1122
+ assert data.target is None
1123
+
1124
+
1125
+ @pytest.mark.parametrize("gzip_response", [True, False])
1126
+ @pytest.mark.parametrize("parser", ["liac-arff", "pandas"])
1127
+ def test_missing_values_pandas(monkeypatch, gzip_response, parser):
1128
+ """check that missing values in categories are compatible with pandas
1129
+ categorical"""
1130
+ pytest.importorskip("pandas")
1131
+
1132
+ data_id = 42585
1133
+ _monkey_patch_webbased_functions(monkeypatch, data_id, gzip_response=gzip_response)
1134
+ penguins = fetch_openml(
1135
+ data_id=data_id,
1136
+ cache=False,
1137
+ as_frame=True,
1138
+ parser=parser,
1139
+ )
1140
+
1141
+ cat_dtype = penguins.data.dtypes["sex"]
1142
+ # there are nans in the categorical
1143
+ assert penguins.data["sex"].isna().any()
1144
+ assert_array_equal(cat_dtype.categories, ["FEMALE", "MALE", "_"])
1145
+
1146
+
1147
+ @pytest.mark.parametrize("gzip_response", [True, False])
1148
+ @pytest.mark.parametrize(
1149
+ "dataset_params",
1150
+ [
1151
+ {"data_id": 40675},
1152
+ {"data_id": None, "name": "glass2", "version": 1},
1153
+ ],
1154
+ )
1155
+ def test_fetch_openml_inactive(monkeypatch, gzip_response, dataset_params):
1156
+ """Check that we raise a warning when the dataset is inactive."""
1157
+ data_id = 40675
1158
+ _monkey_patch_webbased_functions(monkeypatch, data_id, gzip_response)
1159
+ msg = "Version 1 of dataset glass2 is inactive,"
1160
+ with pytest.warns(UserWarning, match=msg):
1161
+ glass2 = fetch_openml(
1162
+ cache=False, as_frame=False, parser="liac-arff", **dataset_params
1163
+ )
1164
+ assert glass2.data.shape == (163, 9)
1165
+ assert glass2.details["id"] == "40675"
1166
+
1167
+
1168
+ @pytest.mark.parametrize("gzip_response", [True, False])
1169
+ @pytest.mark.parametrize(
1170
+ "data_id, params, err_type, err_msg",
1171
+ [
1172
+ (40675, {"name": "glass2"}, ValueError, "No active dataset glass2 found"),
1173
+ (
1174
+ 61,
1175
+ {"data_id": 61, "target_column": ["sepalwidth", "class"]},
1176
+ ValueError,
1177
+ "Can only handle homogeneous multi-target datasets",
1178
+ ),
1179
+ (
1180
+ 40945,
1181
+ {"data_id": 40945, "as_frame": False},
1182
+ ValueError,
1183
+ (
1184
+ "STRING attributes are not supported for array representation. Try"
1185
+ " as_frame=True"
1186
+ ),
1187
+ ),
1188
+ (
1189
+ 2,
1190
+ {"data_id": 2, "target_column": "family", "as_frame": True},
1191
+ ValueError,
1192
+ "Target column 'family'",
1193
+ ),
1194
+ (
1195
+ 2,
1196
+ {"data_id": 2, "target_column": "family", "as_frame": False},
1197
+ ValueError,
1198
+ "Target column 'family'",
1199
+ ),
1200
+ (
1201
+ 61,
1202
+ {"data_id": 61, "target_column": "undefined"},
1203
+ KeyError,
1204
+ "Could not find target_column='undefined'",
1205
+ ),
1206
+ (
1207
+ 61,
1208
+ {"data_id": 61, "target_column": ["undefined", "class"]},
1209
+ KeyError,
1210
+ "Could not find target_column='undefined'",
1211
+ ),
1212
+ ],
1213
+ )
1214
+ @pytest.mark.parametrize("parser", ["liac-arff", "pandas"])
1215
+ def test_fetch_openml_error(
1216
+ monkeypatch, gzip_response, data_id, params, err_type, err_msg, parser
1217
+ ):
1218
+ _monkey_patch_webbased_functions(monkeypatch, data_id, gzip_response)
1219
+ if params.get("as_frame", True) or parser == "pandas":
1220
+ pytest.importorskip("pandas")
1221
+ with pytest.raises(err_type, match=err_msg):
1222
+ fetch_openml(cache=False, parser=parser, **params)
1223
+
1224
+
1225
+ @pytest.mark.parametrize(
1226
+ "params, err_type, err_msg",
1227
+ [
1228
+ (
1229
+ {"data_id": -1, "name": None, "version": "version"},
1230
+ ValueError,
1231
+ "The 'version' parameter of fetch_openml must be an int in the range",
1232
+ ),
1233
+ (
1234
+ {"data_id": -1, "name": "nAmE"},
1235
+ ValueError,
1236
+ "The 'data_id' parameter of fetch_openml must be an int in the range",
1237
+ ),
1238
+ (
1239
+ {"data_id": -1, "name": "nAmE", "version": "version"},
1240
+ ValueError,
1241
+ "The 'version' parameter of fetch_openml must be an int",
1242
+ ),
1243
+ (
1244
+ {},
1245
+ ValueError,
1246
+ "Neither name nor data_id are provided. Please provide name or data_id.",
1247
+ ),
1248
+ ],
1249
+ )
1250
+ def test_fetch_openml_raises_illegal_argument(params, err_type, err_msg):
1251
+ with pytest.raises(err_type, match=err_msg):
1252
+ fetch_openml(**params)
1253
+
1254
+
1255
+ @pytest.mark.parametrize("gzip_response", [True, False])
1256
+ def test_warn_ignore_attribute(monkeypatch, gzip_response):
1257
+ data_id = 40966
1258
+ expected_row_id_msg = "target_column='{}' has flag is_row_identifier."
1259
+ expected_ignore_msg = "target_column='{}' has flag is_ignore."
1260
+ _monkey_patch_webbased_functions(monkeypatch, data_id, gzip_response)
1261
+ # single column test
1262
+ target_col = "MouseID"
1263
+ msg = expected_row_id_msg.format(target_col)
1264
+ with pytest.warns(UserWarning, match=msg):
1265
+ fetch_openml(
1266
+ data_id=data_id,
1267
+ target_column=target_col,
1268
+ cache=False,
1269
+ as_frame=False,
1270
+ parser="liac-arff",
1271
+ )
1272
+ target_col = "Genotype"
1273
+ msg = expected_ignore_msg.format(target_col)
1274
+ with pytest.warns(UserWarning, match=msg):
1275
+ fetch_openml(
1276
+ data_id=data_id,
1277
+ target_column=target_col,
1278
+ cache=False,
1279
+ as_frame=False,
1280
+ parser="liac-arff",
1281
+ )
1282
+ # multi column test
1283
+ target_col = "MouseID"
1284
+ msg = expected_row_id_msg.format(target_col)
1285
+ with pytest.warns(UserWarning, match=msg):
1286
+ fetch_openml(
1287
+ data_id=data_id,
1288
+ target_column=[target_col, "class"],
1289
+ cache=False,
1290
+ as_frame=False,
1291
+ parser="liac-arff",
1292
+ )
1293
+ target_col = "Genotype"
1294
+ msg = expected_ignore_msg.format(target_col)
1295
+ with pytest.warns(UserWarning, match=msg):
1296
+ fetch_openml(
1297
+ data_id=data_id,
1298
+ target_column=[target_col, "class"],
1299
+ cache=False,
1300
+ as_frame=False,
1301
+ parser="liac-arff",
1302
+ )
1303
+
1304
+
1305
+ @pytest.mark.parametrize("gzip_response", [True, False])
1306
+ def test_dataset_with_openml_error(monkeypatch, gzip_response):
1307
+ data_id = 1
1308
+ _monkey_patch_webbased_functions(monkeypatch, data_id, gzip_response)
1309
+ msg = "OpenML registered a problem with the dataset. It might be unusable. Error:"
1310
+ with pytest.warns(UserWarning, match=msg):
1311
+ fetch_openml(data_id=data_id, cache=False, as_frame=False, parser="liac-arff")
1312
+
1313
+
1314
+ @pytest.mark.parametrize("gzip_response", [True, False])
1315
+ def test_dataset_with_openml_warning(monkeypatch, gzip_response):
1316
+ data_id = 3
1317
+ _monkey_patch_webbased_functions(monkeypatch, data_id, gzip_response)
1318
+ msg = "OpenML raised a warning on the dataset. It might be unusable. Warning:"
1319
+ with pytest.warns(UserWarning, match=msg):
1320
+ fetch_openml(data_id=data_id, cache=False, as_frame=False, parser="liac-arff")
1321
+
1322
+
1323
+ def test_fetch_openml_overwrite_default_params_read_csv(monkeypatch):
1324
+ """Check that we can overwrite the default parameters of `read_csv`."""
1325
+ pytest.importorskip("pandas")
1326
+ data_id = 1590
1327
+ _monkey_patch_webbased_functions(monkeypatch, data_id=data_id, gzip_response=False)
1328
+
1329
+ common_params = {
1330
+ "data_id": data_id,
1331
+ "as_frame": True,
1332
+ "cache": False,
1333
+ "parser": "pandas",
1334
+ }
1335
+
1336
+ # By default, the initial spaces are skipped. We checked that setting the parameter
1337
+ # `skipinitialspace` to False will have an effect.
1338
+ adult_without_spaces = fetch_openml(**common_params)
1339
+ adult_with_spaces = fetch_openml(
1340
+ **common_params, read_csv_kwargs={"skipinitialspace": False}
1341
+ )
1342
+ assert all(
1343
+ cat.startswith(" ") for cat in adult_with_spaces.frame["class"].cat.categories
1344
+ )
1345
+ assert not any(
1346
+ cat.startswith(" ")
1347
+ for cat in adult_without_spaces.frame["class"].cat.categories
1348
+ )
1349
+
1350
+
1351
+ ###############################################################################
1352
+ # Test cache, retry mechanisms, checksum, etc.
1353
+
1354
+
1355
+ @pytest.mark.parametrize("gzip_response", [True, False])
1356
+ def test_open_openml_url_cache(monkeypatch, gzip_response, tmpdir):
1357
+ data_id = 61
1358
+
1359
+ _monkey_patch_webbased_functions(monkeypatch, data_id, gzip_response)
1360
+ openml_path = _MONKEY_PATCH_LOCAL_OPENML_PATH.format(data_id) + "/filename.arff"
1361
+ url = f"https://www.openml.org/{openml_path}"
1362
+ cache_directory = str(tmpdir.mkdir("scikit_learn_data"))
1363
+ # first fill the cache
1364
+ response1 = _open_openml_url(url, cache_directory)
1365
+ # assert file exists
1366
+ location = _get_local_path(openml_path, cache_directory)
1367
+ assert os.path.isfile(location)
1368
+ # redownload, to utilize cache
1369
+ response2 = _open_openml_url(url, cache_directory)
1370
+ assert response1.read() == response2.read()
1371
+
1372
+
1373
+ @pytest.mark.parametrize("write_to_disk", [True, False])
1374
+ def test_open_openml_url_unlinks_local_path(monkeypatch, tmpdir, write_to_disk):
1375
+ data_id = 61
1376
+ openml_path = _MONKEY_PATCH_LOCAL_OPENML_PATH.format(data_id) + "/filename.arff"
1377
+ url = f"https://www.openml.org/{openml_path}"
1378
+ cache_directory = str(tmpdir.mkdir("scikit_learn_data"))
1379
+ location = _get_local_path(openml_path, cache_directory)
1380
+
1381
+ def _mock_urlopen(request, *args, **kwargs):
1382
+ if write_to_disk:
1383
+ with open(location, "w") as f:
1384
+ f.write("")
1385
+ raise ValueError("Invalid request")
1386
+
1387
+ monkeypatch.setattr(sklearn.datasets._openml, "urlopen", _mock_urlopen)
1388
+
1389
+ with pytest.raises(ValueError, match="Invalid request"):
1390
+ _open_openml_url(url, cache_directory)
1391
+
1392
+ assert not os.path.exists(location)
1393
+
1394
+
1395
+ def test_retry_with_clean_cache(tmpdir):
1396
+ data_id = 61
1397
+ openml_path = _MONKEY_PATCH_LOCAL_OPENML_PATH.format(data_id)
1398
+ cache_directory = str(tmpdir.mkdir("scikit_learn_data"))
1399
+ location = _get_local_path(openml_path, cache_directory)
1400
+ os.makedirs(os.path.dirname(location))
1401
+
1402
+ with open(location, "w") as f:
1403
+ f.write("")
1404
+
1405
+ @_retry_with_clean_cache(openml_path, cache_directory)
1406
+ def _load_data():
1407
+ # The first call will raise an error since location exists
1408
+ if os.path.exists(location):
1409
+ raise Exception("File exist!")
1410
+ return 1
1411
+
1412
+ warn_msg = "Invalid cache, redownloading file"
1413
+ with pytest.warns(RuntimeWarning, match=warn_msg):
1414
+ result = _load_data()
1415
+ assert result == 1
1416
+
1417
+
1418
+ def test_retry_with_clean_cache_http_error(tmpdir):
1419
+ data_id = 61
1420
+ openml_path = _MONKEY_PATCH_LOCAL_OPENML_PATH.format(data_id)
1421
+ cache_directory = str(tmpdir.mkdir("scikit_learn_data"))
1422
+
1423
+ @_retry_with_clean_cache(openml_path, cache_directory)
1424
+ def _load_data():
1425
+ raise HTTPError(
1426
+ url=None, code=412, msg="Simulated mock error", hdrs=None, fp=BytesIO()
1427
+ )
1428
+
1429
+ error_msg = "Simulated mock error"
1430
+ with pytest.raises(HTTPError, match=error_msg):
1431
+ _load_data()
1432
+
1433
+
1434
+ @pytest.mark.parametrize("gzip_response", [True, False])
1435
+ def test_fetch_openml_cache(monkeypatch, gzip_response, tmpdir):
1436
+ def _mock_urlopen_raise(request, *args, **kwargs):
1437
+ raise ValueError(
1438
+ "This mechanism intends to test correct cache"
1439
+ "handling. As such, urlopen should never be "
1440
+ "accessed. URL: %s" % request.get_full_url()
1441
+ )
1442
+
1443
+ data_id = 61
1444
+ cache_directory = str(tmpdir.mkdir("scikit_learn_data"))
1445
+ _monkey_patch_webbased_functions(monkeypatch, data_id, gzip_response)
1446
+ X_fetched, y_fetched = fetch_openml(
1447
+ data_id=data_id,
1448
+ cache=True,
1449
+ data_home=cache_directory,
1450
+ return_X_y=True,
1451
+ as_frame=False,
1452
+ parser="liac-arff",
1453
+ )
1454
+
1455
+ monkeypatch.setattr(sklearn.datasets._openml, "urlopen", _mock_urlopen_raise)
1456
+
1457
+ X_cached, y_cached = fetch_openml(
1458
+ data_id=data_id,
1459
+ cache=True,
1460
+ data_home=cache_directory,
1461
+ return_X_y=True,
1462
+ as_frame=False,
1463
+ parser="liac-arff",
1464
+ )
1465
+ np.testing.assert_array_equal(X_fetched, X_cached)
1466
+ np.testing.assert_array_equal(y_fetched, y_cached)
1467
+
1468
+
1469
+ @pytest.mark.parametrize(
1470
+ "as_frame, parser",
1471
+ [
1472
+ (True, "liac-arff"),
1473
+ (False, "liac-arff"),
1474
+ (True, "pandas"),
1475
+ (False, "pandas"),
1476
+ ],
1477
+ )
1478
+ def test_fetch_openml_verify_checksum(monkeypatch, as_frame, tmpdir, parser):
1479
+ """Check that the checksum is working as expected."""
1480
+ if as_frame or parser == "pandas":
1481
+ pytest.importorskip("pandas")
1482
+
1483
+ data_id = 2
1484
+ _monkey_patch_webbased_functions(monkeypatch, data_id, True)
1485
+
1486
+ # create a temporary modified arff file
1487
+ original_data_module = OPENML_TEST_DATA_MODULE + "." + f"id_{data_id}"
1488
+ original_data_file_name = "data-v1-dl-1666876.arff.gz"
1489
+ original_data_path = resources.files(original_data_module) / original_data_file_name
1490
+ corrupt_copy_path = tmpdir / "test_invalid_checksum.arff"
1491
+ with original_data_path.open("rb") as orig_file:
1492
+ orig_gzip = gzip.open(orig_file, "rb")
1493
+ data = bytearray(orig_gzip.read())
1494
+ data[len(data) - 1] = 37
1495
+
1496
+ with gzip.GzipFile(corrupt_copy_path, "wb") as modified_gzip:
1497
+ modified_gzip.write(data)
1498
+
1499
+ # Requests are already mocked by monkey_patch_webbased_functions.
1500
+ # We want to reuse that mock for all requests except file download,
1501
+ # hence creating a thin mock over the original mock
1502
+ mocked_openml_url = sklearn.datasets._openml.urlopen
1503
+
1504
+ def swap_file_mock(request, *args, **kwargs):
1505
+ url = request.get_full_url()
1506
+ if url.endswith("data/v1/download/1666876/anneal.arff"):
1507
+ with open(corrupt_copy_path, "rb") as f:
1508
+ corrupted_data = f.read()
1509
+ return _MockHTTPResponse(BytesIO(corrupted_data), is_gzip=True)
1510
+ else:
1511
+ return mocked_openml_url(request)
1512
+
1513
+ monkeypatch.setattr(sklearn.datasets._openml, "urlopen", swap_file_mock)
1514
+
1515
+ # validate failed checksum
1516
+ with pytest.raises(ValueError) as exc:
1517
+ sklearn.datasets.fetch_openml(
1518
+ data_id=data_id, cache=False, as_frame=as_frame, parser=parser
1519
+ )
1520
+ # exception message should have file-path
1521
+ assert exc.match("1666876")
1522
+
1523
+
1524
+ def test_open_openml_url_retry_on_network_error(monkeypatch):
1525
+ def _mock_urlopen_network_error(request, *args, **kwargs):
1526
+ raise HTTPError(
1527
+ url=None, code=404, msg="Simulated network error", hdrs=None, fp=BytesIO()
1528
+ )
1529
+
1530
+ monkeypatch.setattr(
1531
+ sklearn.datasets._openml, "urlopen", _mock_urlopen_network_error
1532
+ )
1533
+
1534
+ invalid_openml_url = "https://api.openml.org/invalid-url"
1535
+
1536
+ with pytest.warns(
1537
+ UserWarning,
1538
+ match=re.escape(
1539
+ "A network error occurred while downloading"
1540
+ f" {invalid_openml_url}. Retrying..."
1541
+ ),
1542
+ ) as record:
1543
+ with pytest.raises(HTTPError, match="Simulated network error") as exc_info:
1544
+ _open_openml_url(invalid_openml_url, None, delay=0)
1545
+ assert len(record) == 3
1546
+ # Avoid a ResourceWarning on Python 3.14 and later.
1547
+ exc_info.value.close()
1548
+
1549
+
1550
+ ###############################################################################
1551
+ # Non-regressiont tests
1552
+
1553
+
1554
+ @pytest.mark.parametrize("gzip_response", [True, False])
1555
+ @pytest.mark.parametrize("parser", ("liac-arff", "pandas"))
1556
+ def test_fetch_openml_with_ignored_feature(monkeypatch, gzip_response, parser):
1557
+ """Check that we can load the "zoo" dataset.
1558
+ Non-regression test for:
1559
+ https://github.com/scikit-learn/scikit-learn/issues/14340
1560
+ """
1561
+ if parser == "pandas":
1562
+ pytest.importorskip("pandas")
1563
+ data_id = 62
1564
+ _monkey_patch_webbased_functions(monkeypatch, data_id, gzip_response)
1565
+
1566
+ dataset = sklearn.datasets.fetch_openml(
1567
+ data_id=data_id, cache=False, as_frame=False, parser=parser
1568
+ )
1569
+ assert dataset is not None
1570
+ # The dataset has 17 features, including 1 ignored (animal),
1571
+ # so we assert that we don't have the ignored feature in the final Bunch
1572
+ assert dataset["data"].shape == (101, 16)
1573
+ assert "animal" not in dataset["feature_names"]
1574
+
1575
+
1576
+ def test_fetch_openml_strip_quotes(monkeypatch):
1577
+ """Check that we strip the single quotes when used as a string delimiter.
1578
+
1579
+ Non-regression test for:
1580
+ https://github.com/scikit-learn/scikit-learn/issues/23381
1581
+ """
1582
+ pd = pytest.importorskip("pandas")
1583
+ data_id = 40966
1584
+ _monkey_patch_webbased_functions(monkeypatch, data_id=data_id, gzip_response=False)
1585
+
1586
+ common_params = {"as_frame": True, "cache": False, "data_id": data_id}
1587
+ mice_pandas = fetch_openml(parser="pandas", **common_params)
1588
+ mice_liac_arff = fetch_openml(parser="liac-arff", **common_params)
1589
+ pd.testing.assert_series_equal(mice_pandas.target, mice_liac_arff.target)
1590
+ assert not mice_pandas.target.str.startswith("'").any()
1591
+ assert not mice_pandas.target.str.endswith("'").any()
1592
+
1593
+ # similar behaviour should be observed when the column is not the target
1594
+ mice_pandas = fetch_openml(parser="pandas", target_column="NUMB_N", **common_params)
1595
+ mice_liac_arff = fetch_openml(
1596
+ parser="liac-arff", target_column="NUMB_N", **common_params
1597
+ )
1598
+ pd.testing.assert_series_equal(
1599
+ mice_pandas.frame["class"], mice_liac_arff.frame["class"]
1600
+ )
1601
+ assert not mice_pandas.frame["class"].str.startswith("'").any()
1602
+ assert not mice_pandas.frame["class"].str.endswith("'").any()
1603
+
1604
+
1605
+ def test_fetch_openml_leading_whitespace(monkeypatch):
1606
+ """Check that we can strip leading whitespace in pandas parser.
1607
+
1608
+ Non-regression test for:
1609
+ https://github.com/scikit-learn/scikit-learn/issues/25311
1610
+ """
1611
+ pd = pytest.importorskip("pandas")
1612
+ data_id = 1590
1613
+ _monkey_patch_webbased_functions(monkeypatch, data_id=data_id, gzip_response=False)
1614
+
1615
+ common_params = {"as_frame": True, "cache": False, "data_id": data_id}
1616
+ adult_pandas = fetch_openml(parser="pandas", **common_params)
1617
+ adult_liac_arff = fetch_openml(parser="liac-arff", **common_params)
1618
+ pd.testing.assert_series_equal(
1619
+ adult_pandas.frame["class"], adult_liac_arff.frame["class"]
1620
+ )
1621
+
1622
+
1623
+ def test_fetch_openml_quotechar_escapechar(monkeypatch):
1624
+ """Check that we can handle escapechar and single/double quotechar.
1625
+
1626
+ Non-regression test for:
1627
+ https://github.com/scikit-learn/scikit-learn/issues/25478
1628
+ """
1629
+ pd = pytest.importorskip("pandas")
1630
+ data_id = 42074
1631
+ _monkey_patch_webbased_functions(monkeypatch, data_id=data_id, gzip_response=False)
1632
+
1633
+ common_params = {"as_frame": True, "cache": False, "data_id": data_id}
1634
+ adult_pandas = fetch_openml(parser="pandas", **common_params)
1635
+ adult_liac_arff = fetch_openml(parser="liac-arff", **common_params)
1636
+ pd.testing.assert_frame_equal(adult_pandas.frame, adult_liac_arff.frame)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/sklearn/datasets/tests/test_rcv1.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Test the rcv1 loader, if the data is available,
2
+ or if specifically requested via environment variable
3
+ (e.g. for CI jobs)."""
4
+
5
+ from functools import partial
6
+
7
+ import numpy as np
8
+ import scipy.sparse as sp
9
+
10
+ from sklearn.datasets.tests.test_common import check_return_X_y
11
+ from sklearn.utils._testing import assert_almost_equal, assert_array_equal
12
+
13
+
14
+ def test_fetch_rcv1(fetch_rcv1_fxt, global_random_seed):
15
+ data1 = fetch_rcv1_fxt(shuffle=False)
16
+ X1, Y1 = data1.data, data1.target
17
+ cat_list, s1 = data1.target_names.tolist(), data1.sample_id
18
+
19
+ # test sparsity
20
+ assert sp.issparse(X1)
21
+ assert sp.issparse(Y1)
22
+ assert 60915113 == X1.data.size
23
+ assert 2606875 == Y1.data.size
24
+
25
+ # test shapes
26
+ assert (804414, 47236) == X1.shape
27
+ assert (804414, 103) == Y1.shape
28
+ assert (804414,) == s1.shape
29
+ assert 103 == len(cat_list)
30
+
31
+ # test descr
32
+ assert data1.DESCR.startswith(".. _rcv1_dataset:")
33
+
34
+ # test ordering of categories
35
+ first_categories = ["C11", "C12", "C13", "C14", "C15", "C151"]
36
+ assert_array_equal(first_categories, cat_list[:6])
37
+
38
+ # test number of sample for some categories
39
+ some_categories = ("GMIL", "E143", "CCAT")
40
+ number_non_zero_in_cat = (5, 1206, 381327)
41
+ for num, cat in zip(number_non_zero_in_cat, some_categories):
42
+ j = cat_list.index(cat)
43
+ assert num == Y1[:, j].data.size
44
+
45
+ # test shuffling and subset
46
+ data2 = fetch_rcv1_fxt(
47
+ shuffle=True, subset="train", random_state=global_random_seed
48
+ )
49
+ X2, Y2 = data2.data, data2.target
50
+ s2 = data2.sample_id
51
+
52
+ # test return_X_y option
53
+ fetch_func = partial(fetch_rcv1_fxt, shuffle=False, subset="train")
54
+ check_return_X_y(data2, fetch_func)
55
+
56
+ # The first 23149 samples are the training samples
57
+ assert_array_equal(np.sort(s1[:23149]), np.sort(s2))
58
+
59
+ # test some precise values
60
+ some_sample_ids = (2286, 3274, 14042)
61
+ for sample_id in some_sample_ids:
62
+ idx1 = s1.tolist().index(sample_id)
63
+ idx2 = s2.tolist().index(sample_id)
64
+
65
+ feature_values_1 = X1[idx1, :].toarray()
66
+ feature_values_2 = X2[idx2, :].toarray()
67
+ assert_almost_equal(feature_values_1, feature_values_2)
68
+
69
+ target_values_1 = Y1[idx1, :].toarray()
70
+ target_values_2 = Y2[idx2, :].toarray()
71
+ assert_almost_equal(target_values_1, target_values_2)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/sklearn/datasets/tests/test_samples_generator.py ADDED
@@ -0,0 +1,744 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ from collections import defaultdict
3
+ from functools import partial
4
+
5
+ import numpy as np
6
+ import pytest
7
+ import scipy.sparse as sp
8
+
9
+ from sklearn.datasets import (
10
+ make_biclusters,
11
+ make_blobs,
12
+ make_checkerboard,
13
+ make_circles,
14
+ make_classification,
15
+ make_friedman1,
16
+ make_friedman2,
17
+ make_friedman3,
18
+ make_hastie_10_2,
19
+ make_low_rank_matrix,
20
+ make_moons,
21
+ make_multilabel_classification,
22
+ make_regression,
23
+ make_s_curve,
24
+ make_sparse_coded_signal,
25
+ make_sparse_spd_matrix,
26
+ make_sparse_uncorrelated,
27
+ make_spd_matrix,
28
+ make_swiss_roll,
29
+ )
30
+ from sklearn.utils._testing import (
31
+ assert_allclose,
32
+ assert_allclose_dense_sparse,
33
+ assert_almost_equal,
34
+ assert_array_almost_equal,
35
+ assert_array_equal,
36
+ )
37
+ from sklearn.utils.validation import assert_all_finite
38
+
39
+
40
+ def test_make_classification():
41
+ weights = [0.1, 0.25]
42
+ X, y = make_classification(
43
+ n_samples=100,
44
+ n_features=20,
45
+ n_informative=5,
46
+ n_redundant=1,
47
+ n_repeated=1,
48
+ n_classes=3,
49
+ n_clusters_per_class=1,
50
+ hypercube=False,
51
+ shift=None,
52
+ scale=None,
53
+ weights=weights,
54
+ random_state=0,
55
+ )
56
+
57
+ assert weights == [0.1, 0.25]
58
+ assert X.shape == (100, 20), "X shape mismatch"
59
+ assert y.shape == (100,), "y shape mismatch"
60
+ assert np.unique(y).shape == (3,), "Unexpected number of classes"
61
+ assert sum(y == 0) == 10, "Unexpected number of samples in class #0"
62
+ assert sum(y == 1) == 25, "Unexpected number of samples in class #1"
63
+ assert sum(y == 2) == 65, "Unexpected number of samples in class #2"
64
+
65
+ # Test for n_features > 30
66
+ X, y = make_classification(
67
+ n_samples=2000,
68
+ n_features=31,
69
+ n_informative=31,
70
+ n_redundant=0,
71
+ n_repeated=0,
72
+ hypercube=True,
73
+ scale=0.5,
74
+ random_state=0,
75
+ )
76
+
77
+ assert X.shape == (2000, 31), "X shape mismatch"
78
+ assert y.shape == (2000,), "y shape mismatch"
79
+ assert (
80
+ np.unique(X.view([("", X.dtype)] * X.shape[1]))
81
+ .view(X.dtype)
82
+ .reshape(-1, X.shape[1])
83
+ .shape[0]
84
+ == 2000
85
+ ), "Unexpected number of unique rows"
86
+
87
+
88
+ def test_make_classification_informative_features():
89
+ """Test the construction of informative features in make_classification
90
+
91
+ Also tests `n_clusters_per_class`, `n_classes`, `hypercube` and
92
+ fully-specified `weights`.
93
+ """
94
+ # Create very separate clusters; check that vertices are unique and
95
+ # correspond to classes
96
+ class_sep = 1e6
97
+ make = partial(
98
+ make_classification,
99
+ class_sep=class_sep,
100
+ n_redundant=0,
101
+ n_repeated=0,
102
+ flip_y=0,
103
+ shift=0,
104
+ scale=1,
105
+ shuffle=False,
106
+ )
107
+
108
+ for n_informative, weights, n_clusters_per_class in [
109
+ (2, [1], 1),
110
+ (2, [1 / 3] * 3, 1),
111
+ (2, [1 / 4] * 4, 1),
112
+ (2, [1 / 2] * 2, 2),
113
+ (2, [3 / 4, 1 / 4], 2),
114
+ (10, [1 / 3] * 3, 10),
115
+ (64, [1], 1),
116
+ ]:
117
+ n_classes = len(weights)
118
+ n_clusters = n_classes * n_clusters_per_class
119
+ n_samples = n_clusters * 50
120
+
121
+ for hypercube in (False, True):
122
+ X, y = make(
123
+ n_samples=n_samples,
124
+ n_classes=n_classes,
125
+ weights=weights,
126
+ n_features=n_informative,
127
+ n_informative=n_informative,
128
+ n_clusters_per_class=n_clusters_per_class,
129
+ hypercube=hypercube,
130
+ random_state=0,
131
+ )
132
+
133
+ assert X.shape == (n_samples, n_informative)
134
+ assert y.shape == (n_samples,)
135
+
136
+ # Cluster by sign, viewed as strings to allow uniquing
137
+ signs = np.sign(X)
138
+ signs = signs.view(dtype="|S{0}".format(signs.strides[0])).ravel()
139
+ unique_signs, cluster_index = np.unique(signs, return_inverse=True)
140
+
141
+ assert len(unique_signs) == n_clusters, (
142
+ "Wrong number of clusters, or not in distinct quadrants"
143
+ )
144
+
145
+ clusters_by_class = defaultdict(set)
146
+ for cluster, cls in zip(cluster_index, y):
147
+ clusters_by_class[cls].add(cluster)
148
+ for clusters in clusters_by_class.values():
149
+ assert len(clusters) == n_clusters_per_class, (
150
+ "Wrong number of clusters per class"
151
+ )
152
+ assert len(clusters_by_class) == n_classes, "Wrong number of classes"
153
+
154
+ assert_array_almost_equal(
155
+ np.bincount(y) / len(y) // weights,
156
+ [1] * n_classes,
157
+ err_msg="Wrong number of samples per class",
158
+ )
159
+
160
+ # Ensure on vertices of hypercube
161
+ for cluster in range(len(unique_signs)):
162
+ centroid = X[cluster_index == cluster].mean(axis=0)
163
+ if hypercube:
164
+ assert_array_almost_equal(
165
+ np.abs(centroid) / class_sep,
166
+ np.ones(n_informative),
167
+ decimal=5,
168
+ err_msg="Clusters are not centered on hypercube vertices",
169
+ )
170
+ else:
171
+ with pytest.raises(AssertionError):
172
+ assert_array_almost_equal(
173
+ np.abs(centroid) / class_sep,
174
+ np.ones(n_informative),
175
+ decimal=5,
176
+ err_msg=(
177
+ "Clusters should not be centered on hypercube vertices"
178
+ ),
179
+ )
180
+
181
+ with pytest.raises(ValueError):
182
+ make(n_features=2, n_informative=2, n_classes=5, n_clusters_per_class=1)
183
+ with pytest.raises(ValueError):
184
+ make(n_features=2, n_informative=2, n_classes=3, n_clusters_per_class=2)
185
+
186
+
187
+ def test_make_classification_return_x_y():
188
+ """
189
+ Test that make_classification returns a Bunch when return_X_y is False.
190
+
191
+ Also that bunch.X is the same as X
192
+ """
193
+
194
+ kwargs = {
195
+ "n_samples": 100,
196
+ "n_features": 20,
197
+ "n_informative": 5,
198
+ "n_redundant": 1,
199
+ "n_repeated": 1,
200
+ "n_classes": 3,
201
+ "n_clusters_per_class": 2,
202
+ "weights": None,
203
+ "flip_y": 0.01,
204
+ "class_sep": 1.0,
205
+ "hypercube": True,
206
+ "shift": 0.0,
207
+ "scale": 1.0,
208
+ "shuffle": True,
209
+ "random_state": 42,
210
+ "return_X_y": True,
211
+ }
212
+
213
+ X, y = make_classification(**kwargs)
214
+
215
+ kwargs["return_X_y"] = False
216
+ bunch = make_classification(**kwargs)
217
+
218
+ assert (
219
+ hasattr(bunch, "DESCR")
220
+ and hasattr(bunch, "parameters")
221
+ and hasattr(bunch, "feature_info")
222
+ and hasattr(bunch, "X")
223
+ and hasattr(bunch, "y")
224
+ )
225
+
226
+ def count(str_):
227
+ return bunch.feature_info.count(str_)
228
+
229
+ assert np.array_equal(X, bunch.X)
230
+ assert np.array_equal(y, bunch.y)
231
+ assert bunch.DESCR == make_classification.__doc__
232
+ assert bunch.parameters == kwargs
233
+ assert count("informative") == kwargs["n_informative"]
234
+ assert count("redundant") == kwargs["n_redundant"]
235
+ assert count("repeated") == kwargs["n_repeated"]
236
+
237
+
238
+ @pytest.mark.parametrize(
239
+ "weights, err_type, err_msg",
240
+ [
241
+ ([], ValueError, "Weights specified but incompatible with number of classes."),
242
+ (
243
+ [0.25, 0.75, 0.1],
244
+ ValueError,
245
+ "Weights specified but incompatible with number of classes.",
246
+ ),
247
+ (
248
+ np.array([]),
249
+ ValueError,
250
+ "Weights specified but incompatible with number of classes.",
251
+ ),
252
+ (
253
+ np.array([0.25, 0.75, 0.1]),
254
+ ValueError,
255
+ "Weights specified but incompatible with number of classes.",
256
+ ),
257
+ (
258
+ np.random.random(3),
259
+ ValueError,
260
+ "Weights specified but incompatible with number of classes.",
261
+ ),
262
+ ],
263
+ )
264
+ def test_make_classification_weights_type(weights, err_type, err_msg):
265
+ with pytest.raises(err_type, match=err_msg):
266
+ make_classification(weights=weights)
267
+
268
+
269
+ @pytest.mark.parametrize("kwargs", [{}, {"n_classes": 3, "n_informative": 3}])
270
+ def test_make_classification_weights_array_or_list_ok(kwargs):
271
+ X1, y1 = make_classification(weights=[0.1, 0.9], random_state=0, **kwargs)
272
+ X2, y2 = make_classification(weights=np.array([0.1, 0.9]), random_state=0, **kwargs)
273
+ assert_almost_equal(X1, X2)
274
+ assert_almost_equal(y1, y2)
275
+
276
+
277
+ def test_make_multilabel_classification_return_sequences():
278
+ for allow_unlabeled, min_length in zip((True, False), (0, 1)):
279
+ X, Y = make_multilabel_classification(
280
+ n_samples=100,
281
+ n_features=20,
282
+ n_classes=3,
283
+ random_state=0,
284
+ return_indicator=False,
285
+ allow_unlabeled=allow_unlabeled,
286
+ )
287
+ assert X.shape == (100, 20), "X shape mismatch"
288
+ if not allow_unlabeled:
289
+ assert max([max(y) for y in Y]) == 2
290
+ assert min([len(y) for y in Y]) == min_length
291
+ assert max([len(y) for y in Y]) <= 3
292
+
293
+
294
+ def test_make_multilabel_classification_return_indicator():
295
+ for allow_unlabeled, min_length in zip((True, False), (0, 1)):
296
+ X, Y = make_multilabel_classification(
297
+ n_samples=25,
298
+ n_features=20,
299
+ n_classes=3,
300
+ random_state=0,
301
+ allow_unlabeled=allow_unlabeled,
302
+ )
303
+ assert X.shape == (25, 20), "X shape mismatch"
304
+ assert Y.shape == (25, 3), "Y shape mismatch"
305
+ assert np.all(np.sum(Y, axis=0) > min_length)
306
+
307
+ # Also test return_distributions and return_indicator with True
308
+ X2, Y2, p_c, p_w_c = make_multilabel_classification(
309
+ n_samples=25,
310
+ n_features=20,
311
+ n_classes=3,
312
+ random_state=0,
313
+ allow_unlabeled=allow_unlabeled,
314
+ return_distributions=True,
315
+ )
316
+
317
+ assert_array_almost_equal(X, X2)
318
+ assert_array_equal(Y, Y2)
319
+ assert p_c.shape == (3,)
320
+ assert_almost_equal(p_c.sum(), 1)
321
+ assert p_w_c.shape == (20, 3)
322
+ assert_almost_equal(p_w_c.sum(axis=0), [1] * 3)
323
+
324
+
325
+ def test_make_multilabel_classification_return_indicator_sparse():
326
+ for allow_unlabeled, min_length in zip((True, False), (0, 1)):
327
+ X, Y = make_multilabel_classification(
328
+ n_samples=25,
329
+ n_features=20,
330
+ n_classes=3,
331
+ random_state=0,
332
+ return_indicator="sparse",
333
+ allow_unlabeled=allow_unlabeled,
334
+ )
335
+ assert X.shape == (25, 20), "X shape mismatch"
336
+ assert Y.shape == (25, 3), "Y shape mismatch"
337
+ assert sp.issparse(Y)
338
+
339
+
340
+ def test_make_hastie_10_2():
341
+ X, y = make_hastie_10_2(n_samples=100, random_state=0)
342
+ assert X.shape == (100, 10), "X shape mismatch"
343
+ assert y.shape == (100,), "y shape mismatch"
344
+ assert np.unique(y).shape == (2,), "Unexpected number of classes"
345
+
346
+
347
+ def test_make_regression(global_random_seed):
348
+ X, y, c = make_regression(
349
+ n_samples=200,
350
+ n_features=10,
351
+ n_informative=3,
352
+ effective_rank=5,
353
+ coef=True,
354
+ bias=0.0,
355
+ noise=1.0,
356
+ random_state=global_random_seed,
357
+ )
358
+
359
+ assert X.shape == (200, 10), "X shape mismatch"
360
+ assert y.shape == (200,), "y shape mismatch"
361
+ assert c.shape == (10,), "coef shape mismatch"
362
+ assert sum(c != 0.0) == 3, "Unexpected number of informative features"
363
+
364
+ # Test that y ~= np.dot(X, c) + bias + N(0, 1.0).
365
+ assert_almost_equal(np.std(y - np.dot(X, c)), 1.0, decimal=1)
366
+
367
+ # Test with small number of features.
368
+ X, y = make_regression(n_samples=100, n_features=1) # n_informative=3
369
+ assert X.shape == (100, 1)
370
+
371
+
372
+ def test_make_regression_multitarget(global_random_seed):
373
+ X, y, c = make_regression(
374
+ n_samples=100,
375
+ n_features=10,
376
+ n_informative=3,
377
+ n_targets=3,
378
+ coef=True,
379
+ noise=1.0,
380
+ random_state=global_random_seed,
381
+ )
382
+
383
+ assert X.shape == (100, 10), "X shape mismatch"
384
+ assert y.shape == (100, 3), "y shape mismatch"
385
+ assert c.shape == (10, 3), "coef shape mismatch"
386
+ assert_array_equal(sum(c != 0.0), 3, "Unexpected number of informative features")
387
+
388
+ # Test that y ~= np.dot(X, c) + bias + N(0, 1.0)
389
+ assert_almost_equal(np.std(y - np.dot(X, c)), 1.0, decimal=1)
390
+
391
+
392
+ def test_make_blobs(global_random_seed):
393
+ cluster_stds = np.array([0.05, 0.2, 0.4])
394
+ cluster_centers = np.array([[0.0, 0.0], [1.0, 1.0], [0.0, 1.0]])
395
+ X, y = make_blobs(
396
+ random_state=global_random_seed,
397
+ n_samples=50,
398
+ n_features=2,
399
+ centers=cluster_centers,
400
+ cluster_std=cluster_stds,
401
+ )
402
+
403
+ assert X.shape == (50, 2), "X shape mismatch"
404
+ assert y.shape == (50,), "y shape mismatch"
405
+ assert np.unique(y).shape == (3,), "Unexpected number of blobs"
406
+ for i, (ctr, std) in enumerate(zip(cluster_centers, cluster_stds)):
407
+ assert_almost_equal((X[y == i] - ctr).std(), std, 1, "Unexpected std")
408
+
409
+
410
+ def test_make_blobs_n_samples_list():
411
+ n_samples = [50, 30, 20]
412
+ X, y = make_blobs(n_samples=n_samples, n_features=2, random_state=0)
413
+
414
+ assert X.shape == (sum(n_samples), 2), "X shape mismatch"
415
+ assert all(np.bincount(y, minlength=len(n_samples)) == n_samples), (
416
+ "Incorrect number of samples per blob"
417
+ )
418
+
419
+
420
+ def test_make_blobs_n_samples_list_with_centers(global_random_seed):
421
+ n_samples = [20, 20, 20]
422
+ centers = np.array([[0.0, 0.0], [1.0, 1.0], [0.0, 1.0]])
423
+ cluster_stds = np.array([0.05, 0.2, 0.4])
424
+ X, y = make_blobs(
425
+ n_samples=n_samples,
426
+ centers=centers,
427
+ cluster_std=cluster_stds,
428
+ random_state=global_random_seed,
429
+ )
430
+
431
+ assert X.shape == (sum(n_samples), 2), "X shape mismatch"
432
+ assert all(np.bincount(y, minlength=len(n_samples)) == n_samples), (
433
+ "Incorrect number of samples per blob"
434
+ )
435
+ for i, (ctr, std) in enumerate(zip(centers, cluster_stds)):
436
+ assert_almost_equal((X[y == i] - ctr).std(), std, 1, "Unexpected std")
437
+
438
+
439
+ @pytest.mark.parametrize(
440
+ "n_samples", [[5, 3, 0], np.array([5, 3, 0]), tuple([5, 3, 0])]
441
+ )
442
+ def test_make_blobs_n_samples_centers_none(n_samples):
443
+ centers = None
444
+ X, y = make_blobs(n_samples=n_samples, centers=centers, random_state=0)
445
+
446
+ assert X.shape == (sum(n_samples), 2), "X shape mismatch"
447
+ assert all(np.bincount(y, minlength=len(n_samples)) == n_samples), (
448
+ "Incorrect number of samples per blob"
449
+ )
450
+
451
+
452
+ def test_make_blobs_return_centers():
453
+ n_samples = [10, 20]
454
+ n_features = 3
455
+ X, y, centers = make_blobs(
456
+ n_samples=n_samples, n_features=n_features, return_centers=True, random_state=0
457
+ )
458
+
459
+ assert centers.shape == (len(n_samples), n_features)
460
+
461
+
462
+ def test_make_blobs_error():
463
+ n_samples = [20, 20, 20]
464
+ centers = np.array([[0.0, 0.0], [1.0, 1.0], [0.0, 1.0]])
465
+ cluster_stds = np.array([0.05, 0.2, 0.4])
466
+ wrong_centers_msg = re.escape(
467
+ "Length of `n_samples` not consistent with number of centers. "
468
+ f"Got n_samples = {n_samples} and centers = {centers[:-1]}"
469
+ )
470
+ with pytest.raises(ValueError, match=wrong_centers_msg):
471
+ make_blobs(n_samples, centers=centers[:-1])
472
+ wrong_std_msg = re.escape(
473
+ "Length of `clusters_std` not consistent with number of centers. "
474
+ f"Got centers = {centers} and cluster_std = {cluster_stds[:-1]}"
475
+ )
476
+ with pytest.raises(ValueError, match=wrong_std_msg):
477
+ make_blobs(n_samples, centers=centers, cluster_std=cluster_stds[:-1])
478
+ wrong_type_msg = "Parameter `centers` must be array-like. Got {!r} instead".format(
479
+ 3
480
+ )
481
+ with pytest.raises(ValueError, match=wrong_type_msg):
482
+ make_blobs(n_samples, centers=3)
483
+
484
+
485
+ def test_make_friedman1(global_random_seed):
486
+ X, y = make_friedman1(
487
+ n_samples=5, n_features=10, noise=0.0, random_state=global_random_seed
488
+ )
489
+
490
+ assert X.shape == (5, 10), "X shape mismatch"
491
+ assert y.shape == (5,), "y shape mismatch"
492
+
493
+ assert_array_almost_equal(
494
+ y,
495
+ 10 * np.sin(np.pi * X[:, 0] * X[:, 1])
496
+ + 20 * (X[:, 2] - 0.5) ** 2
497
+ + 10 * X[:, 3]
498
+ + 5 * X[:, 4],
499
+ )
500
+
501
+
502
+ def test_make_friedman2(global_random_seed):
503
+ X, y = make_friedman2(n_samples=5, noise=0.0, random_state=global_random_seed)
504
+
505
+ assert X.shape == (5, 4), "X shape mismatch"
506
+ assert y.shape == (5,), "y shape mismatch"
507
+
508
+ assert_array_almost_equal(
509
+ y, (X[:, 0] ** 2 + (X[:, 1] * X[:, 2] - 1 / (X[:, 1] * X[:, 3])) ** 2) ** 0.5
510
+ )
511
+
512
+
513
+ def test_make_friedman3(global_random_seed):
514
+ X, y = make_friedman3(n_samples=5, noise=0.0, random_state=global_random_seed)
515
+
516
+ assert X.shape == (5, 4), "X shape mismatch"
517
+ assert y.shape == (5,), "y shape mismatch"
518
+
519
+ assert_array_almost_equal(
520
+ y, np.arctan((X[:, 1] * X[:, 2] - 1 / (X[:, 1] * X[:, 3])) / X[:, 0])
521
+ )
522
+
523
+
524
+ def test_make_low_rank_matrix():
525
+ X = make_low_rank_matrix(
526
+ n_samples=50,
527
+ n_features=25,
528
+ effective_rank=5,
529
+ tail_strength=0.01,
530
+ random_state=0,
531
+ )
532
+
533
+ assert X.shape == (50, 25), "X shape mismatch"
534
+
535
+ from numpy.linalg import svd
536
+
537
+ u, s, v = svd(X)
538
+ assert sum(s) - 5 < 0.1, "X rank is not approximately 5"
539
+
540
+
541
+ def test_make_sparse_coded_signal(global_random_seed):
542
+ Y, D, X = make_sparse_coded_signal(
543
+ n_samples=5,
544
+ n_components=8,
545
+ n_features=10,
546
+ n_nonzero_coefs=3,
547
+ random_state=global_random_seed,
548
+ )
549
+ assert Y.shape == (5, 10), "Y shape mismatch"
550
+ assert D.shape == (8, 10), "D shape mismatch"
551
+ assert X.shape == (5, 8), "X shape mismatch"
552
+ for row in X:
553
+ assert len(np.flatnonzero(row)) == 3, "Non-zero coefs mismatch"
554
+ assert_allclose(Y, X @ D)
555
+ assert_allclose(np.sqrt((D**2).sum(axis=1)), np.ones(D.shape[0]))
556
+
557
+
558
+ def test_make_sparse_uncorrelated():
559
+ X, y = make_sparse_uncorrelated(n_samples=5, n_features=10, random_state=0)
560
+
561
+ assert X.shape == (5, 10), "X shape mismatch"
562
+ assert y.shape == (5,), "y shape mismatch"
563
+
564
+
565
+ def test_make_spd_matrix(global_random_seed):
566
+ X = make_spd_matrix(n_dim=5, random_state=global_random_seed)
567
+
568
+ assert X.shape == (5, 5), "X shape mismatch"
569
+ assert_array_almost_equal(X, X.T)
570
+
571
+ from numpy.linalg import eig
572
+
573
+ eigenvalues, _ = eig(X)
574
+ assert np.all(eigenvalues > 0), "X is not positive-definite"
575
+
576
+
577
+ @pytest.mark.parametrize("norm_diag", [True, False])
578
+ @pytest.mark.parametrize(
579
+ "sparse_format", [None, "bsr", "coo", "csc", "csr", "dia", "dok", "lil"]
580
+ )
581
+ def test_make_sparse_spd_matrix(norm_diag, sparse_format, global_random_seed):
582
+ n_dim = 5
583
+ X = make_sparse_spd_matrix(
584
+ n_dim=n_dim,
585
+ norm_diag=norm_diag,
586
+ sparse_format=sparse_format,
587
+ random_state=global_random_seed,
588
+ )
589
+
590
+ assert X.shape == (n_dim, n_dim), "X shape mismatch"
591
+ if sparse_format is None:
592
+ assert not sp.issparse(X)
593
+ assert_allclose(X, X.T)
594
+ Xarr = X
595
+ else:
596
+ assert sp.issparse(X) and X.format == sparse_format
597
+ assert_allclose_dense_sparse(X, X.T)
598
+ Xarr = X.toarray()
599
+
600
+ from numpy.linalg import eig
601
+
602
+ # Do not use scipy.sparse.linalg.eigs because it cannot find all eigenvalues
603
+ eigenvalues, _ = eig(Xarr)
604
+ assert np.all(eigenvalues > 0), "X is not positive-definite"
605
+
606
+ if norm_diag:
607
+ # Check that leading diagonal elements are 1
608
+ assert_array_almost_equal(Xarr.diagonal(), np.ones(n_dim))
609
+
610
+
611
+ @pytest.mark.parametrize("hole", [False, True])
612
+ def test_make_swiss_roll(global_random_seed, hole):
613
+ X, t = make_swiss_roll(
614
+ n_samples=5, noise=0.0, random_state=global_random_seed, hole=hole
615
+ )
616
+
617
+ assert X.shape == (5, 3)
618
+ assert t.shape == (5,)
619
+ assert_array_almost_equal(X[:, 0], t * np.cos(t))
620
+ assert_array_almost_equal(X[:, 2], t * np.sin(t))
621
+
622
+
623
+ def test_make_s_curve(global_random_seed):
624
+ X, t = make_s_curve(n_samples=5, noise=0.0, random_state=global_random_seed)
625
+
626
+ assert X.shape == (5, 3), "X shape mismatch"
627
+ assert t.shape == (5,), "t shape mismatch"
628
+ assert_array_almost_equal(X[:, 0], np.sin(t))
629
+ assert_array_almost_equal(X[:, 2], np.sign(t) * (np.cos(t) - 1))
630
+
631
+
632
+ def test_make_biclusters():
633
+ X, rows, cols = make_biclusters(
634
+ shape=(100, 100), n_clusters=4, shuffle=True, random_state=0
635
+ )
636
+ assert X.shape == (100, 100), "X shape mismatch"
637
+ assert rows.shape == (4, 100), "rows shape mismatch"
638
+ assert cols.shape == (
639
+ 4,
640
+ 100,
641
+ ), "columns shape mismatch"
642
+ assert_all_finite(X)
643
+ assert_all_finite(rows)
644
+ assert_all_finite(cols)
645
+
646
+ X2, _, _ = make_biclusters(
647
+ shape=(100, 100), n_clusters=4, shuffle=True, random_state=0
648
+ )
649
+ assert_array_almost_equal(X, X2)
650
+
651
+
652
+ def test_make_checkerboard():
653
+ X, rows, cols = make_checkerboard(
654
+ shape=(100, 100), n_clusters=(20, 5), shuffle=True, random_state=0
655
+ )
656
+ assert X.shape == (100, 100), "X shape mismatch"
657
+ assert rows.shape == (100, 100), "rows shape mismatch"
658
+ assert cols.shape == (
659
+ 100,
660
+ 100,
661
+ ), "columns shape mismatch"
662
+
663
+ X, rows, cols = make_checkerboard(
664
+ shape=(100, 100), n_clusters=2, shuffle=True, random_state=0
665
+ )
666
+ assert_all_finite(X)
667
+ assert_all_finite(rows)
668
+ assert_all_finite(cols)
669
+
670
+ X1, _, _ = make_checkerboard(
671
+ shape=(100, 100), n_clusters=2, shuffle=True, random_state=0
672
+ )
673
+ X2, _, _ = make_checkerboard(
674
+ shape=(100, 100), n_clusters=2, shuffle=True, random_state=0
675
+ )
676
+ assert_array_almost_equal(X1, X2)
677
+
678
+
679
+ def test_make_moons(global_random_seed):
680
+ X, y = make_moons(3, shuffle=False, random_state=global_random_seed)
681
+ for x, label in zip(X, y):
682
+ center = [0.0, 0.0] if label == 0 else [1.0, 0.5]
683
+ dist_sqr = ((x - center) ** 2).sum()
684
+ assert_almost_equal(
685
+ dist_sqr, 1.0, err_msg="Point is not on expected unit circle"
686
+ )
687
+
688
+
689
+ def test_make_moons_unbalanced():
690
+ X, y = make_moons(n_samples=(7, 5))
691
+ assert np.sum(y == 0) == 7 and np.sum(y == 1) == 5, (
692
+ "Number of samples in a moon is wrong"
693
+ )
694
+ assert X.shape == (12, 2), "X shape mismatch"
695
+ assert y.shape == (12,), "y shape mismatch"
696
+
697
+ with pytest.raises(
698
+ ValueError,
699
+ match=r"`n_samples` can be either an int or a two-element tuple.",
700
+ ):
701
+ make_moons(n_samples=(10,))
702
+
703
+
704
+ def test_make_circles():
705
+ factor = 0.3
706
+
707
+ for n_samples, n_outer, n_inner in [(7, 3, 4), (8, 4, 4)]:
708
+ # Testing odd and even case, because in the past make_circles always
709
+ # created an even number of samples.
710
+ X, y = make_circles(n_samples, shuffle=False, noise=None, factor=factor)
711
+ assert X.shape == (n_samples, 2), "X shape mismatch"
712
+ assert y.shape == (n_samples,), "y shape mismatch"
713
+ center = [0.0, 0.0]
714
+ for x, label in zip(X, y):
715
+ dist_sqr = ((x - center) ** 2).sum()
716
+ dist_exp = 1.0 if label == 0 else factor**2
717
+ dist_exp = 1.0 if label == 0 else factor**2
718
+ assert_almost_equal(
719
+ dist_sqr, dist_exp, err_msg="Point is not on expected circle"
720
+ )
721
+
722
+ assert X[y == 0].shape == (
723
+ n_outer,
724
+ 2,
725
+ ), "Samples not correctly distributed across circles."
726
+ assert X[y == 1].shape == (
727
+ n_inner,
728
+ 2,
729
+ ), "Samples not correctly distributed across circles."
730
+
731
+
732
+ def test_make_circles_unbalanced():
733
+ X, y = make_circles(n_samples=(2, 8))
734
+
735
+ assert np.sum(y == 0) == 2, "Number of samples in inner circle is wrong"
736
+ assert np.sum(y == 1) == 8, "Number of samples in outer circle is wrong"
737
+ assert X.shape == (10, 2), "X shape mismatch"
738
+ assert y.shape == (10,), "y shape mismatch"
739
+
740
+ with pytest.raises(
741
+ ValueError,
742
+ match="When a tuple, n_samples must have exactly two elements.",
743
+ ):
744
+ make_circles(n_samples=(10,))
miniconda3/envs/active_proaction/lib/python3.10/site-packages/sklearn/datasets/tests/test_svmlight_format.py ADDED
@@ -0,0 +1,613 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gzip
2
+ import os
3
+ import shutil
4
+ from bz2 import BZ2File
5
+ from importlib import resources
6
+ from io import BytesIO
7
+ from tempfile import NamedTemporaryFile
8
+
9
+ import numpy as np
10
+ import pytest
11
+ import scipy.sparse as sp
12
+
13
+ import sklearn
14
+ from sklearn.datasets import dump_svmlight_file, load_svmlight_file, load_svmlight_files
15
+ from sklearn.utils._testing import (
16
+ assert_allclose,
17
+ assert_array_almost_equal,
18
+ assert_array_equal,
19
+ create_memmap_backed_data,
20
+ )
21
+ from sklearn.utils.fixes import CSR_CONTAINERS
22
+
23
+ TEST_DATA_MODULE = "sklearn.datasets.tests.data"
24
+ datafile = "svmlight_classification.txt"
25
+ multifile = "svmlight_multilabel.txt"
26
+ invalidfile = "svmlight_invalid.txt"
27
+ invalidfile2 = "svmlight_invalid_order.txt"
28
+
29
+
30
+ def _svmlight_local_test_file_path(filename):
31
+ return resources.files(TEST_DATA_MODULE) / filename
32
+
33
+
34
+ def _load_svmlight_local_test_file(filename, **kwargs):
35
+ """
36
+ Helper to load resource `filename` with `importlib.resources`
37
+ """
38
+ data_path = _svmlight_local_test_file_path(filename)
39
+ with data_path.open("rb") as f:
40
+ return load_svmlight_file(f, **kwargs)
41
+
42
+
43
+ def test_load_svmlight_file():
44
+ X, y = _load_svmlight_local_test_file(datafile)
45
+
46
+ # test X's shape
47
+ assert X.indptr.shape[0] == 7
48
+ assert X.shape[0] == 6
49
+ assert X.shape[1] == 21
50
+ assert y.shape[0] == 6
51
+
52
+ # test X's non-zero values
53
+ for i, j, val in (
54
+ (0, 2, 2.5),
55
+ (0, 10, -5.2),
56
+ (0, 15, 1.5),
57
+ (1, 5, 1.0),
58
+ (1, 12, -3),
59
+ (2, 20, 27),
60
+ ):
61
+ assert X[i, j] == val
62
+
63
+ # tests X's zero values
64
+ assert X[0, 3] == 0
65
+ assert X[0, 5] == 0
66
+ assert X[1, 8] == 0
67
+ assert X[1, 16] == 0
68
+ assert X[2, 18] == 0
69
+
70
+ # test can change X's values
71
+ X[0, 2] *= 2
72
+ assert X[0, 2] == 5
73
+
74
+ # test y
75
+ assert_array_equal(y, [1, 2, 3, 4, 1, 2])
76
+
77
+
78
+ def test_load_svmlight_file_fd():
79
+ # test loading from file descriptor
80
+
81
+ # GH20081: testing equality between path-based and
82
+ # fd-based load_svmlight_file
83
+
84
+ data_path = resources.files(TEST_DATA_MODULE) / datafile
85
+ data_path = str(data_path)
86
+ X1, y1 = load_svmlight_file(data_path)
87
+
88
+ fd = os.open(data_path, os.O_RDONLY)
89
+ try:
90
+ X2, y2 = load_svmlight_file(fd)
91
+ assert_array_almost_equal(X1.data, X2.data)
92
+ assert_array_almost_equal(y1, y2)
93
+ finally:
94
+ os.close(fd)
95
+
96
+
97
+ def test_load_svmlight_pathlib():
98
+ # test loading from file descriptor
99
+ data_path = _svmlight_local_test_file_path(datafile)
100
+ X1, y1 = load_svmlight_file(str(data_path))
101
+ X2, y2 = load_svmlight_file(data_path)
102
+
103
+ assert_allclose(X1.data, X2.data)
104
+ assert_allclose(y1, y2)
105
+
106
+
107
+ def test_load_svmlight_file_multilabel():
108
+ X, y = _load_svmlight_local_test_file(multifile, multilabel=True)
109
+ assert y == [(0, 1), (2,), (), (1, 2)]
110
+
111
+
112
+ def test_load_svmlight_files():
113
+ data_path = _svmlight_local_test_file_path(datafile)
114
+ X_train, y_train, X_test, y_test = load_svmlight_files(
115
+ [str(data_path)] * 2, dtype=np.float32
116
+ )
117
+ assert_array_equal(X_train.toarray(), X_test.toarray())
118
+ assert_array_almost_equal(y_train, y_test)
119
+ assert X_train.dtype == np.float32
120
+ assert X_test.dtype == np.float32
121
+
122
+ X1, y1, X2, y2, X3, y3 = load_svmlight_files([str(data_path)] * 3, dtype=np.float64)
123
+ assert X1.dtype == X2.dtype
124
+ assert X2.dtype == X3.dtype
125
+ assert X3.dtype == np.float64
126
+
127
+
128
+ def test_load_svmlight_file_n_features():
129
+ X, y = _load_svmlight_local_test_file(datafile, n_features=22)
130
+
131
+ # test X'shape
132
+ assert X.indptr.shape[0] == 7
133
+ assert X.shape[0] == 6
134
+ assert X.shape[1] == 22
135
+
136
+ # test X's non-zero values
137
+ for i, j, val in ((0, 2, 2.5), (0, 10, -5.2), (1, 5, 1.0), (1, 12, -3)):
138
+ assert X[i, j] == val
139
+
140
+ # 21 features in file
141
+ with pytest.raises(ValueError):
142
+ _load_svmlight_local_test_file(datafile, n_features=20)
143
+
144
+
145
+ def test_load_compressed():
146
+ X, y = _load_svmlight_local_test_file(datafile)
147
+
148
+ with NamedTemporaryFile(prefix="sklearn-test", suffix=".gz") as tmp:
149
+ tmp.close() # necessary under windows
150
+ with _svmlight_local_test_file_path(datafile).open("rb") as f:
151
+ with gzip.open(tmp.name, "wb") as fh_out:
152
+ shutil.copyfileobj(f, fh_out)
153
+ Xgz, ygz = load_svmlight_file(tmp.name)
154
+ # because we "close" it manually and write to it,
155
+ # we need to remove it manually.
156
+ os.remove(tmp.name)
157
+ assert_array_almost_equal(X.toarray(), Xgz.toarray())
158
+ assert_array_almost_equal(y, ygz)
159
+
160
+ with NamedTemporaryFile(prefix="sklearn-test", suffix=".bz2") as tmp:
161
+ tmp.close() # necessary under windows
162
+ with _svmlight_local_test_file_path(datafile).open("rb") as f:
163
+ with BZ2File(tmp.name, "wb") as fh_out:
164
+ shutil.copyfileobj(f, fh_out)
165
+ Xbz, ybz = load_svmlight_file(tmp.name)
166
+ # because we "close" it manually and write to it,
167
+ # we need to remove it manually.
168
+ os.remove(tmp.name)
169
+ assert_array_almost_equal(X.toarray(), Xbz.toarray())
170
+ assert_array_almost_equal(y, ybz)
171
+
172
+
173
+ def test_load_invalid_file():
174
+ with pytest.raises(ValueError):
175
+ _load_svmlight_local_test_file(invalidfile)
176
+
177
+
178
+ def test_load_invalid_order_file():
179
+ with pytest.raises(ValueError):
180
+ _load_svmlight_local_test_file(invalidfile2)
181
+
182
+
183
+ def test_load_zero_based():
184
+ f = BytesIO(b"-1 4:1.\n1 0:1\n")
185
+ with pytest.raises(ValueError):
186
+ load_svmlight_file(f, zero_based=False)
187
+
188
+
189
+ def test_load_zero_based_auto():
190
+ data1 = b"-1 1:1 2:2 3:3\n"
191
+ data2 = b"-1 0:0 1:1\n"
192
+
193
+ f1 = BytesIO(data1)
194
+ X, y = load_svmlight_file(f1, zero_based="auto")
195
+ assert X.shape == (1, 3)
196
+
197
+ f1 = BytesIO(data1)
198
+ f2 = BytesIO(data2)
199
+ X1, y1, X2, y2 = load_svmlight_files([f1, f2], zero_based="auto")
200
+ assert X1.shape == (1, 4)
201
+ assert X2.shape == (1, 4)
202
+
203
+
204
+ def test_load_with_qid():
205
+ # load svmfile with qid attribute
206
+ data = b"""
207
+ 3 qid:1 1:0.53 2:0.12
208
+ 2 qid:1 1:0.13 2:0.1
209
+ 7 qid:2 1:0.87 2:0.12"""
210
+ X, y = load_svmlight_file(BytesIO(data), query_id=False)
211
+ assert_array_equal(y, [3, 2, 7])
212
+ assert_array_equal(X.toarray(), [[0.53, 0.12], [0.13, 0.1], [0.87, 0.12]])
213
+ res1 = load_svmlight_files([BytesIO(data)], query_id=True)
214
+ res2 = load_svmlight_file(BytesIO(data), query_id=True)
215
+ for X, y, qid in (res1, res2):
216
+ assert_array_equal(y, [3, 2, 7])
217
+ assert_array_equal(qid, [1, 1, 2])
218
+ assert_array_equal(X.toarray(), [[0.53, 0.12], [0.13, 0.1], [0.87, 0.12]])
219
+
220
+
221
+ @pytest.mark.skip(
222
+ "testing the overflow of 32 bit sparse indexing requires a large amount of memory"
223
+ )
224
+ def test_load_large_qid():
225
+ """
226
+ load large libsvm / svmlight file with qid attribute. Tests 64-bit query ID
227
+ """
228
+ data = b"\n".join(
229
+ (
230
+ "3 qid:{0} 1:0.53 2:0.12\n2 qid:{0} 1:0.13 2:0.1".format(i).encode()
231
+ for i in range(1, 40 * 1000 * 1000)
232
+ )
233
+ )
234
+ X, y, qid = load_svmlight_file(BytesIO(data), query_id=True)
235
+ assert_array_equal(y[-4:], [3, 2, 3, 2])
236
+ assert_array_equal(np.unique(qid), np.arange(1, 40 * 1000 * 1000))
237
+
238
+
239
+ def test_load_invalid_file2():
240
+ with pytest.raises(ValueError):
241
+ data_path = _svmlight_local_test_file_path(datafile)
242
+ invalid_path = _svmlight_local_test_file_path(invalidfile)
243
+ load_svmlight_files([str(data_path), str(invalid_path), str(data_path)])
244
+
245
+
246
+ def test_not_a_filename():
247
+ # in python 3 integers are valid file opening arguments (taken as unix
248
+ # file descriptors)
249
+ with pytest.raises(TypeError):
250
+ load_svmlight_file(0.42)
251
+
252
+
253
+ def test_invalid_filename():
254
+ with pytest.raises(OSError):
255
+ load_svmlight_file("trou pic nic douille")
256
+
257
+
258
+ @pytest.mark.parametrize("csr_container", CSR_CONTAINERS)
259
+ def test_dump(csr_container):
260
+ X_sparse, y_dense = _load_svmlight_local_test_file(datafile)
261
+ X_dense = X_sparse.toarray()
262
+ y_sparse = csr_container(np.atleast_2d(y_dense))
263
+
264
+ # slicing a csr_matrix can unsort its .indices, so test that we sort
265
+ # those correctly
266
+ X_sliced = X_sparse[np.arange(X_sparse.shape[0])]
267
+ y_sliced = y_sparse[np.arange(y_sparse.shape[0])]
268
+
269
+ for X in (X_sparse, X_dense, X_sliced):
270
+ for y in (y_sparse, y_dense, y_sliced):
271
+ for zero_based in (True, False):
272
+ for dtype in [np.float32, np.float64, np.int32, np.int64]:
273
+ f = BytesIO()
274
+ # we need to pass a comment to get the version info in;
275
+ # LibSVM doesn't grok comments so they're not put in by
276
+ # default anymore.
277
+
278
+ if sp.issparse(y) and y.shape[0] == 1:
279
+ # make sure y's shape is: (n_samples, n_labels)
280
+ # when it is sparse
281
+ y = y.T
282
+
283
+ # Note: with dtype=np.int32 we are performing unsafe casts,
284
+ # where X.astype(dtype) overflows. The result is
285
+ # then platform dependent and X_dense.astype(dtype) may be
286
+ # different from X_sparse.astype(dtype).asarray().
287
+ X_input = X.astype(dtype)
288
+
289
+ dump_svmlight_file(
290
+ X_input, y, f, comment="test", zero_based=zero_based
291
+ )
292
+ f.seek(0)
293
+
294
+ comment = f.readline()
295
+ comment = str(comment, "utf-8")
296
+
297
+ assert "scikit-learn %s" % sklearn.__version__ in comment
298
+
299
+ comment = f.readline()
300
+ comment = str(comment, "utf-8")
301
+
302
+ assert ["one", "zero"][zero_based] + "-based" in comment
303
+
304
+ X2, y2 = load_svmlight_file(f, dtype=dtype, zero_based=zero_based)
305
+ assert X2.dtype == dtype
306
+ assert_array_equal(X2.sorted_indices().indices, X2.indices)
307
+
308
+ X2_dense = X2.toarray()
309
+ if sp.issparse(X_input):
310
+ X_input_dense = X_input.toarray()
311
+ else:
312
+ X_input_dense = X_input
313
+
314
+ if dtype == np.float32:
315
+ # allow a rounding error at the last decimal place
316
+ assert_array_almost_equal(X_input_dense, X2_dense, 4)
317
+ assert_array_almost_equal(
318
+ y_dense.astype(dtype, copy=False), y2, 4
319
+ )
320
+ else:
321
+ # allow a rounding error at the last decimal place
322
+ assert_array_almost_equal(X_input_dense, X2_dense, 15)
323
+ assert_array_almost_equal(
324
+ y_dense.astype(dtype, copy=False), y2, 15
325
+ )
326
+
327
+
328
+ @pytest.mark.parametrize("csr_container", CSR_CONTAINERS)
329
+ def test_dump_multilabel(csr_container):
330
+ X = [[1, 0, 3, 0, 5], [0, 0, 0, 0, 0], [0, 5, 0, 1, 0]]
331
+ y_dense = [[0, 1, 0], [1, 0, 1], [1, 1, 0]]
332
+ y_sparse = csr_container(y_dense)
333
+ for y in [y_dense, y_sparse]:
334
+ f = BytesIO()
335
+ dump_svmlight_file(X, y, f, multilabel=True)
336
+ f.seek(0)
337
+ # make sure it dumps multilabel correctly
338
+ assert f.readline() == b"1 0:1 2:3 4:5\n"
339
+ assert f.readline() == b"0,2 \n"
340
+ assert f.readline() == b"0,1 1:5 3:1\n"
341
+
342
+
343
+ def test_dump_concise():
344
+ one = 1
345
+ two = 2.1
346
+ three = 3.01
347
+ exact = 1.000000000000001
348
+ # loses the last decimal place
349
+ almost = 1.0000000000000001
350
+ X = [
351
+ [one, two, three, exact, almost],
352
+ [1e9, 2e18, 3e27, 0, 0],
353
+ [0, 0, 0, 0, 0],
354
+ [0, 0, 0, 0, 0],
355
+ [0, 0, 0, 0, 0],
356
+ ]
357
+ y = [one, two, three, exact, almost]
358
+ f = BytesIO()
359
+ dump_svmlight_file(X, y, f)
360
+ f.seek(0)
361
+ # make sure it's using the most concise format possible
362
+ assert f.readline() == b"1 0:1 1:2.1 2:3.01 3:1.000000000000001 4:1\n"
363
+ assert f.readline() == b"2.1 0:1000000000 1:2e+18 2:3e+27\n"
364
+ assert f.readline() == b"3.01 \n"
365
+ assert f.readline() == b"1.000000000000001 \n"
366
+ assert f.readline() == b"1 \n"
367
+ f.seek(0)
368
+ # make sure it's correct too :)
369
+ X2, y2 = load_svmlight_file(f)
370
+ assert_array_almost_equal(X, X2.toarray())
371
+ assert_array_almost_equal(y, y2)
372
+
373
+
374
+ def test_dump_comment():
375
+ X, y = _load_svmlight_local_test_file(datafile)
376
+ X = X.toarray()
377
+
378
+ f = BytesIO()
379
+ ascii_comment = "This is a comment\nspanning multiple lines."
380
+ dump_svmlight_file(X, y, f, comment=ascii_comment, zero_based=False)
381
+ f.seek(0)
382
+
383
+ X2, y2 = load_svmlight_file(f, zero_based=False)
384
+ assert_array_almost_equal(X, X2.toarray())
385
+ assert_array_almost_equal(y, y2)
386
+
387
+ # XXX we have to update this to support Python 3.x
388
+ utf8_comment = b"It is true that\n\xc2\xbd\xc2\xb2 = \xc2\xbc"
389
+ f = BytesIO()
390
+ with pytest.raises(UnicodeDecodeError):
391
+ dump_svmlight_file(X, y, f, comment=utf8_comment)
392
+
393
+ unicode_comment = utf8_comment.decode("utf-8")
394
+ f = BytesIO()
395
+ dump_svmlight_file(X, y, f, comment=unicode_comment, zero_based=False)
396
+ f.seek(0)
397
+
398
+ X2, y2 = load_svmlight_file(f, zero_based=False)
399
+ assert_array_almost_equal(X, X2.toarray())
400
+ assert_array_almost_equal(y, y2)
401
+
402
+ f = BytesIO()
403
+ with pytest.raises(ValueError):
404
+ dump_svmlight_file(X, y, f, comment="I've got a \0.")
405
+
406
+
407
+ def test_dump_invalid():
408
+ X, y = _load_svmlight_local_test_file(datafile)
409
+
410
+ f = BytesIO()
411
+ y2d = [y]
412
+ with pytest.raises(ValueError):
413
+ dump_svmlight_file(X, y2d, f)
414
+
415
+ f = BytesIO()
416
+ with pytest.raises(ValueError):
417
+ dump_svmlight_file(X, y[:-1], f)
418
+
419
+
420
+ def test_dump_query_id():
421
+ # test dumping a file with query_id
422
+ X, y = _load_svmlight_local_test_file(datafile)
423
+ X = X.toarray()
424
+ query_id = np.arange(X.shape[0]) // 2
425
+ f = BytesIO()
426
+ dump_svmlight_file(X, y, f, query_id=query_id, zero_based=True)
427
+
428
+ f.seek(0)
429
+ X1, y1, query_id1 = load_svmlight_file(f, query_id=True, zero_based=True)
430
+ assert_array_almost_equal(X, X1.toarray())
431
+ assert_array_almost_equal(y, y1)
432
+ assert_array_almost_equal(query_id, query_id1)
433
+
434
+
435
+ def test_load_with_long_qid():
436
+ # load svmfile with longint qid attribute
437
+ data = b"""
438
+ 1 qid:0 0:1 1:2 2:3
439
+ 0 qid:72048431380967004 0:1440446648 1:72048431380967004 2:236784985
440
+ 0 qid:-9223372036854775807 0:1440446648 1:72048431380967004 2:236784985
441
+ 3 qid:9223372036854775807 0:1440446648 1:72048431380967004 2:236784985"""
442
+ X, y, qid = load_svmlight_file(BytesIO(data), query_id=True)
443
+
444
+ true_X = [
445
+ [1, 2, 3],
446
+ [1440446648, 72048431380967004, 236784985],
447
+ [1440446648, 72048431380967004, 236784985],
448
+ [1440446648, 72048431380967004, 236784985],
449
+ ]
450
+
451
+ true_y = [1, 0, 0, 3]
452
+ trueQID = [0, 72048431380967004, -9223372036854775807, 9223372036854775807]
453
+ assert_array_equal(y, true_y)
454
+ assert_array_equal(X.toarray(), true_X)
455
+ assert_array_equal(qid, trueQID)
456
+
457
+ f = BytesIO()
458
+ dump_svmlight_file(X, y, f, query_id=qid, zero_based=True)
459
+ f.seek(0)
460
+ X, y, qid = load_svmlight_file(f, query_id=True, zero_based=True)
461
+ assert_array_equal(y, true_y)
462
+ assert_array_equal(X.toarray(), true_X)
463
+ assert_array_equal(qid, trueQID)
464
+
465
+ f.seek(0)
466
+ X, y = load_svmlight_file(f, query_id=False, zero_based=True)
467
+ assert_array_equal(y, true_y)
468
+ assert_array_equal(X.toarray(), true_X)
469
+
470
+
471
+ @pytest.mark.parametrize("csr_container", CSR_CONTAINERS)
472
+ def test_load_zeros(csr_container):
473
+ f = BytesIO()
474
+ true_X = csr_container(np.zeros(shape=(3, 4)))
475
+ true_y = np.array([0, 1, 0])
476
+ dump_svmlight_file(true_X, true_y, f)
477
+
478
+ for zero_based in ["auto", True, False]:
479
+ f.seek(0)
480
+ X, y = load_svmlight_file(f, n_features=4, zero_based=zero_based)
481
+ assert_array_almost_equal(y, true_y)
482
+ assert_array_almost_equal(X.toarray(), true_X.toarray())
483
+
484
+
485
+ @pytest.mark.parametrize("sparsity", [0, 0.1, 0.5, 0.99, 1])
486
+ @pytest.mark.parametrize("n_samples", [13, 101])
487
+ @pytest.mark.parametrize("n_features", [2, 7, 41])
488
+ @pytest.mark.parametrize("csr_container", CSR_CONTAINERS)
489
+ def test_load_with_offsets(sparsity, n_samples, n_features, csr_container):
490
+ rng = np.random.RandomState(0)
491
+ X = rng.uniform(low=0.0, high=1.0, size=(n_samples, n_features))
492
+ if sparsity:
493
+ X[X < sparsity] = 0.0
494
+ X = csr_container(X)
495
+ y = rng.randint(low=0, high=2, size=n_samples)
496
+
497
+ f = BytesIO()
498
+ dump_svmlight_file(X, y, f)
499
+ f.seek(0)
500
+
501
+ size = len(f.getvalue())
502
+
503
+ # put some marks that are likely to happen anywhere in a row
504
+ mark_0 = 0
505
+ mark_1 = size // 3
506
+ length_0 = mark_1 - mark_0
507
+ mark_2 = 4 * size // 5
508
+ length_1 = mark_2 - mark_1
509
+
510
+ # load the original sparse matrix into 3 independent CSR matrices
511
+ X_0, y_0 = load_svmlight_file(
512
+ f, n_features=n_features, offset=mark_0, length=length_0
513
+ )
514
+ X_1, y_1 = load_svmlight_file(
515
+ f, n_features=n_features, offset=mark_1, length=length_1
516
+ )
517
+ X_2, y_2 = load_svmlight_file(f, n_features=n_features, offset=mark_2)
518
+
519
+ y_concat = np.concatenate([y_0, y_1, y_2])
520
+ X_concat = sp.vstack([X_0, X_1, X_2])
521
+ assert_array_almost_equal(y, y_concat)
522
+ assert_array_almost_equal(X.toarray(), X_concat.toarray())
523
+
524
+
525
+ @pytest.mark.parametrize("csr_container", CSR_CONTAINERS)
526
+ def test_load_offset_exhaustive_splits(csr_container):
527
+ rng = np.random.RandomState(0)
528
+ X = np.array(
529
+ [
530
+ [0, 0, 0, 0, 0, 0],
531
+ [1, 2, 3, 4, 0, 6],
532
+ [1, 2, 3, 4, 0, 6],
533
+ [0, 0, 0, 0, 0, 0],
534
+ [1, 0, 3, 0, 0, 0],
535
+ [0, 0, 0, 0, 0, 1],
536
+ [1, 0, 0, 0, 0, 0],
537
+ ]
538
+ )
539
+ X = csr_container(X)
540
+ n_samples, n_features = X.shape
541
+ y = rng.randint(low=0, high=2, size=n_samples)
542
+ query_id = np.arange(n_samples) // 2
543
+
544
+ f = BytesIO()
545
+ dump_svmlight_file(X, y, f, query_id=query_id)
546
+ f.seek(0)
547
+
548
+ size = len(f.getvalue())
549
+
550
+ # load the same data in 2 parts with all the possible byte offsets to
551
+ # locate the split so has to test for particular boundary cases
552
+ for mark in range(size):
553
+ f.seek(0)
554
+ X_0, y_0, q_0 = load_svmlight_file(
555
+ f, n_features=n_features, query_id=True, offset=0, length=mark
556
+ )
557
+ X_1, y_1, q_1 = load_svmlight_file(
558
+ f, n_features=n_features, query_id=True, offset=mark, length=-1
559
+ )
560
+ q_concat = np.concatenate([q_0, q_1])
561
+ y_concat = np.concatenate([y_0, y_1])
562
+ X_concat = sp.vstack([X_0, X_1])
563
+ assert_array_almost_equal(y, y_concat)
564
+ assert_array_equal(query_id, q_concat)
565
+ assert_array_almost_equal(X.toarray(), X_concat.toarray())
566
+
567
+
568
+ def test_load_with_offsets_error():
569
+ with pytest.raises(ValueError, match="n_features is required"):
570
+ _load_svmlight_local_test_file(datafile, offset=3, length=3)
571
+
572
+
573
+ @pytest.mark.parametrize("csr_container", CSR_CONTAINERS)
574
+ def test_multilabel_y_explicit_zeros(tmp_path, csr_container):
575
+ """
576
+ Ensure that if y contains explicit zeros (i.e. elements of y.data equal to
577
+ 0) then those explicit zeros are not encoded.
578
+ """
579
+ save_path = str(tmp_path / "svm_explicit_zero")
580
+ rng = np.random.RandomState(42)
581
+ X = rng.randn(3, 5).astype(np.float64)
582
+ indptr = np.array([0, 2, 3, 6])
583
+ indices = np.array([0, 2, 2, 0, 1, 2])
584
+ # The first and last element are explicit zeros.
585
+ data = np.array([0, 1, 1, 1, 1, 0])
586
+ y = csr_container((data, indices, indptr), shape=(3, 3))
587
+ # y as a dense array would look like
588
+ # [[0, 0, 1],
589
+ # [0, 0, 1],
590
+ # [1, 1, 0]]
591
+
592
+ dump_svmlight_file(X, y, save_path, multilabel=True)
593
+
594
+ _, y_load = load_svmlight_file(save_path, multilabel=True)
595
+ y_true = [(2.0,), (2.0,), (0.0, 1.0)]
596
+ assert y_load == y_true
597
+
598
+
599
+ def test_dump_read_only(tmp_path):
600
+ """Ensure that there is no ValueError when dumping a read-only `X`.
601
+
602
+ Non-regression test for:
603
+ https://github.com/scikit-learn/scikit-learn/issues/28026
604
+ """
605
+ rng = np.random.RandomState(42)
606
+ X = rng.randn(5, 2)
607
+ y = rng.randn(5)
608
+
609
+ # Convert to memmap-backed which are read-only
610
+ X, y = create_memmap_backed_data([X, y])
611
+
612
+ save_path = str(tmp_path / "svm_read_only")
613
+ dump_svmlight_file(X, y, save_path)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/sklearn/decomposition/__init__.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Matrix decomposition algorithms.
2
+
3
+ These include PCA, NMF, ICA, and more. Most of the algorithms of this module can be
4
+ regarded as dimensionality reduction techniques.
5
+ """
6
+
7
+ # Authors: The scikit-learn developers
8
+ # SPDX-License-Identifier: BSD-3-Clause
9
+
10
+ from ..utils.extmath import randomized_svd
11
+ from ._dict_learning import (
12
+ DictionaryLearning,
13
+ MiniBatchDictionaryLearning,
14
+ SparseCoder,
15
+ dict_learning,
16
+ dict_learning_online,
17
+ sparse_encode,
18
+ )
19
+ from ._factor_analysis import FactorAnalysis
20
+ from ._fastica import FastICA, fastica
21
+ from ._incremental_pca import IncrementalPCA
22
+ from ._kernel_pca import KernelPCA
23
+ from ._lda import LatentDirichletAllocation
24
+ from ._nmf import (
25
+ NMF,
26
+ MiniBatchNMF,
27
+ non_negative_factorization,
28
+ )
29
+ from ._pca import PCA
30
+ from ._sparse_pca import MiniBatchSparsePCA, SparsePCA
31
+ from ._truncated_svd import TruncatedSVD
32
+
33
+ __all__ = [
34
+ "NMF",
35
+ "PCA",
36
+ "DictionaryLearning",
37
+ "FactorAnalysis",
38
+ "FastICA",
39
+ "IncrementalPCA",
40
+ "KernelPCA",
41
+ "LatentDirichletAllocation",
42
+ "MiniBatchDictionaryLearning",
43
+ "MiniBatchNMF",
44
+ "MiniBatchSparsePCA",
45
+ "SparseCoder",
46
+ "SparsePCA",
47
+ "TruncatedSVD",
48
+ "dict_learning",
49
+ "dict_learning_online",
50
+ "fastica",
51
+ "non_negative_factorization",
52
+ "randomized_svd",
53
+ "sparse_encode",
54
+ ]
miniconda3/envs/active_proaction/lib/python3.10/site-packages/sklearn/decomposition/_base.py ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Principal Component Analysis Base Classes"""
2
+
3
+ # Authors: The scikit-learn developers
4
+ # SPDX-License-Identifier: BSD-3-Clause
5
+
6
+ from abc import ABCMeta, abstractmethod
7
+
8
+ import numpy as np
9
+ from scipy import linalg
10
+
11
+ from ..base import BaseEstimator, ClassNamePrefixFeaturesOutMixin, TransformerMixin
12
+ from ..utils._array_api import _fill_or_add_to_diagonal, device, get_namespace
13
+ from ..utils.validation import check_is_fitted, validate_data
14
+
15
+
16
+ class _BasePCA(
17
+ ClassNamePrefixFeaturesOutMixin, TransformerMixin, BaseEstimator, metaclass=ABCMeta
18
+ ):
19
+ """Base class for PCA methods.
20
+
21
+ Warning: This class should not be used directly.
22
+ Use derived classes instead.
23
+ """
24
+
25
+ def get_covariance(self):
26
+ """Compute data covariance with the generative model.
27
+
28
+ ``cov = components_.T * S**2 * components_ + sigma2 * eye(n_features)``
29
+ where S**2 contains the explained variances, and sigma2 contains the
30
+ noise variances.
31
+
32
+ Returns
33
+ -------
34
+ cov : array of shape=(n_features, n_features)
35
+ Estimated covariance of data.
36
+ """
37
+ xp, _ = get_namespace(self.components_)
38
+
39
+ components_ = self.components_
40
+ exp_var = self.explained_variance_
41
+ if self.whiten:
42
+ components_ = components_ * xp.sqrt(exp_var[:, np.newaxis])
43
+ exp_var_diff = exp_var - self.noise_variance_
44
+ exp_var_diff = xp.where(
45
+ exp_var > self.noise_variance_,
46
+ exp_var_diff,
47
+ xp.asarray(0.0, device=device(exp_var), dtype=exp_var.dtype),
48
+ )
49
+ cov = (components_.T * exp_var_diff) @ components_
50
+ _fill_or_add_to_diagonal(cov, self.noise_variance_, xp)
51
+ return cov
52
+
53
+ def get_precision(self):
54
+ """Compute data precision matrix with the generative model.
55
+
56
+ Equals the inverse of the covariance but computed with
57
+ the matrix inversion lemma for efficiency.
58
+
59
+ Returns
60
+ -------
61
+ precision : array, shape=(n_features, n_features)
62
+ Estimated precision of data.
63
+ """
64
+ xp, is_array_api_compliant = get_namespace(self.components_)
65
+
66
+ n_features = self.components_.shape[1]
67
+
68
+ # handle corner cases first
69
+ if self.n_components_ == 0:
70
+ return xp.eye(n_features) / self.noise_variance_
71
+
72
+ if is_array_api_compliant:
73
+ linalg_inv = xp.linalg.inv
74
+ else:
75
+ linalg_inv = linalg.inv
76
+
77
+ if self.noise_variance_ == 0.0:
78
+ return linalg_inv(self.get_covariance())
79
+
80
+ # Get precision using matrix inversion lemma
81
+ components_ = self.components_
82
+ exp_var = self.explained_variance_
83
+ if self.whiten:
84
+ components_ = components_ * xp.sqrt(exp_var[:, np.newaxis])
85
+ exp_var_diff = exp_var - self.noise_variance_
86
+ exp_var_diff = xp.where(
87
+ exp_var > self.noise_variance_,
88
+ exp_var_diff,
89
+ xp.asarray(0.0, device=device(exp_var)),
90
+ )
91
+ precision = components_ @ components_.T / self.noise_variance_
92
+ _fill_or_add_to_diagonal(precision, 1.0 / exp_var_diff, xp)
93
+ precision = components_.T @ linalg_inv(precision) @ components_
94
+ precision /= -(self.noise_variance_**2)
95
+ _fill_or_add_to_diagonal(precision, 1.0 / self.noise_variance_, xp)
96
+ return precision
97
+
98
+ @abstractmethod
99
+ def fit(self, X, y=None):
100
+ """Placeholder for fit. Subclasses should implement this method!
101
+
102
+ Fit the model with X.
103
+
104
+ Parameters
105
+ ----------
106
+ X : array-like of shape (n_samples, n_features)
107
+ Training data, where `n_samples` is the number of samples and
108
+ `n_features` is the number of features.
109
+
110
+ Returns
111
+ -------
112
+ self : object
113
+ Returns the instance itself.
114
+ """
115
+
116
+ def transform(self, X):
117
+ """Apply dimensionality reduction to X.
118
+
119
+ X is projected on the first principal components previously extracted
120
+ from a training set.
121
+
122
+ Parameters
123
+ ----------
124
+ X : {array-like, sparse matrix} of shape (n_samples, n_features)
125
+ New data, where `n_samples` is the number of samples
126
+ and `n_features` is the number of features.
127
+
128
+ Returns
129
+ -------
130
+ X_new : array-like of shape (n_samples, n_components)
131
+ Projection of X in the first principal components, where `n_samples`
132
+ is the number of samples and `n_components` is the number of the components.
133
+ """
134
+ xp, _ = get_namespace(X, self.components_, self.explained_variance_)
135
+
136
+ check_is_fitted(self)
137
+
138
+ X = validate_data(
139
+ self,
140
+ X,
141
+ dtype=[xp.float64, xp.float32],
142
+ accept_sparse=("csr", "csc"),
143
+ reset=False,
144
+ )
145
+ return self._transform(X, xp=xp, x_is_centered=False)
146
+
147
+ def _transform(self, X, xp, x_is_centered=False):
148
+ X_transformed = X @ self.components_.T
149
+ if not x_is_centered:
150
+ # Apply the centering after the projection.
151
+ # For dense X this avoids copying or mutating the data passed by
152
+ # the caller.
153
+ # For sparse X it keeps sparsity and avoids having to wrap X into
154
+ # a linear operator.
155
+ X_transformed -= xp.reshape(self.mean_, (1, -1)) @ self.components_.T
156
+ if self.whiten:
157
+ # For some solvers (such as "arpack" and "covariance_eigh"), on
158
+ # rank deficient data, some components can have a variance
159
+ # arbitrarily close to zero, leading to non-finite results when
160
+ # whitening. To avoid this problem we clip the variance below.
161
+ scale = xp.sqrt(self.explained_variance_)
162
+ min_scale = xp.finfo(scale.dtype).eps
163
+ scale[scale < min_scale] = min_scale
164
+ X_transformed /= scale
165
+ return X_transformed
166
+
167
+ def inverse_transform(self, X):
168
+ """Transform data back to its original space.
169
+
170
+ In other words, return an input `X_original` whose transform would be X.
171
+
172
+ Parameters
173
+ ----------
174
+ X : array-like of shape (n_samples, n_components)
175
+ New data, where `n_samples` is the number of samples
176
+ and `n_components` is the number of components.
177
+
178
+ Returns
179
+ -------
180
+ X_original : array-like of shape (n_samples, n_features)
181
+ Original data, where `n_samples` is the number of samples
182
+ and `n_features` is the number of features.
183
+
184
+ Notes
185
+ -----
186
+ If whitening is enabled, inverse_transform will compute the
187
+ exact inverse operation, which includes reversing whitening.
188
+ """
189
+ xp, _ = get_namespace(X)
190
+
191
+ if self.whiten:
192
+ scaled_components = (
193
+ xp.sqrt(self.explained_variance_[:, np.newaxis]) * self.components_
194
+ )
195
+ return X @ scaled_components + self.mean_
196
+ else:
197
+ return X @ self.components_ + self.mean_
198
+
199
+ @property
200
+ def _n_features_out(self):
201
+ """Number of transformed output features."""
202
+ return self.components_.shape[0]
miniconda3/envs/active_proaction/lib/python3.10/site-packages/sklearn/decomposition/_cdnmf_fast.pyx ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Authors: The scikit-learn developers
2
+ # SPDX-License-Identifier: BSD-3-Clause
3
+
4
+ from cython cimport floating
5
+ from libc.math cimport fabs
6
+
7
+
8
+ def _update_cdnmf_fast(floating[:, ::1] W, floating[:, :] HHt,
9
+ floating[:, :] XHt, Py_ssize_t[::1] permutation):
10
+ cdef:
11
+ floating violation = 0
12
+ Py_ssize_t n_components = W.shape[1]
13
+ Py_ssize_t n_samples = W.shape[0] # n_features for H update
14
+ floating grad, pg, hess
15
+ Py_ssize_t i, r, s, t
16
+
17
+ with nogil:
18
+ for s in range(n_components):
19
+ t = permutation[s]
20
+
21
+ for i in range(n_samples):
22
+ # gradient = GW[t, i] where GW = np.dot(W, HHt) - XHt
23
+ grad = -XHt[i, t]
24
+
25
+ for r in range(n_components):
26
+ grad += HHt[t, r] * W[i, r]
27
+
28
+ # projected gradient
29
+ pg = min(0., grad) if W[i, t] == 0 else grad
30
+ violation += fabs(pg)
31
+
32
+ # Hessian
33
+ hess = HHt[t, t]
34
+
35
+ if hess != 0:
36
+ W[i, t] = max(W[i, t] - grad / hess, 0.)
37
+
38
+ return violation
miniconda3/envs/active_proaction/lib/python3.10/site-packages/sklearn/decomposition/_dict_learning.py ADDED
@@ -0,0 +1,2329 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Dictionary learning."""
2
+
3
+ # Authors: The scikit-learn developers
4
+ # SPDX-License-Identifier: BSD-3-Clause
5
+
6
+ import itertools
7
+ import sys
8
+ import time
9
+ from numbers import Integral, Real
10
+
11
+ import numpy as np
12
+ from joblib import effective_n_jobs
13
+ from scipy import linalg
14
+
15
+ from ..base import (
16
+ BaseEstimator,
17
+ ClassNamePrefixFeaturesOutMixin,
18
+ TransformerMixin,
19
+ _fit_context,
20
+ )
21
+ from ..linear_model import Lars, Lasso, LassoLars, orthogonal_mp_gram
22
+ from ..utils import check_array, check_random_state, gen_batches, gen_even_slices
23
+ from ..utils._param_validation import Interval, StrOptions, validate_params
24
+ from ..utils.extmath import _randomized_svd, row_norms, svd_flip
25
+ from ..utils.parallel import Parallel, delayed
26
+ from ..utils.validation import check_is_fitted, validate_data
27
+
28
+
29
+ def _check_positive_coding(method, positive):
30
+ if positive and method in ["omp", "lars"]:
31
+ raise ValueError(
32
+ "Positive constraint not supported for '{}' coding method.".format(method)
33
+ )
34
+
35
+
36
+ def _sparse_encode_precomputed(
37
+ X,
38
+ dictionary,
39
+ *,
40
+ gram=None,
41
+ cov=None,
42
+ algorithm="lasso_lars",
43
+ regularization=None,
44
+ copy_cov=True,
45
+ init=None,
46
+ max_iter=1000,
47
+ verbose=0,
48
+ positive=False,
49
+ ):
50
+ """Generic sparse coding with precomputed Gram and/or covariance matrices.
51
+
52
+ Each row of the result is the solution to a Lasso problem.
53
+
54
+ Parameters
55
+ ----------
56
+ X : ndarray of shape (n_samples, n_features)
57
+ Data matrix.
58
+
59
+ dictionary : ndarray of shape (n_components, n_features)
60
+ The dictionary matrix against which to solve the sparse coding of
61
+ the data. Some of the algorithms assume normalized rows.
62
+
63
+ gram : ndarray of shape (n_components, n_components), default=None
64
+ Precomputed Gram matrix, `dictionary * dictionary'`
65
+ gram can be `None` if method is 'threshold'.
66
+
67
+ cov : ndarray of shape (n_components, n_samples), default=None
68
+ Precomputed covariance, `dictionary * X'`.
69
+
70
+ algorithm : {'lasso_lars', 'lasso_cd', 'lars', 'omp', 'threshold'}, \
71
+ default='lasso_lars'
72
+ The algorithm used:
73
+
74
+ * `'lars'`: uses the least angle regression method
75
+ (`linear_model.lars_path`);
76
+ * `'lasso_lars'`: uses Lars to compute the Lasso solution;
77
+ * `'lasso_cd'`: uses the coordinate descent method to compute the
78
+ Lasso solution (`linear_model.Lasso`). lasso_lars will be faster if
79
+ the estimated components are sparse;
80
+ * `'omp'`: uses orthogonal matching pursuit to estimate the sparse
81
+ solution;
82
+ * `'threshold'`: squashes to zero all coefficients less than
83
+ regularization from the projection `dictionary * data'`.
84
+
85
+ regularization : int or float, default=None
86
+ The regularization parameter. It corresponds to alpha when
87
+ algorithm is `'lasso_lars'`, `'lasso_cd'` or `'threshold'`.
88
+ Otherwise it corresponds to `n_nonzero_coefs`.
89
+
90
+ init : ndarray of shape (n_samples, n_components), default=None
91
+ Initialization value of the sparse code. Only used if
92
+ `algorithm='lasso_cd'`.
93
+
94
+ max_iter : int, default=1000
95
+ Maximum number of iterations to perform if `algorithm='lasso_cd'` or
96
+ `'lasso_lars'`.
97
+
98
+ copy_cov : bool, default=True
99
+ Whether to copy the precomputed covariance matrix; if `False`, it may
100
+ be overwritten.
101
+
102
+ verbose : int, default=0
103
+ Controls the verbosity; the higher, the more messages.
104
+
105
+ positive: bool, default=False
106
+ Whether to enforce a positivity constraint on the sparse code.
107
+
108
+ .. versionadded:: 0.20
109
+
110
+ Returns
111
+ -------
112
+ code : ndarray of shape (n_components, n_features)
113
+ The sparse codes.
114
+ """
115
+ n_samples, n_features = X.shape
116
+ n_components = dictionary.shape[0]
117
+
118
+ if algorithm == "lasso_lars":
119
+ alpha = float(regularization) / n_features # account for scaling
120
+ try:
121
+ err_mgt = np.seterr(all="ignore")
122
+
123
+ # Not passing in verbose=max(0, verbose-1) because Lars.fit already
124
+ # corrects the verbosity level.
125
+ lasso_lars = LassoLars(
126
+ alpha=alpha,
127
+ fit_intercept=False,
128
+ verbose=verbose,
129
+ precompute=gram,
130
+ fit_path=False,
131
+ positive=positive,
132
+ max_iter=max_iter,
133
+ )
134
+ lasso_lars.fit(dictionary.T, X.T, Xy=cov)
135
+ new_code = lasso_lars.coef_
136
+ finally:
137
+ np.seterr(**err_mgt)
138
+
139
+ elif algorithm == "lasso_cd":
140
+ alpha = float(regularization) / n_features # account for scaling
141
+
142
+ # TODO: Make verbosity argument for Lasso?
143
+ # sklearn.linear_model.coordinate_descent.enet_path has a verbosity
144
+ # argument that we could pass in from Lasso.
145
+ clf = Lasso(
146
+ alpha=alpha,
147
+ fit_intercept=False,
148
+ precompute=gram,
149
+ max_iter=max_iter,
150
+ warm_start=True,
151
+ positive=positive,
152
+ )
153
+
154
+ if init is not None:
155
+ # In some workflows using coordinate descent algorithms:
156
+ # - users might provide NumPy arrays with read-only buffers
157
+ # - `joblib` might memmap arrays making their buffer read-only
158
+ # TODO: move this handling (which is currently too broad)
159
+ # closer to the actual private function which need buffers to be writable.
160
+ if not init.flags["WRITEABLE"]:
161
+ init = np.array(init)
162
+ clf.coef_ = init
163
+
164
+ clf.fit(dictionary.T, X.T, check_input=False)
165
+ new_code = clf.coef_
166
+
167
+ elif algorithm == "lars":
168
+ try:
169
+ err_mgt = np.seterr(all="ignore")
170
+
171
+ # Not passing in verbose=max(0, verbose-1) because Lars.fit already
172
+ # corrects the verbosity level.
173
+ lars = Lars(
174
+ fit_intercept=False,
175
+ verbose=verbose,
176
+ precompute=gram,
177
+ n_nonzero_coefs=int(regularization),
178
+ fit_path=False,
179
+ )
180
+ lars.fit(dictionary.T, X.T, Xy=cov)
181
+ new_code = lars.coef_
182
+ finally:
183
+ np.seterr(**err_mgt)
184
+
185
+ elif algorithm == "threshold":
186
+ new_code = (np.sign(cov) * np.maximum(np.abs(cov) - regularization, 0)).T
187
+ if positive:
188
+ np.clip(new_code, 0, None, out=new_code)
189
+
190
+ elif algorithm == "omp":
191
+ new_code = orthogonal_mp_gram(
192
+ Gram=gram,
193
+ Xy=cov,
194
+ n_nonzero_coefs=int(regularization),
195
+ tol=None,
196
+ norms_squared=row_norms(X, squared=True),
197
+ copy_Xy=copy_cov,
198
+ ).T
199
+
200
+ return new_code.reshape(n_samples, n_components)
201
+
202
+
203
+ @validate_params(
204
+ {
205
+ "X": ["array-like"],
206
+ "dictionary": ["array-like"],
207
+ "gram": ["array-like", None],
208
+ "cov": ["array-like", None],
209
+ "algorithm": [
210
+ StrOptions({"lasso_lars", "lasso_cd", "lars", "omp", "threshold"})
211
+ ],
212
+ "n_nonzero_coefs": [Interval(Integral, 1, None, closed="left"), None],
213
+ "alpha": [Interval(Real, 0, None, closed="left"), None],
214
+ "copy_cov": ["boolean"],
215
+ "init": ["array-like", None],
216
+ "max_iter": [Interval(Integral, 0, None, closed="left")],
217
+ "n_jobs": [Integral, None],
218
+ "check_input": ["boolean"],
219
+ "verbose": ["verbose"],
220
+ "positive": ["boolean"],
221
+ },
222
+ prefer_skip_nested_validation=True,
223
+ )
224
+ # XXX : could be moved to the linear_model module
225
+ def sparse_encode(
226
+ X,
227
+ dictionary,
228
+ *,
229
+ gram=None,
230
+ cov=None,
231
+ algorithm="lasso_lars",
232
+ n_nonzero_coefs=None,
233
+ alpha=None,
234
+ copy_cov=True,
235
+ init=None,
236
+ max_iter=1000,
237
+ n_jobs=None,
238
+ check_input=True,
239
+ verbose=0,
240
+ positive=False,
241
+ ):
242
+ """Sparse coding.
243
+
244
+ Each row of the result is the solution to a sparse coding problem.
245
+ The goal is to find a sparse array `code` such that::
246
+
247
+ X ~= code * dictionary
248
+
249
+ Read more in the :ref:`User Guide <SparseCoder>`.
250
+
251
+ Parameters
252
+ ----------
253
+ X : array-like of shape (n_samples, n_features)
254
+ Data matrix.
255
+
256
+ dictionary : array-like of shape (n_components, n_features)
257
+ The dictionary matrix against which to solve the sparse coding of
258
+ the data. Some of the algorithms assume normalized rows for meaningful
259
+ output.
260
+
261
+ gram : array-like of shape (n_components, n_components), default=None
262
+ Precomputed Gram matrix, `dictionary * dictionary'`.
263
+
264
+ cov : array-like of shape (n_components, n_samples), default=None
265
+ Precomputed covariance, `dictionary' * X`.
266
+
267
+ algorithm : {'lasso_lars', 'lasso_cd', 'lars', 'omp', 'threshold'}, \
268
+ default='lasso_lars'
269
+ The algorithm used:
270
+
271
+ * `'lars'`: uses the least angle regression method
272
+ (`linear_model.lars_path`);
273
+ * `'lasso_lars'`: uses Lars to compute the Lasso solution;
274
+ * `'lasso_cd'`: uses the coordinate descent method to compute the
275
+ Lasso solution (`linear_model.Lasso`). lasso_lars will be faster if
276
+ the estimated components are sparse;
277
+ * `'omp'`: uses orthogonal matching pursuit to estimate the sparse
278
+ solution;
279
+ * `'threshold'`: squashes to zero all coefficients less than
280
+ regularization from the projection `dictionary * data'`.
281
+
282
+ n_nonzero_coefs : int, default=None
283
+ Number of nonzero coefficients to target in each column of the
284
+ solution. This is only used by `algorithm='lars'` and `algorithm='omp'`
285
+ and is overridden by `alpha` in the `omp` case. If `None`, then
286
+ `n_nonzero_coefs=int(n_features / 10)`.
287
+
288
+ alpha : float, default=None
289
+ If `algorithm='lasso_lars'` or `algorithm='lasso_cd'`, `alpha` is the
290
+ penalty applied to the L1 norm.
291
+ If `algorithm='threshold'`, `alpha` is the absolute value of the
292
+ threshold below which coefficients will be squashed to zero.
293
+ If `algorithm='omp'`, `alpha` is the tolerance parameter: the value of
294
+ the reconstruction error targeted. In this case, it overrides
295
+ `n_nonzero_coefs`.
296
+ If `None`, default to 1.
297
+
298
+ copy_cov : bool, default=True
299
+ Whether to copy the precomputed covariance matrix; if `False`, it may
300
+ be overwritten.
301
+
302
+ init : ndarray of shape (n_samples, n_components), default=None
303
+ Initialization value of the sparse codes. Only used if
304
+ `algorithm='lasso_cd'`.
305
+
306
+ max_iter : int, default=1000
307
+ Maximum number of iterations to perform if `algorithm='lasso_cd'` or
308
+ `'lasso_lars'`.
309
+
310
+ n_jobs : int, default=None
311
+ Number of parallel jobs to run.
312
+ ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
313
+ ``-1`` means using all processors. See :term:`Glossary <n_jobs>`
314
+ for more details.
315
+
316
+ check_input : bool, default=True
317
+ If `False`, the input arrays X and dictionary will not be checked.
318
+
319
+ verbose : int, default=0
320
+ Controls the verbosity; the higher, the more messages.
321
+
322
+ positive : bool, default=False
323
+ Whether to enforce positivity when finding the encoding.
324
+
325
+ .. versionadded:: 0.20
326
+
327
+ Returns
328
+ -------
329
+ code : ndarray of shape (n_samples, n_components)
330
+ The sparse codes.
331
+
332
+ See Also
333
+ --------
334
+ sklearn.linear_model.lars_path : Compute Least Angle Regression or Lasso
335
+ path using LARS algorithm.
336
+ sklearn.linear_model.orthogonal_mp : Solves Orthogonal Matching Pursuit problems.
337
+ sklearn.linear_model.Lasso : Train Linear Model with L1 prior as regularizer.
338
+ SparseCoder : Find a sparse representation of data from a fixed precomputed
339
+ dictionary.
340
+
341
+ Examples
342
+ --------
343
+ >>> import numpy as np
344
+ >>> from sklearn.decomposition import sparse_encode
345
+ >>> X = np.array([[-1, -1, -1], [0, 0, 3]])
346
+ >>> dictionary = np.array(
347
+ ... [[0, 1, 0],
348
+ ... [-1, -1, 2],
349
+ ... [1, 1, 1],
350
+ ... [0, 1, 1],
351
+ ... [0, 2, 1]],
352
+ ... dtype=np.float64
353
+ ... )
354
+ >>> sparse_encode(X, dictionary, alpha=1e-10)
355
+ array([[ 0., 0., -1., 0., 0.],
356
+ [ 0., 1., 1., 0., 0.]])
357
+ """
358
+ if check_input:
359
+ if algorithm == "lasso_cd":
360
+ dictionary = check_array(
361
+ dictionary, order="C", dtype=[np.float64, np.float32]
362
+ )
363
+ X = check_array(X, order="C", dtype=[np.float64, np.float32])
364
+ else:
365
+ dictionary = check_array(dictionary)
366
+ X = check_array(X)
367
+
368
+ if dictionary.shape[1] != X.shape[1]:
369
+ raise ValueError(
370
+ "Dictionary and X have different numbers of features:"
371
+ "dictionary.shape: {} X.shape{}".format(dictionary.shape, X.shape)
372
+ )
373
+
374
+ _check_positive_coding(algorithm, positive)
375
+
376
+ return _sparse_encode(
377
+ X,
378
+ dictionary,
379
+ gram=gram,
380
+ cov=cov,
381
+ algorithm=algorithm,
382
+ n_nonzero_coefs=n_nonzero_coefs,
383
+ alpha=alpha,
384
+ copy_cov=copy_cov,
385
+ init=init,
386
+ max_iter=max_iter,
387
+ n_jobs=n_jobs,
388
+ verbose=verbose,
389
+ positive=positive,
390
+ )
391
+
392
+
393
+ def _sparse_encode(
394
+ X,
395
+ dictionary,
396
+ *,
397
+ gram=None,
398
+ cov=None,
399
+ algorithm="lasso_lars",
400
+ n_nonzero_coefs=None,
401
+ alpha=None,
402
+ copy_cov=True,
403
+ init=None,
404
+ max_iter=1000,
405
+ n_jobs=None,
406
+ verbose=0,
407
+ positive=False,
408
+ ):
409
+ """Sparse coding without input/parameter validation."""
410
+
411
+ n_samples, n_features = X.shape
412
+ n_components = dictionary.shape[0]
413
+
414
+ if algorithm in ("lars", "omp"):
415
+ regularization = n_nonzero_coefs
416
+ if regularization is None:
417
+ regularization = min(max(n_features / 10, 1), n_components)
418
+ else:
419
+ regularization = alpha
420
+ if regularization is None:
421
+ regularization = 1.0
422
+
423
+ if gram is None and algorithm != "threshold":
424
+ gram = np.dot(dictionary, dictionary.T)
425
+
426
+ if cov is None and algorithm != "lasso_cd":
427
+ copy_cov = False
428
+ cov = np.dot(dictionary, X.T)
429
+
430
+ if effective_n_jobs(n_jobs) == 1 or algorithm == "threshold":
431
+ code = _sparse_encode_precomputed(
432
+ X,
433
+ dictionary,
434
+ gram=gram,
435
+ cov=cov,
436
+ algorithm=algorithm,
437
+ regularization=regularization,
438
+ copy_cov=copy_cov,
439
+ init=init,
440
+ max_iter=max_iter,
441
+ verbose=verbose,
442
+ positive=positive,
443
+ )
444
+ return code
445
+
446
+ # Enter parallel code block
447
+ n_samples = X.shape[0]
448
+ n_components = dictionary.shape[0]
449
+ code = np.empty((n_samples, n_components))
450
+ slices = list(gen_even_slices(n_samples, effective_n_jobs(n_jobs)))
451
+
452
+ code_views = Parallel(n_jobs=n_jobs, verbose=verbose)(
453
+ delayed(_sparse_encode_precomputed)(
454
+ X[this_slice],
455
+ dictionary,
456
+ gram=gram,
457
+ cov=cov[:, this_slice] if cov is not None else None,
458
+ algorithm=algorithm,
459
+ regularization=regularization,
460
+ copy_cov=copy_cov,
461
+ init=init[this_slice] if init is not None else None,
462
+ max_iter=max_iter,
463
+ verbose=verbose,
464
+ positive=positive,
465
+ )
466
+ for this_slice in slices
467
+ )
468
+ for this_slice, this_view in zip(slices, code_views):
469
+ code[this_slice] = this_view
470
+ return code
471
+
472
+
473
+ def _update_dict(
474
+ dictionary,
475
+ Y,
476
+ code,
477
+ A=None,
478
+ B=None,
479
+ verbose=False,
480
+ random_state=None,
481
+ positive=False,
482
+ ):
483
+ """Update the dense dictionary factor in place.
484
+
485
+ Parameters
486
+ ----------
487
+ dictionary : ndarray of shape (n_components, n_features)
488
+ Value of the dictionary at the previous iteration.
489
+
490
+ Y : ndarray of shape (n_samples, n_features)
491
+ Data matrix.
492
+
493
+ code : ndarray of shape (n_samples, n_components)
494
+ Sparse coding of the data against which to optimize the dictionary.
495
+
496
+ A : ndarray of shape (n_components, n_components), default=None
497
+ Together with `B`, sufficient stats of the online model to update the
498
+ dictionary.
499
+
500
+ B : ndarray of shape (n_features, n_components), default=None
501
+ Together with `A`, sufficient stats of the online model to update the
502
+ dictionary.
503
+
504
+ verbose: bool, default=False
505
+ Degree of output the procedure will print.
506
+
507
+ random_state : int, RandomState instance or None, default=None
508
+ Used for randomly initializing the dictionary. Pass an int for
509
+ reproducible results across multiple function calls.
510
+ See :term:`Glossary <random_state>`.
511
+
512
+ positive : bool, default=False
513
+ Whether to enforce positivity when finding the dictionary.
514
+
515
+ .. versionadded:: 0.20
516
+ """
517
+ n_samples, n_components = code.shape
518
+ random_state = check_random_state(random_state)
519
+
520
+ if A is None:
521
+ A = code.T @ code
522
+ if B is None:
523
+ B = Y.T @ code
524
+
525
+ n_unused = 0
526
+
527
+ for k in range(n_components):
528
+ if A[k, k] > 1e-6:
529
+ # 1e-6 is arbitrary but consistent with the spams implementation
530
+ dictionary[k] += (B[:, k] - A[k] @ dictionary) / A[k, k]
531
+ else:
532
+ # kth atom is almost never used -> sample a new one from the data
533
+ newd = Y[random_state.choice(n_samples)]
534
+
535
+ # add small noise to avoid making the sparse coding ill conditioned
536
+ noise_level = 0.01 * (newd.std() or 1) # avoid 0 std
537
+ noise = random_state.normal(0, noise_level, size=len(newd))
538
+
539
+ dictionary[k] = newd + noise
540
+ code[:, k] = 0
541
+ n_unused += 1
542
+
543
+ if positive:
544
+ np.clip(dictionary[k], 0, None, out=dictionary[k])
545
+
546
+ # Projection on the constraint set ||V_k|| <= 1
547
+ dictionary[k] /= max(linalg.norm(dictionary[k]), 1)
548
+
549
+ if verbose and n_unused > 0:
550
+ print(f"{n_unused} unused atoms resampled.")
551
+
552
+
553
+ def _dict_learning(
554
+ X,
555
+ n_components,
556
+ *,
557
+ alpha,
558
+ max_iter,
559
+ tol,
560
+ method,
561
+ n_jobs,
562
+ dict_init,
563
+ code_init,
564
+ callback,
565
+ verbose,
566
+ random_state,
567
+ return_n_iter,
568
+ positive_dict,
569
+ positive_code,
570
+ method_max_iter,
571
+ ):
572
+ """Main dictionary learning algorithm"""
573
+ t0 = time.time()
574
+ # Init the code and the dictionary with SVD of Y
575
+ if code_init is not None and dict_init is not None:
576
+ code = np.array(code_init, order="F")
577
+ # Don't copy V, it will happen below
578
+ dictionary = dict_init
579
+ else:
580
+ code, S, dictionary = linalg.svd(X, full_matrices=False)
581
+ # flip the initial code's sign to enforce deterministic output
582
+ code, dictionary = svd_flip(code, dictionary)
583
+ dictionary = S[:, np.newaxis] * dictionary
584
+ r = len(dictionary)
585
+ if n_components <= r: # True even if n_components=None
586
+ code = code[:, :n_components]
587
+ dictionary = dictionary[:n_components, :]
588
+ else:
589
+ code = np.c_[code, np.zeros((len(code), n_components - r))]
590
+ dictionary = np.r_[
591
+ dictionary, np.zeros((n_components - r, dictionary.shape[1]))
592
+ ]
593
+
594
+ # Fortran-order dict better suited for the sparse coding which is the
595
+ # bottleneck of this algorithm.
596
+ dictionary = np.asfortranarray(dictionary)
597
+
598
+ errors = []
599
+ current_cost = np.nan
600
+
601
+ if verbose == 1:
602
+ print("[dict_learning]", end=" ")
603
+
604
+ # If max_iter is 0, number of iterations returned should be zero
605
+ ii = -1
606
+
607
+ for ii in range(max_iter):
608
+ dt = time.time() - t0
609
+ if verbose == 1:
610
+ sys.stdout.write(".")
611
+ sys.stdout.flush()
612
+ elif verbose:
613
+ print(
614
+ "Iteration % 3i (elapsed time: % 3is, % 4.1fmn, current cost % 7.3f)"
615
+ % (ii, dt, dt / 60, current_cost)
616
+ )
617
+
618
+ # Update code
619
+ code = sparse_encode(
620
+ X,
621
+ dictionary,
622
+ algorithm=method,
623
+ alpha=alpha,
624
+ init=code,
625
+ n_jobs=n_jobs,
626
+ positive=positive_code,
627
+ max_iter=method_max_iter,
628
+ verbose=verbose,
629
+ )
630
+
631
+ # Update dictionary in place
632
+ _update_dict(
633
+ dictionary,
634
+ X,
635
+ code,
636
+ verbose=verbose,
637
+ random_state=random_state,
638
+ positive=positive_dict,
639
+ )
640
+
641
+ # Cost function
642
+ current_cost = 0.5 * np.sum((X - code @ dictionary) ** 2) + alpha * np.sum(
643
+ np.abs(code)
644
+ )
645
+ errors.append(current_cost)
646
+
647
+ if ii > 0:
648
+ dE = errors[-2] - errors[-1]
649
+ # assert(dE >= -tol * errors[-1])
650
+ if dE < tol * errors[-1]:
651
+ if verbose == 1:
652
+ # A line return
653
+ print("")
654
+ elif verbose:
655
+ print("--- Convergence reached after %d iterations" % ii)
656
+ break
657
+ if ii % 5 == 0 and callback is not None:
658
+ callback(locals())
659
+
660
+ if return_n_iter:
661
+ return code, dictionary, errors, ii + 1
662
+ else:
663
+ return code, dictionary, errors
664
+
665
+
666
+ @validate_params(
667
+ {
668
+ "X": ["array-like"],
669
+ "return_code": ["boolean"],
670
+ "method": [StrOptions({"cd", "lars"})],
671
+ "method_max_iter": [Interval(Integral, 0, None, closed="left")],
672
+ },
673
+ prefer_skip_nested_validation=False,
674
+ )
675
+ def dict_learning_online(
676
+ X,
677
+ n_components=2,
678
+ *,
679
+ alpha=1,
680
+ max_iter=100,
681
+ return_code=True,
682
+ dict_init=None,
683
+ callback=None,
684
+ batch_size=256,
685
+ verbose=False,
686
+ shuffle=True,
687
+ n_jobs=None,
688
+ method="lars",
689
+ random_state=None,
690
+ positive_dict=False,
691
+ positive_code=False,
692
+ method_max_iter=1000,
693
+ tol=1e-3,
694
+ max_no_improvement=10,
695
+ ):
696
+ """Solve a dictionary learning matrix factorization problem online.
697
+
698
+ Finds the best dictionary and the corresponding sparse code for
699
+ approximating the data matrix X by solving::
700
+
701
+ (U^*, V^*) = argmin 0.5 || X - U V ||_Fro^2 + alpha * || U ||_1,1
702
+ (U,V)
703
+ with || V_k ||_2 = 1 for all 0 <= k < n_components
704
+
705
+ where V is the dictionary and U is the sparse code. ||.||_Fro stands for
706
+ the Frobenius norm and ||.||_1,1 stands for the entry-wise matrix norm
707
+ which is the sum of the absolute values of all the entries in the matrix.
708
+ This is accomplished by repeatedly iterating over mini-batches by slicing
709
+ the input data.
710
+
711
+ Read more in the :ref:`User Guide <DictionaryLearning>`.
712
+
713
+ Parameters
714
+ ----------
715
+ X : array-like of shape (n_samples, n_features)
716
+ Data matrix.
717
+
718
+ n_components : int or None, default=2
719
+ Number of dictionary atoms to extract. If None, then ``n_components``
720
+ is set to ``n_features``.
721
+
722
+ alpha : float, default=1
723
+ Sparsity controlling parameter.
724
+
725
+ max_iter : int, default=100
726
+ Maximum number of iterations over the complete dataset before
727
+ stopping independently of any early stopping criterion heuristics.
728
+
729
+ .. versionadded:: 1.1
730
+
731
+ return_code : bool, default=True
732
+ Whether to also return the code U or just the dictionary `V`.
733
+
734
+ dict_init : ndarray of shape (n_components, n_features), default=None
735
+ Initial values for the dictionary for warm restart scenarios.
736
+ If `None`, the initial values for the dictionary are created
737
+ with an SVD decomposition of the data via
738
+ :func:`~sklearn.utils.extmath.randomized_svd`.
739
+
740
+ callback : callable, default=None
741
+ A callable that gets invoked at the end of each iteration.
742
+
743
+ batch_size : int, default=256
744
+ The number of samples to take in each batch.
745
+
746
+ .. versionchanged:: 1.3
747
+ The default value of `batch_size` changed from 3 to 256 in version 1.3.
748
+
749
+ verbose : bool, default=False
750
+ To control the verbosity of the procedure.
751
+
752
+ shuffle : bool, default=True
753
+ Whether to shuffle the data before splitting it in batches.
754
+
755
+ n_jobs : int, default=None
756
+ Number of parallel jobs to run.
757
+ ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
758
+ ``-1`` means using all processors. See :term:`Glossary <n_jobs>`
759
+ for more details.
760
+
761
+ method : {'lars', 'cd'}, default='lars'
762
+ * `'lars'`: uses the least angle regression method to solve the lasso
763
+ problem (`linear_model.lars_path`);
764
+ * `'cd'`: uses the coordinate descent method to compute the
765
+ Lasso solution (`linear_model.Lasso`). Lars will be faster if
766
+ the estimated components are sparse.
767
+
768
+ random_state : int, RandomState instance or None, default=None
769
+ Used for initializing the dictionary when ``dict_init`` is not
770
+ specified, randomly shuffling the data when ``shuffle`` is set to
771
+ ``True``, and updating the dictionary. Pass an int for reproducible
772
+ results across multiple function calls.
773
+ See :term:`Glossary <random_state>`.
774
+
775
+ positive_dict : bool, default=False
776
+ Whether to enforce positivity when finding the dictionary.
777
+
778
+ .. versionadded:: 0.20
779
+
780
+ positive_code : bool, default=False
781
+ Whether to enforce positivity when finding the code.
782
+
783
+ .. versionadded:: 0.20
784
+
785
+ method_max_iter : int, default=1000
786
+ Maximum number of iterations to perform when solving the lasso problem.
787
+
788
+ .. versionadded:: 0.22
789
+
790
+ tol : float, default=1e-3
791
+ Control early stopping based on the norm of the differences in the
792
+ dictionary between 2 steps.
793
+
794
+ To disable early stopping based on changes in the dictionary, set
795
+ `tol` to 0.0.
796
+
797
+ .. versionadded:: 1.1
798
+
799
+ max_no_improvement : int, default=10
800
+ Control early stopping based on the consecutive number of mini batches
801
+ that does not yield an improvement on the smoothed cost function.
802
+
803
+ To disable convergence detection based on cost function, set
804
+ `max_no_improvement` to None.
805
+
806
+ .. versionadded:: 1.1
807
+
808
+ Returns
809
+ -------
810
+ code : ndarray of shape (n_samples, n_components),
811
+ The sparse code (only returned if `return_code=True`).
812
+
813
+ dictionary : ndarray of shape (n_components, n_features),
814
+ The solutions to the dictionary learning problem.
815
+
816
+ n_iter : int
817
+ Number of iterations run. Returned only if `return_n_iter` is
818
+ set to `True`.
819
+
820
+ See Also
821
+ --------
822
+ dict_learning : Solve a dictionary learning matrix factorization problem.
823
+ DictionaryLearning : Find a dictionary that sparsely encodes data.
824
+ MiniBatchDictionaryLearning : A faster, less accurate, version of the dictionary
825
+ learning algorithm.
826
+ SparsePCA : Sparse Principal Components Analysis.
827
+ MiniBatchSparsePCA : Mini-batch Sparse Principal Components Analysis.
828
+
829
+ Examples
830
+ --------
831
+ >>> import numpy as np
832
+ >>> from sklearn.datasets import make_sparse_coded_signal
833
+ >>> from sklearn.decomposition import dict_learning_online
834
+ >>> X, _, _ = make_sparse_coded_signal(
835
+ ... n_samples=30, n_components=15, n_features=20, n_nonzero_coefs=10,
836
+ ... random_state=42,
837
+ ... )
838
+ >>> U, V = dict_learning_online(
839
+ ... X, n_components=15, alpha=0.2, max_iter=20, batch_size=3, random_state=42
840
+ ... )
841
+
842
+ We can check the level of sparsity of `U`:
843
+
844
+ >>> np.mean(U == 0)
845
+ np.float64(0.53)
846
+
847
+ We can compare the average squared euclidean norm of the reconstruction
848
+ error of the sparse coded signal relative to the squared euclidean norm of
849
+ the original signal:
850
+
851
+ >>> X_hat = U @ V
852
+ >>> np.mean(np.sum((X_hat - X) ** 2, axis=1) / np.sum(X ** 2, axis=1))
853
+ np.float64(0.053)
854
+ """
855
+ transform_algorithm = "lasso_" + method
856
+
857
+ est = MiniBatchDictionaryLearning(
858
+ n_components=n_components,
859
+ alpha=alpha,
860
+ max_iter=max_iter,
861
+ n_jobs=n_jobs,
862
+ fit_algorithm=method,
863
+ batch_size=batch_size,
864
+ shuffle=shuffle,
865
+ dict_init=dict_init,
866
+ random_state=random_state,
867
+ transform_algorithm=transform_algorithm,
868
+ transform_alpha=alpha,
869
+ positive_code=positive_code,
870
+ positive_dict=positive_dict,
871
+ transform_max_iter=method_max_iter,
872
+ verbose=verbose,
873
+ callback=callback,
874
+ tol=tol,
875
+ max_no_improvement=max_no_improvement,
876
+ ).fit(X)
877
+
878
+ if not return_code:
879
+ return est.components_
880
+ else:
881
+ code = est.transform(X)
882
+ return code, est.components_
883
+
884
+
885
+ @validate_params(
886
+ {
887
+ "X": ["array-like"],
888
+ "method": [StrOptions({"lars", "cd"})],
889
+ "return_n_iter": ["boolean"],
890
+ "method_max_iter": [Interval(Integral, 0, None, closed="left")],
891
+ },
892
+ prefer_skip_nested_validation=False,
893
+ )
894
+ def dict_learning(
895
+ X,
896
+ n_components,
897
+ *,
898
+ alpha,
899
+ max_iter=100,
900
+ tol=1e-8,
901
+ method="lars",
902
+ n_jobs=None,
903
+ dict_init=None,
904
+ code_init=None,
905
+ callback=None,
906
+ verbose=False,
907
+ random_state=None,
908
+ return_n_iter=False,
909
+ positive_dict=False,
910
+ positive_code=False,
911
+ method_max_iter=1000,
912
+ ):
913
+ """Solve a dictionary learning matrix factorization problem.
914
+
915
+ Finds the best dictionary and the corresponding sparse code for
916
+ approximating the data matrix X by solving::
917
+
918
+ (U^*, V^*) = argmin 0.5 || X - U V ||_Fro^2 + alpha * || U ||_1,1
919
+ (U,V)
920
+ with || V_k ||_2 = 1 for all 0 <= k < n_components
921
+
922
+ where V is the dictionary and U is the sparse code. ||.||_Fro stands for
923
+ the Frobenius norm and ||.||_1,1 stands for the entry-wise matrix norm
924
+ which is the sum of the absolute values of all the entries in the matrix.
925
+
926
+ Read more in the :ref:`User Guide <DictionaryLearning>`.
927
+
928
+ Parameters
929
+ ----------
930
+ X : array-like of shape (n_samples, n_features)
931
+ Data matrix.
932
+
933
+ n_components : int
934
+ Number of dictionary atoms to extract.
935
+
936
+ alpha : int or float
937
+ Sparsity controlling parameter.
938
+
939
+ max_iter : int, default=100
940
+ Maximum number of iterations to perform.
941
+
942
+ tol : float, default=1e-8
943
+ Tolerance for the stopping condition.
944
+
945
+ method : {'lars', 'cd'}, default='lars'
946
+ The method used:
947
+
948
+ * `'lars'`: uses the least angle regression method to solve the lasso
949
+ problem (`linear_model.lars_path`);
950
+ * `'cd'`: uses the coordinate descent method to compute the
951
+ Lasso solution (`linear_model.Lasso`). Lars will be faster if
952
+ the estimated components are sparse.
953
+
954
+ n_jobs : int, default=None
955
+ Number of parallel jobs to run.
956
+ ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
957
+ ``-1`` means using all processors. See :term:`Glossary <n_jobs>`
958
+ for more details.
959
+
960
+ dict_init : ndarray of shape (n_components, n_features), default=None
961
+ Initial value for the dictionary for warm restart scenarios. Only used
962
+ if `code_init` and `dict_init` are not None.
963
+
964
+ code_init : ndarray of shape (n_samples, n_components), default=None
965
+ Initial value for the sparse code for warm restart scenarios. Only used
966
+ if `code_init` and `dict_init` are not None.
967
+
968
+ callback : callable, default=None
969
+ Callable that gets invoked every five iterations.
970
+
971
+ verbose : bool, default=False
972
+ To control the verbosity of the procedure.
973
+
974
+ random_state : int, RandomState instance or None, default=None
975
+ Used for randomly initializing the dictionary. Pass an int for
976
+ reproducible results across multiple function calls.
977
+ See :term:`Glossary <random_state>`.
978
+
979
+ return_n_iter : bool, default=False
980
+ Whether or not to return the number of iterations.
981
+
982
+ positive_dict : bool, default=False
983
+ Whether to enforce positivity when finding the dictionary.
984
+
985
+ .. versionadded:: 0.20
986
+
987
+ positive_code : bool, default=False
988
+ Whether to enforce positivity when finding the code.
989
+
990
+ .. versionadded:: 0.20
991
+
992
+ method_max_iter : int, default=1000
993
+ Maximum number of iterations to perform.
994
+
995
+ .. versionadded:: 0.22
996
+
997
+ Returns
998
+ -------
999
+ code : ndarray of shape (n_samples, n_components)
1000
+ The sparse code factor in the matrix factorization.
1001
+
1002
+ dictionary : ndarray of shape (n_components, n_features),
1003
+ The dictionary factor in the matrix factorization.
1004
+
1005
+ errors : array
1006
+ Vector of errors at each iteration.
1007
+
1008
+ n_iter : int
1009
+ Number of iterations run. Returned only if `return_n_iter` is
1010
+ set to True.
1011
+
1012
+ See Also
1013
+ --------
1014
+ dict_learning_online : Solve a dictionary learning matrix factorization
1015
+ problem online.
1016
+ DictionaryLearning : Find a dictionary that sparsely encodes data.
1017
+ MiniBatchDictionaryLearning : A faster, less accurate version
1018
+ of the dictionary learning algorithm.
1019
+ SparsePCA : Sparse Principal Components Analysis.
1020
+ MiniBatchSparsePCA : Mini-batch Sparse Principal Components Analysis.
1021
+
1022
+ Examples
1023
+ --------
1024
+ >>> import numpy as np
1025
+ >>> from sklearn.datasets import make_sparse_coded_signal
1026
+ >>> from sklearn.decomposition import dict_learning
1027
+ >>> X, _, _ = make_sparse_coded_signal(
1028
+ ... n_samples=30, n_components=15, n_features=20, n_nonzero_coefs=10,
1029
+ ... random_state=42,
1030
+ ... )
1031
+ >>> U, V, errors = dict_learning(X, n_components=15, alpha=0.1, random_state=42)
1032
+
1033
+ We can check the level of sparsity of `U`:
1034
+
1035
+ >>> np.mean(U == 0)
1036
+ np.float64(0.62)
1037
+
1038
+ We can compare the average squared euclidean norm of the reconstruction
1039
+ error of the sparse coded signal relative to the squared euclidean norm of
1040
+ the original signal:
1041
+
1042
+ >>> X_hat = U @ V
1043
+ >>> np.mean(np.sum((X_hat - X) ** 2, axis=1) / np.sum(X ** 2, axis=1))
1044
+ np.float64(0.0192)
1045
+ """
1046
+ estimator = DictionaryLearning(
1047
+ n_components=n_components,
1048
+ alpha=alpha,
1049
+ max_iter=max_iter,
1050
+ tol=tol,
1051
+ fit_algorithm=method,
1052
+ n_jobs=n_jobs,
1053
+ dict_init=dict_init,
1054
+ callback=callback,
1055
+ code_init=code_init,
1056
+ verbose=verbose,
1057
+ random_state=random_state,
1058
+ positive_code=positive_code,
1059
+ positive_dict=positive_dict,
1060
+ transform_max_iter=method_max_iter,
1061
+ ).set_output(transform="default")
1062
+ code = estimator.fit_transform(X)
1063
+ if return_n_iter:
1064
+ return (
1065
+ code,
1066
+ estimator.components_,
1067
+ estimator.error_,
1068
+ estimator.n_iter_,
1069
+ )
1070
+ return code, estimator.components_, estimator.error_
1071
+
1072
+
1073
+ class _BaseSparseCoding(ClassNamePrefixFeaturesOutMixin, TransformerMixin):
1074
+ """Base class from SparseCoder and DictionaryLearning algorithms."""
1075
+
1076
+ def __init__(
1077
+ self,
1078
+ transform_algorithm,
1079
+ transform_n_nonzero_coefs,
1080
+ transform_alpha,
1081
+ split_sign,
1082
+ n_jobs,
1083
+ positive_code,
1084
+ transform_max_iter,
1085
+ ):
1086
+ self.transform_algorithm = transform_algorithm
1087
+ self.transform_n_nonzero_coefs = transform_n_nonzero_coefs
1088
+ self.transform_alpha = transform_alpha
1089
+ self.transform_max_iter = transform_max_iter
1090
+ self.split_sign = split_sign
1091
+ self.n_jobs = n_jobs
1092
+ self.positive_code = positive_code
1093
+
1094
+ def _transform(self, X, dictionary):
1095
+ """Private method allowing to accommodate both DictionaryLearning and
1096
+ SparseCoder."""
1097
+ X = validate_data(self, X, reset=False)
1098
+
1099
+ if hasattr(self, "alpha") and self.transform_alpha is None:
1100
+ transform_alpha = self.alpha
1101
+ else:
1102
+ transform_alpha = self.transform_alpha
1103
+
1104
+ code = sparse_encode(
1105
+ X,
1106
+ dictionary,
1107
+ algorithm=self.transform_algorithm,
1108
+ n_nonzero_coefs=self.transform_n_nonzero_coefs,
1109
+ alpha=transform_alpha,
1110
+ max_iter=self.transform_max_iter,
1111
+ n_jobs=self.n_jobs,
1112
+ positive=self.positive_code,
1113
+ )
1114
+
1115
+ if self.split_sign:
1116
+ # feature vector is split into a positive and negative side
1117
+ n_samples, n_features = code.shape
1118
+ split_code = np.empty((n_samples, 2 * n_features))
1119
+ split_code[:, :n_features] = np.maximum(code, 0)
1120
+ split_code[:, n_features:] = -np.minimum(code, 0)
1121
+ code = split_code
1122
+
1123
+ return code
1124
+
1125
+ def transform(self, X):
1126
+ """Encode the data as a sparse combination of the dictionary atoms.
1127
+
1128
+ Coding method is determined by the object parameter
1129
+ `transform_algorithm`.
1130
+
1131
+ Parameters
1132
+ ----------
1133
+ X : ndarray of shape (n_samples, n_features)
1134
+ Test data to be transformed, must have the same number of
1135
+ features as the data used to train the model.
1136
+
1137
+ Returns
1138
+ -------
1139
+ X_new : ndarray of shape (n_samples, n_components)
1140
+ Transformed data.
1141
+ """
1142
+ check_is_fitted(self)
1143
+ return self._transform(X, self.components_)
1144
+
1145
+ def _inverse_transform(self, code, dictionary):
1146
+ """Private method allowing to accommodate both DictionaryLearning and
1147
+ SparseCoder."""
1148
+ code = check_array(code)
1149
+ # compute number of expected features in code
1150
+ expected_n_components = dictionary.shape[0]
1151
+ if self.split_sign:
1152
+ expected_n_components += expected_n_components
1153
+ if not code.shape[1] == expected_n_components:
1154
+ raise ValueError(
1155
+ "The number of components in the code is different from the "
1156
+ "number of components in the dictionary."
1157
+ f"Expected {expected_n_components}, got {code.shape[1]}."
1158
+ )
1159
+ if self.split_sign:
1160
+ n_samples, n_features = code.shape
1161
+ n_features //= 2
1162
+ code = code[:, :n_features] - code[:, n_features:]
1163
+
1164
+ return code @ dictionary
1165
+
1166
+ def inverse_transform(self, X):
1167
+ """Transform data back to its original space.
1168
+
1169
+ Parameters
1170
+ ----------
1171
+ X : array-like of shape (n_samples, n_components)
1172
+ Data to be transformed back. Must have the same number of
1173
+ components as the data used to train the model.
1174
+
1175
+ Returns
1176
+ -------
1177
+ X_original : ndarray of shape (n_samples, n_features)
1178
+ Transformed data.
1179
+ """
1180
+ check_is_fitted(self)
1181
+ return self._inverse_transform(X, self.components_)
1182
+
1183
+
1184
+ class SparseCoder(_BaseSparseCoding, BaseEstimator):
1185
+ """Sparse coding.
1186
+
1187
+ Finds a sparse representation of data against a fixed, precomputed
1188
+ dictionary.
1189
+
1190
+ Each row of the result is the solution to a sparse coding problem.
1191
+ The goal is to find a sparse array `code` such that::
1192
+
1193
+ X ~= code * dictionary
1194
+
1195
+ Read more in the :ref:`User Guide <SparseCoder>`.
1196
+
1197
+ Parameters
1198
+ ----------
1199
+ dictionary : ndarray of shape (n_components, n_features)
1200
+ The dictionary atoms used for sparse coding. Lines are assumed to be
1201
+ normalized to unit norm.
1202
+
1203
+ transform_algorithm : {'lasso_lars', 'lasso_cd', 'lars', 'omp', \
1204
+ 'threshold'}, default='omp'
1205
+ Algorithm used to transform the data:
1206
+
1207
+ - `'lars'`: uses the least angle regression method
1208
+ (`linear_model.lars_path`);
1209
+ - `'lasso_lars'`: uses Lars to compute the Lasso solution;
1210
+ - `'lasso_cd'`: uses the coordinate descent method to compute the
1211
+ Lasso solution (linear_model.Lasso). `'lasso_lars'` will be faster if
1212
+ the estimated components are sparse;
1213
+ - `'omp'`: uses orthogonal matching pursuit to estimate the sparse
1214
+ solution;
1215
+ - `'threshold'`: squashes to zero all coefficients less than alpha from
1216
+ the projection ``dictionary * X'``.
1217
+
1218
+ transform_n_nonzero_coefs : int, default=None
1219
+ Number of nonzero coefficients to target in each column of the
1220
+ solution. This is only used by `algorithm='lars'` and `algorithm='omp'`
1221
+ and is overridden by `alpha` in the `omp` case. If `None`, then
1222
+ `transform_n_nonzero_coefs=int(n_features / 10)`.
1223
+
1224
+ transform_alpha : float, default=None
1225
+ If `algorithm='lasso_lars'` or `algorithm='lasso_cd'`, `alpha` is the
1226
+ penalty applied to the L1 norm.
1227
+ If `algorithm='threshold'`, `alpha` is the absolute value of the
1228
+ threshold below which coefficients will be squashed to zero.
1229
+ If `algorithm='omp'`, `alpha` is the tolerance parameter: the value of
1230
+ the reconstruction error targeted. In this case, it overrides
1231
+ `n_nonzero_coefs`.
1232
+ If `None`, default to 1.
1233
+
1234
+ split_sign : bool, default=False
1235
+ Whether to split the sparse feature vector into the concatenation of
1236
+ its negative part and its positive part. This can improve the
1237
+ performance of downstream classifiers.
1238
+
1239
+ n_jobs : int, default=None
1240
+ Number of parallel jobs to run.
1241
+ ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
1242
+ ``-1`` means using all processors. See :term:`Glossary <n_jobs>`
1243
+ for more details.
1244
+
1245
+ positive_code : bool, default=False
1246
+ Whether to enforce positivity when finding the code.
1247
+
1248
+ .. versionadded:: 0.20
1249
+
1250
+ transform_max_iter : int, default=1000
1251
+ Maximum number of iterations to perform if `algorithm='lasso_cd'` or
1252
+ `lasso_lars`.
1253
+
1254
+ .. versionadded:: 0.22
1255
+
1256
+ Attributes
1257
+ ----------
1258
+ n_components_ : int
1259
+ Number of atoms.
1260
+
1261
+ n_features_in_ : int
1262
+ Number of features seen during :term:`fit`.
1263
+
1264
+ .. versionadded:: 0.24
1265
+
1266
+ feature_names_in_ : ndarray of shape (`n_features_in_`,)
1267
+ Names of features seen during :term:`fit`. Defined only when `X`
1268
+ has feature names that are all strings.
1269
+
1270
+ .. versionadded:: 1.0
1271
+
1272
+ See Also
1273
+ --------
1274
+ DictionaryLearning : Find a dictionary that sparsely encodes data.
1275
+ MiniBatchDictionaryLearning : A faster, less accurate, version of the
1276
+ dictionary learning algorithm.
1277
+ MiniBatchSparsePCA : Mini-batch Sparse Principal Components Analysis.
1278
+ SparsePCA : Sparse Principal Components Analysis.
1279
+ sparse_encode : Sparse coding where each row of the result is the solution
1280
+ to a sparse coding problem.
1281
+
1282
+ Examples
1283
+ --------
1284
+ >>> import numpy as np
1285
+ >>> from sklearn.decomposition import SparseCoder
1286
+ >>> X = np.array([[-1, -1, -1], [0, 0, 3]])
1287
+ >>> dictionary = np.array(
1288
+ ... [[0, 1, 0],
1289
+ ... [-1, -1, 2],
1290
+ ... [1, 1, 1],
1291
+ ... [0, 1, 1],
1292
+ ... [0, 2, 1]],
1293
+ ... dtype=np.float64
1294
+ ... )
1295
+ >>> coder = SparseCoder(
1296
+ ... dictionary=dictionary, transform_algorithm='lasso_lars',
1297
+ ... transform_alpha=1e-10,
1298
+ ... )
1299
+ >>> coder.transform(X)
1300
+ array([[ 0., 0., -1., 0., 0.],
1301
+ [ 0., 1., 1., 0., 0.]])
1302
+ """
1303
+
1304
+ def __init__(
1305
+ self,
1306
+ dictionary,
1307
+ *,
1308
+ transform_algorithm="omp",
1309
+ transform_n_nonzero_coefs=None,
1310
+ transform_alpha=None,
1311
+ split_sign=False,
1312
+ n_jobs=None,
1313
+ positive_code=False,
1314
+ transform_max_iter=1000,
1315
+ ):
1316
+ super().__init__(
1317
+ transform_algorithm,
1318
+ transform_n_nonzero_coefs,
1319
+ transform_alpha,
1320
+ split_sign,
1321
+ n_jobs,
1322
+ positive_code,
1323
+ transform_max_iter,
1324
+ )
1325
+ self.dictionary = dictionary
1326
+
1327
+ def fit(self, X, y=None):
1328
+ """Do nothing and return the estimator unchanged.
1329
+
1330
+ This method is just there to implement the usual API and hence
1331
+ work in pipelines.
1332
+
1333
+ Parameters
1334
+ ----------
1335
+ X : Ignored
1336
+ Not used, present for API consistency by convention.
1337
+
1338
+ y : Ignored
1339
+ Not used, present for API consistency by convention.
1340
+
1341
+ Returns
1342
+ -------
1343
+ self : object
1344
+ Returns the instance itself.
1345
+ """
1346
+ return self
1347
+
1348
+ def transform(self, X, y=None):
1349
+ """Encode the data as a sparse combination of the dictionary atoms.
1350
+
1351
+ Coding method is determined by the object parameter
1352
+ `transform_algorithm`.
1353
+
1354
+ Parameters
1355
+ ----------
1356
+ X : ndarray of shape (n_samples, n_features)
1357
+ Training vector, where `n_samples` is the number of samples
1358
+ and `n_features` is the number of features.
1359
+
1360
+ y : Ignored
1361
+ Not used, present for API consistency by convention.
1362
+
1363
+ Returns
1364
+ -------
1365
+ X_new : ndarray of shape (n_samples, n_components)
1366
+ Transformed data.
1367
+ """
1368
+ return super()._transform(X, self.dictionary)
1369
+
1370
+ def inverse_transform(self, X):
1371
+ """Transform data back to its original space.
1372
+
1373
+ Parameters
1374
+ ----------
1375
+ X : array-like of shape (n_samples, n_components)
1376
+ Data to be transformed back. Must have the same number of
1377
+ components as the data used to train the model.
1378
+
1379
+ Returns
1380
+ -------
1381
+ X_original : ndarray of shape (n_samples, n_features)
1382
+ Transformed data.
1383
+ """
1384
+ return self._inverse_transform(X, self.dictionary)
1385
+
1386
+ def __sklearn_tags__(self):
1387
+ tags = super().__sklearn_tags__()
1388
+ tags.requires_fit = False
1389
+ tags.transformer_tags.preserves_dtype = ["float64", "float32"]
1390
+ return tags
1391
+
1392
+ @property
1393
+ def n_components_(self):
1394
+ """Number of atoms."""
1395
+ return self.dictionary.shape[0]
1396
+
1397
+ @property
1398
+ def n_features_in_(self):
1399
+ """Number of features seen during `fit`."""
1400
+ return self.dictionary.shape[1]
1401
+
1402
+ @property
1403
+ def _n_features_out(self):
1404
+ """Number of transformed output features."""
1405
+ return self.n_components_
1406
+
1407
+
1408
+ class DictionaryLearning(_BaseSparseCoding, BaseEstimator):
1409
+ """Dictionary learning.
1410
+
1411
+ Finds a dictionary (a set of atoms) that performs well at sparsely
1412
+ encoding the fitted data.
1413
+
1414
+ Solves the optimization problem::
1415
+
1416
+ (U^*,V^*) = argmin 0.5 || X - U V ||_Fro^2 + alpha * || U ||_1,1
1417
+ (U,V)
1418
+ with || V_k ||_2 <= 1 for all 0 <= k < n_components
1419
+
1420
+ ||.||_Fro stands for the Frobenius norm and ||.||_1,1 stands for
1421
+ the entry-wise matrix norm which is the sum of the absolute values
1422
+ of all the entries in the matrix.
1423
+
1424
+ Read more in the :ref:`User Guide <DictionaryLearning>`.
1425
+
1426
+ Parameters
1427
+ ----------
1428
+ n_components : int, default=None
1429
+ Number of dictionary elements to extract. If None, then ``n_components``
1430
+ is set to ``n_features``.
1431
+
1432
+ alpha : float, default=1.0
1433
+ Sparsity controlling parameter.
1434
+
1435
+ max_iter : int, default=1000
1436
+ Maximum number of iterations to perform.
1437
+
1438
+ tol : float, default=1e-8
1439
+ Tolerance for numerical error.
1440
+
1441
+ fit_algorithm : {'lars', 'cd'}, default='lars'
1442
+ * `'lars'`: uses the least angle regression method to solve the lasso
1443
+ problem (:func:`~sklearn.linear_model.lars_path`);
1444
+ * `'cd'`: uses the coordinate descent method to compute the
1445
+ Lasso solution (:class:`~sklearn.linear_model.Lasso`). Lars will be
1446
+ faster if the estimated components are sparse.
1447
+
1448
+ .. versionadded:: 0.17
1449
+ *cd* coordinate descent method to improve speed.
1450
+
1451
+ transform_algorithm : {'lasso_lars', 'lasso_cd', 'lars', 'omp', \
1452
+ 'threshold'}, default='omp'
1453
+ Algorithm used to transform the data:
1454
+
1455
+ - `'lars'`: uses the least angle regression method
1456
+ (:func:`~sklearn.linear_model.lars_path`);
1457
+ - `'lasso_lars'`: uses Lars to compute the Lasso solution.
1458
+ - `'lasso_cd'`: uses the coordinate descent method to compute the
1459
+ Lasso solution (:class:`~sklearn.linear_model.Lasso`). `'lasso_lars'`
1460
+ will be faster if the estimated components are sparse.
1461
+ - `'omp'`: uses orthogonal matching pursuit to estimate the sparse
1462
+ solution.
1463
+ - `'threshold'`: squashes to zero all coefficients less than alpha from
1464
+ the projection ``dictionary * X'``.
1465
+
1466
+ .. versionadded:: 0.17
1467
+ *lasso_cd* coordinate descent method to improve speed.
1468
+
1469
+ transform_n_nonzero_coefs : int, default=None
1470
+ Number of nonzero coefficients to target in each column of the
1471
+ solution. This is only used by `algorithm='lars'` and
1472
+ `algorithm='omp'`. If `None`, then
1473
+ `transform_n_nonzero_coefs=int(n_features / 10)`.
1474
+
1475
+ transform_alpha : float, default=None
1476
+ If `algorithm='lasso_lars'` or `algorithm='lasso_cd'`, `alpha` is the
1477
+ penalty applied to the L1 norm.
1478
+ If `algorithm='threshold'`, `alpha` is the absolute value of the
1479
+ threshold below which coefficients will be squashed to zero.
1480
+ If `None`, defaults to `alpha`.
1481
+
1482
+ .. versionchanged:: 1.2
1483
+ When None, default value changed from 1.0 to `alpha`.
1484
+
1485
+ n_jobs : int or None, default=None
1486
+ Number of parallel jobs to run.
1487
+ ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
1488
+ ``-1`` means using all processors. See :term:`Glossary <n_jobs>`
1489
+ for more details.
1490
+
1491
+ code_init : ndarray of shape (n_samples, n_components), default=None
1492
+ Initial value for the code, for warm restart. Only used if `code_init`
1493
+ and `dict_init` are not None.
1494
+
1495
+ dict_init : ndarray of shape (n_components, n_features), default=None
1496
+ Initial values for the dictionary, for warm restart. Only used if
1497
+ `code_init` and `dict_init` are not None.
1498
+
1499
+ callback : callable, default=None
1500
+ Callable that gets invoked every five iterations.
1501
+
1502
+ .. versionadded:: 1.3
1503
+
1504
+ verbose : bool, default=False
1505
+ To control the verbosity of the procedure.
1506
+
1507
+ split_sign : bool, default=False
1508
+ Whether to split the sparse feature vector into the concatenation of
1509
+ its negative part and its positive part. This can improve the
1510
+ performance of downstream classifiers.
1511
+
1512
+ random_state : int, RandomState instance or None, default=None
1513
+ Used for initializing the dictionary when ``dict_init`` is not
1514
+ specified, randomly shuffling the data when ``shuffle`` is set to
1515
+ ``True``, and updating the dictionary. Pass an int for reproducible
1516
+ results across multiple function calls.
1517
+ See :term:`Glossary <random_state>`.
1518
+
1519
+ positive_code : bool, default=False
1520
+ Whether to enforce positivity when finding the code.
1521
+
1522
+ .. versionadded:: 0.20
1523
+
1524
+ positive_dict : bool, default=False
1525
+ Whether to enforce positivity when finding the dictionary.
1526
+
1527
+ .. versionadded:: 0.20
1528
+
1529
+ transform_max_iter : int, default=1000
1530
+ Maximum number of iterations to perform if `algorithm='lasso_cd'` or
1531
+ `'lasso_lars'`.
1532
+
1533
+ .. versionadded:: 0.22
1534
+
1535
+ Attributes
1536
+ ----------
1537
+ components_ : ndarray of shape (n_components, n_features)
1538
+ dictionary atoms extracted from the data
1539
+
1540
+ error_ : array
1541
+ vector of errors at each iteration
1542
+
1543
+ n_features_in_ : int
1544
+ Number of features seen during :term:`fit`.
1545
+
1546
+ .. versionadded:: 0.24
1547
+
1548
+ feature_names_in_ : ndarray of shape (`n_features_in_`,)
1549
+ Names of features seen during :term:`fit`. Defined only when `X`
1550
+ has feature names that are all strings.
1551
+
1552
+ .. versionadded:: 1.0
1553
+
1554
+ n_iter_ : int
1555
+ Number of iterations run.
1556
+
1557
+ See Also
1558
+ --------
1559
+ MiniBatchDictionaryLearning: A faster, less accurate, version of the
1560
+ dictionary learning algorithm.
1561
+ MiniBatchSparsePCA : Mini-batch Sparse Principal Components Analysis.
1562
+ SparseCoder : Find a sparse representation of data from a fixed,
1563
+ precomputed dictionary.
1564
+ SparsePCA : Sparse Principal Components Analysis.
1565
+
1566
+ References
1567
+ ----------
1568
+
1569
+ J. Mairal, F. Bach, J. Ponce, G. Sapiro, 2009: Online dictionary learning
1570
+ for sparse coding (https://www.di.ens.fr/~fbach/mairal_icml09.pdf)
1571
+
1572
+ Examples
1573
+ --------
1574
+ >>> import numpy as np
1575
+ >>> from sklearn.datasets import make_sparse_coded_signal
1576
+ >>> from sklearn.decomposition import DictionaryLearning
1577
+ >>> X, dictionary, code = make_sparse_coded_signal(
1578
+ ... n_samples=30, n_components=15, n_features=20, n_nonzero_coefs=10,
1579
+ ... random_state=42,
1580
+ ... )
1581
+ >>> dict_learner = DictionaryLearning(
1582
+ ... n_components=15, transform_algorithm='lasso_lars', transform_alpha=0.1,
1583
+ ... random_state=42,
1584
+ ... )
1585
+ >>> X_transformed = dict_learner.fit(X).transform(X)
1586
+
1587
+ We can check the level of sparsity of `X_transformed`:
1588
+
1589
+ >>> np.mean(X_transformed == 0)
1590
+ np.float64(0.527)
1591
+
1592
+ We can compare the average squared euclidean norm of the reconstruction
1593
+ error of the sparse coded signal relative to the squared euclidean norm of
1594
+ the original signal:
1595
+
1596
+ >>> X_hat = X_transformed @ dict_learner.components_
1597
+ >>> np.mean(np.sum((X_hat - X) ** 2, axis=1) / np.sum(X ** 2, axis=1))
1598
+ np.float64(0.056)
1599
+ """
1600
+
1601
+ _parameter_constraints: dict = {
1602
+ "n_components": [Interval(Integral, 1, None, closed="left"), None],
1603
+ "alpha": [Interval(Real, 0, None, closed="left")],
1604
+ "max_iter": [Interval(Integral, 0, None, closed="left")],
1605
+ "tol": [Interval(Real, 0, None, closed="left")],
1606
+ "fit_algorithm": [StrOptions({"lars", "cd"})],
1607
+ "transform_algorithm": [
1608
+ StrOptions({"lasso_lars", "lasso_cd", "lars", "omp", "threshold"})
1609
+ ],
1610
+ "transform_n_nonzero_coefs": [Interval(Integral, 1, None, closed="left"), None],
1611
+ "transform_alpha": [Interval(Real, 0, None, closed="left"), None],
1612
+ "n_jobs": [Integral, None],
1613
+ "code_init": [np.ndarray, None],
1614
+ "dict_init": [np.ndarray, None],
1615
+ "callback": [callable, None],
1616
+ "verbose": ["verbose"],
1617
+ "split_sign": ["boolean"],
1618
+ "random_state": ["random_state"],
1619
+ "positive_code": ["boolean"],
1620
+ "positive_dict": ["boolean"],
1621
+ "transform_max_iter": [Interval(Integral, 0, None, closed="left")],
1622
+ }
1623
+
1624
+ def __init__(
1625
+ self,
1626
+ n_components=None,
1627
+ *,
1628
+ alpha=1,
1629
+ max_iter=1000,
1630
+ tol=1e-8,
1631
+ fit_algorithm="lars",
1632
+ transform_algorithm="omp",
1633
+ transform_n_nonzero_coefs=None,
1634
+ transform_alpha=None,
1635
+ n_jobs=None,
1636
+ code_init=None,
1637
+ dict_init=None,
1638
+ callback=None,
1639
+ verbose=False,
1640
+ split_sign=False,
1641
+ random_state=None,
1642
+ positive_code=False,
1643
+ positive_dict=False,
1644
+ transform_max_iter=1000,
1645
+ ):
1646
+ super().__init__(
1647
+ transform_algorithm,
1648
+ transform_n_nonzero_coefs,
1649
+ transform_alpha,
1650
+ split_sign,
1651
+ n_jobs,
1652
+ positive_code,
1653
+ transform_max_iter,
1654
+ )
1655
+ self.n_components = n_components
1656
+ self.alpha = alpha
1657
+ self.max_iter = max_iter
1658
+ self.tol = tol
1659
+ self.fit_algorithm = fit_algorithm
1660
+ self.code_init = code_init
1661
+ self.dict_init = dict_init
1662
+ self.callback = callback
1663
+ self.verbose = verbose
1664
+ self.random_state = random_state
1665
+ self.positive_dict = positive_dict
1666
+
1667
+ def fit(self, X, y=None):
1668
+ """Fit the model from data in X.
1669
+
1670
+ Parameters
1671
+ ----------
1672
+ X : array-like of shape (n_samples, n_features)
1673
+ Training vector, where `n_samples` is the number of samples
1674
+ and `n_features` is the number of features.
1675
+
1676
+ y : Ignored
1677
+ Not used, present for API consistency by convention.
1678
+
1679
+ Returns
1680
+ -------
1681
+ self : object
1682
+ Returns the instance itself.
1683
+ """
1684
+ self.fit_transform(X)
1685
+ return self
1686
+
1687
+ @_fit_context(prefer_skip_nested_validation=True)
1688
+ def fit_transform(self, X, y=None):
1689
+ """Fit the model from data in X and return the transformed data.
1690
+
1691
+ Parameters
1692
+ ----------
1693
+ X : array-like of shape (n_samples, n_features)
1694
+ Training vector, where `n_samples` is the number of samples
1695
+ and `n_features` is the number of features.
1696
+
1697
+ y : Ignored
1698
+ Not used, present for API consistency by convention.
1699
+
1700
+ Returns
1701
+ -------
1702
+ V : ndarray of shape (n_samples, n_components)
1703
+ Transformed data.
1704
+ """
1705
+ _check_positive_coding(method=self.fit_algorithm, positive=self.positive_code)
1706
+
1707
+ method = "lasso_" + self.fit_algorithm
1708
+
1709
+ random_state = check_random_state(self.random_state)
1710
+ X = validate_data(self, X)
1711
+
1712
+ if self.n_components is None:
1713
+ n_components = X.shape[1]
1714
+ else:
1715
+ n_components = self.n_components
1716
+
1717
+ V, U, E, self.n_iter_ = _dict_learning(
1718
+ X,
1719
+ n_components,
1720
+ alpha=self.alpha,
1721
+ tol=self.tol,
1722
+ max_iter=self.max_iter,
1723
+ method=method,
1724
+ method_max_iter=self.transform_max_iter,
1725
+ n_jobs=self.n_jobs,
1726
+ code_init=self.code_init,
1727
+ dict_init=self.dict_init,
1728
+ callback=self.callback,
1729
+ verbose=self.verbose,
1730
+ random_state=random_state,
1731
+ return_n_iter=True,
1732
+ positive_dict=self.positive_dict,
1733
+ positive_code=self.positive_code,
1734
+ )
1735
+ self.components_ = U
1736
+ self.error_ = E
1737
+
1738
+ return V
1739
+
1740
+ @property
1741
+ def _n_features_out(self):
1742
+ """Number of transformed output features."""
1743
+ return self.components_.shape[0]
1744
+
1745
+ def __sklearn_tags__(self):
1746
+ tags = super().__sklearn_tags__()
1747
+ tags.transformer_tags.preserves_dtype = ["float64", "float32"]
1748
+ return tags
1749
+
1750
+
1751
+ class MiniBatchDictionaryLearning(_BaseSparseCoding, BaseEstimator):
1752
+ """Mini-batch dictionary learning.
1753
+
1754
+ Finds a dictionary (a set of atoms) that performs well at sparsely
1755
+ encoding the fitted data.
1756
+
1757
+ Solves the optimization problem::
1758
+
1759
+ (U^*,V^*) = argmin 0.5 || X - U V ||_Fro^2 + alpha * || U ||_1,1
1760
+ (U,V)
1761
+ with || V_k ||_2 <= 1 for all 0 <= k < n_components
1762
+
1763
+ ||.||_Fro stands for the Frobenius norm and ||.||_1,1 stands for
1764
+ the entry-wise matrix norm which is the sum of the absolute values
1765
+ of all the entries in the matrix.
1766
+
1767
+ Read more in the :ref:`User Guide <DictionaryLearning>`.
1768
+
1769
+ Parameters
1770
+ ----------
1771
+ n_components : int, default=None
1772
+ Number of dictionary elements to extract.
1773
+
1774
+ alpha : float, default=1
1775
+ Sparsity controlling parameter.
1776
+
1777
+ max_iter : int, default=1_000
1778
+ Maximum number of iterations over the complete dataset before
1779
+ stopping independently of any early stopping criterion heuristics.
1780
+
1781
+ .. versionadded:: 1.1
1782
+
1783
+ fit_algorithm : {'lars', 'cd'}, default='lars'
1784
+ The algorithm used:
1785
+
1786
+ - `'lars'`: uses the least angle regression method to solve the lasso
1787
+ problem (`linear_model.lars_path`)
1788
+ - `'cd'`: uses the coordinate descent method to compute the
1789
+ Lasso solution (`linear_model.Lasso`). Lars will be faster if
1790
+ the estimated components are sparse.
1791
+
1792
+ n_jobs : int, default=None
1793
+ Number of parallel jobs to run.
1794
+ ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
1795
+ ``-1`` means using all processors. See :term:`Glossary <n_jobs>`
1796
+ for more details.
1797
+
1798
+ batch_size : int, default=256
1799
+ Number of samples in each mini-batch.
1800
+
1801
+ .. versionchanged:: 1.3
1802
+ The default value of `batch_size` changed from 3 to 256 in version 1.3.
1803
+
1804
+ shuffle : bool, default=True
1805
+ Whether to shuffle the samples before forming batches.
1806
+
1807
+ dict_init : ndarray of shape (n_components, n_features), default=None
1808
+ Initial value of the dictionary for warm restart scenarios.
1809
+
1810
+ transform_algorithm : {'lasso_lars', 'lasso_cd', 'lars', 'omp', \
1811
+ 'threshold'}, default='omp'
1812
+ Algorithm used to transform the data:
1813
+
1814
+ - `'lars'`: uses the least angle regression method
1815
+ (`linear_model.lars_path`);
1816
+ - `'lasso_lars'`: uses Lars to compute the Lasso solution.
1817
+ - `'lasso_cd'`: uses the coordinate descent method to compute the
1818
+ Lasso solution (`linear_model.Lasso`). `'lasso_lars'` will be faster
1819
+ if the estimated components are sparse.
1820
+ - `'omp'`: uses orthogonal matching pursuit to estimate the sparse
1821
+ solution.
1822
+ - `'threshold'`: squashes to zero all coefficients less than alpha from
1823
+ the projection ``dictionary * X'``.
1824
+
1825
+ transform_n_nonzero_coefs : int, default=None
1826
+ Number of nonzero coefficients to target in each column of the
1827
+ solution. This is only used by `algorithm='lars'` and
1828
+ `algorithm='omp'`. If `None`, then
1829
+ `transform_n_nonzero_coefs=int(n_features / 10)`.
1830
+
1831
+ transform_alpha : float, default=None
1832
+ If `algorithm='lasso_lars'` or `algorithm='lasso_cd'`, `alpha` is the
1833
+ penalty applied to the L1 norm.
1834
+ If `algorithm='threshold'`, `alpha` is the absolute value of the
1835
+ threshold below which coefficients will be squashed to zero.
1836
+ If `None`, defaults to `alpha`.
1837
+
1838
+ .. versionchanged:: 1.2
1839
+ When None, default value changed from 1.0 to `alpha`.
1840
+
1841
+ verbose : bool or int, default=False
1842
+ To control the verbosity of the procedure.
1843
+
1844
+ split_sign : bool, default=False
1845
+ Whether to split the sparse feature vector into the concatenation of
1846
+ its negative part and its positive part. This can improve the
1847
+ performance of downstream classifiers.
1848
+
1849
+ random_state : int, RandomState instance or None, default=None
1850
+ Used for initializing the dictionary when ``dict_init`` is not
1851
+ specified, randomly shuffling the data when ``shuffle`` is set to
1852
+ ``True``, and updating the dictionary. Pass an int for reproducible
1853
+ results across multiple function calls.
1854
+ See :term:`Glossary <random_state>`.
1855
+
1856
+ positive_code : bool, default=False
1857
+ Whether to enforce positivity when finding the code.
1858
+
1859
+ .. versionadded:: 0.20
1860
+
1861
+ positive_dict : bool, default=False
1862
+ Whether to enforce positivity when finding the dictionary.
1863
+
1864
+ .. versionadded:: 0.20
1865
+
1866
+ transform_max_iter : int, default=1000
1867
+ Maximum number of iterations to perform if `algorithm='lasso_cd'` or
1868
+ `'lasso_lars'`.
1869
+
1870
+ .. versionadded:: 0.22
1871
+
1872
+ callback : callable, default=None
1873
+ A callable that gets invoked at the end of each iteration.
1874
+
1875
+ .. versionadded:: 1.1
1876
+
1877
+ tol : float, default=1e-3
1878
+ Control early stopping based on the norm of the differences in the
1879
+ dictionary between 2 steps.
1880
+
1881
+ To disable early stopping based on changes in the dictionary, set
1882
+ `tol` to 0.0.
1883
+
1884
+ .. versionadded:: 1.1
1885
+
1886
+ max_no_improvement : int, default=10
1887
+ Control early stopping based on the consecutive number of mini batches
1888
+ that does not yield an improvement on the smoothed cost function.
1889
+
1890
+ To disable convergence detection based on cost function, set
1891
+ `max_no_improvement` to None.
1892
+
1893
+ .. versionadded:: 1.1
1894
+
1895
+ Attributes
1896
+ ----------
1897
+ components_ : ndarray of shape (n_components, n_features)
1898
+ Components extracted from the data.
1899
+
1900
+ n_features_in_ : int
1901
+ Number of features seen during :term:`fit`.
1902
+
1903
+ .. versionadded:: 0.24
1904
+
1905
+ feature_names_in_ : ndarray of shape (`n_features_in_`,)
1906
+ Names of features seen during :term:`fit`. Defined only when `X`
1907
+ has feature names that are all strings.
1908
+
1909
+ .. versionadded:: 1.0
1910
+
1911
+ n_iter_ : int
1912
+ Number of iterations over the full dataset.
1913
+
1914
+ n_steps_ : int
1915
+ Number of mini-batches processed.
1916
+
1917
+ .. versionadded:: 1.1
1918
+
1919
+ See Also
1920
+ --------
1921
+ DictionaryLearning : Find a dictionary that sparsely encodes data.
1922
+ MiniBatchSparsePCA : Mini-batch Sparse Principal Components Analysis.
1923
+ SparseCoder : Find a sparse representation of data from a fixed,
1924
+ precomputed dictionary.
1925
+ SparsePCA : Sparse Principal Components Analysis.
1926
+
1927
+ References
1928
+ ----------
1929
+
1930
+ J. Mairal, F. Bach, J. Ponce, G. Sapiro, 2009: Online dictionary learning
1931
+ for sparse coding (https://www.di.ens.fr/~fbach/mairal_icml09.pdf)
1932
+
1933
+ Examples
1934
+ --------
1935
+ >>> import numpy as np
1936
+ >>> from sklearn.datasets import make_sparse_coded_signal
1937
+ >>> from sklearn.decomposition import MiniBatchDictionaryLearning
1938
+ >>> X, dictionary, code = make_sparse_coded_signal(
1939
+ ... n_samples=30, n_components=15, n_features=20, n_nonzero_coefs=10,
1940
+ ... random_state=42)
1941
+ >>> dict_learner = MiniBatchDictionaryLearning(
1942
+ ... n_components=15, batch_size=3, transform_algorithm='lasso_lars',
1943
+ ... transform_alpha=0.1, max_iter=20, random_state=42)
1944
+ >>> X_transformed = dict_learner.fit_transform(X)
1945
+
1946
+ We can check the level of sparsity of `X_transformed`:
1947
+
1948
+ >>> np.mean(X_transformed == 0) > 0.5
1949
+ np.True_
1950
+
1951
+ We can compare the average squared euclidean norm of the reconstruction
1952
+ error of the sparse coded signal relative to the squared euclidean norm of
1953
+ the original signal:
1954
+
1955
+ >>> X_hat = X_transformed @ dict_learner.components_
1956
+ >>> np.mean(np.sum((X_hat - X) ** 2, axis=1) / np.sum(X ** 2, axis=1))
1957
+ np.float64(0.052)
1958
+ """
1959
+
1960
+ _parameter_constraints: dict = {
1961
+ "n_components": [Interval(Integral, 1, None, closed="left"), None],
1962
+ "alpha": [Interval(Real, 0, None, closed="left")],
1963
+ "max_iter": [Interval(Integral, 0, None, closed="left")],
1964
+ "fit_algorithm": [StrOptions({"cd", "lars"})],
1965
+ "n_jobs": [None, Integral],
1966
+ "batch_size": [Interval(Integral, 1, None, closed="left")],
1967
+ "shuffle": ["boolean"],
1968
+ "dict_init": [None, np.ndarray],
1969
+ "transform_algorithm": [
1970
+ StrOptions({"lasso_lars", "lasso_cd", "lars", "omp", "threshold"})
1971
+ ],
1972
+ "transform_n_nonzero_coefs": [Interval(Integral, 1, None, closed="left"), None],
1973
+ "transform_alpha": [Interval(Real, 0, None, closed="left"), None],
1974
+ "verbose": ["verbose"],
1975
+ "split_sign": ["boolean"],
1976
+ "random_state": ["random_state"],
1977
+ "positive_code": ["boolean"],
1978
+ "positive_dict": ["boolean"],
1979
+ "transform_max_iter": [Interval(Integral, 0, None, closed="left")],
1980
+ "callback": [None, callable],
1981
+ "tol": [Interval(Real, 0, None, closed="left")],
1982
+ "max_no_improvement": [Interval(Integral, 0, None, closed="left"), None],
1983
+ }
1984
+
1985
+ def __init__(
1986
+ self,
1987
+ n_components=None,
1988
+ *,
1989
+ alpha=1,
1990
+ max_iter=1_000,
1991
+ fit_algorithm="lars",
1992
+ n_jobs=None,
1993
+ batch_size=256,
1994
+ shuffle=True,
1995
+ dict_init=None,
1996
+ transform_algorithm="omp",
1997
+ transform_n_nonzero_coefs=None,
1998
+ transform_alpha=None,
1999
+ verbose=False,
2000
+ split_sign=False,
2001
+ random_state=None,
2002
+ positive_code=False,
2003
+ positive_dict=False,
2004
+ transform_max_iter=1000,
2005
+ callback=None,
2006
+ tol=1e-3,
2007
+ max_no_improvement=10,
2008
+ ):
2009
+ super().__init__(
2010
+ transform_algorithm,
2011
+ transform_n_nonzero_coefs,
2012
+ transform_alpha,
2013
+ split_sign,
2014
+ n_jobs,
2015
+ positive_code,
2016
+ transform_max_iter,
2017
+ )
2018
+ self.n_components = n_components
2019
+ self.alpha = alpha
2020
+ self.max_iter = max_iter
2021
+ self.fit_algorithm = fit_algorithm
2022
+ self.dict_init = dict_init
2023
+ self.verbose = verbose
2024
+ self.shuffle = shuffle
2025
+ self.batch_size = batch_size
2026
+ self.split_sign = split_sign
2027
+ self.random_state = random_state
2028
+ self.positive_dict = positive_dict
2029
+ self.callback = callback
2030
+ self.max_no_improvement = max_no_improvement
2031
+ self.tol = tol
2032
+
2033
+ def _check_params(self, X):
2034
+ # n_components
2035
+ self._n_components = self.n_components
2036
+ if self._n_components is None:
2037
+ self._n_components = X.shape[1]
2038
+
2039
+ # fit_algorithm
2040
+ _check_positive_coding(self.fit_algorithm, self.positive_code)
2041
+ self._fit_algorithm = "lasso_" + self.fit_algorithm
2042
+
2043
+ # batch_size
2044
+ self._batch_size = min(self.batch_size, X.shape[0])
2045
+
2046
+ def _initialize_dict(self, X, random_state):
2047
+ """Initialization of the dictionary."""
2048
+ if self.dict_init is not None:
2049
+ dictionary = self.dict_init
2050
+ else:
2051
+ # Init V with SVD of X
2052
+ _, S, dictionary = _randomized_svd(
2053
+ X, self._n_components, random_state=random_state
2054
+ )
2055
+ dictionary = S[:, np.newaxis] * dictionary
2056
+
2057
+ if self._n_components <= len(dictionary):
2058
+ dictionary = dictionary[: self._n_components, :]
2059
+ else:
2060
+ dictionary = np.concatenate(
2061
+ (
2062
+ dictionary,
2063
+ np.zeros(
2064
+ (self._n_components - len(dictionary), dictionary.shape[1]),
2065
+ dtype=dictionary.dtype,
2066
+ ),
2067
+ )
2068
+ )
2069
+
2070
+ dictionary = check_array(dictionary, order="F", dtype=X.dtype, copy=False)
2071
+ dictionary = np.require(dictionary, requirements="W")
2072
+
2073
+ return dictionary
2074
+
2075
+ def _update_inner_stats(self, X, code, batch_size, step):
2076
+ """Update the inner stats inplace."""
2077
+ if step < batch_size - 1:
2078
+ theta = (step + 1) * batch_size
2079
+ else:
2080
+ theta = batch_size**2 + step + 1 - batch_size
2081
+ beta = (theta + 1 - batch_size) / (theta + 1)
2082
+
2083
+ self._A *= beta
2084
+ self._A += code.T @ code / batch_size
2085
+ self._B *= beta
2086
+ self._B += X.T @ code / batch_size
2087
+
2088
+ def _minibatch_step(self, X, dictionary, random_state, step):
2089
+ """Perform the update on the dictionary for one minibatch."""
2090
+ batch_size = X.shape[0]
2091
+
2092
+ # Compute code for this batch
2093
+ code = _sparse_encode(
2094
+ X,
2095
+ dictionary,
2096
+ algorithm=self._fit_algorithm,
2097
+ alpha=self.alpha,
2098
+ n_jobs=self.n_jobs,
2099
+ positive=self.positive_code,
2100
+ max_iter=self.transform_max_iter,
2101
+ verbose=self.verbose,
2102
+ )
2103
+
2104
+ batch_cost = (
2105
+ 0.5 * ((X - code @ dictionary) ** 2).sum()
2106
+ + self.alpha * np.sum(np.abs(code))
2107
+ ) / batch_size
2108
+
2109
+ # Update inner stats
2110
+ self._update_inner_stats(X, code, batch_size, step)
2111
+
2112
+ # Update dictionary
2113
+ _update_dict(
2114
+ dictionary,
2115
+ X,
2116
+ code,
2117
+ self._A,
2118
+ self._B,
2119
+ verbose=self.verbose,
2120
+ random_state=random_state,
2121
+ positive=self.positive_dict,
2122
+ )
2123
+
2124
+ return batch_cost
2125
+
2126
+ def _check_convergence(
2127
+ self, X, batch_cost, new_dict, old_dict, n_samples, step, n_steps
2128
+ ):
2129
+ """Helper function to encapsulate the early stopping logic.
2130
+
2131
+ Early stopping is based on two factors:
2132
+ - A small change of the dictionary between two minibatch updates. This is
2133
+ controlled by the tol parameter.
2134
+ - No more improvement on a smoothed estimate of the objective function for a
2135
+ a certain number of consecutive minibatch updates. This is controlled by
2136
+ the max_no_improvement parameter.
2137
+ """
2138
+ batch_size = X.shape[0]
2139
+
2140
+ # counts steps starting from 1 for user friendly verbose mode.
2141
+ step = step + 1
2142
+
2143
+ # Ignore 100 first steps or 1 epoch to avoid initializing the ewa_cost with a
2144
+ # too bad value
2145
+ if step <= min(100, n_samples / batch_size):
2146
+ if self.verbose:
2147
+ print(f"Minibatch step {step}/{n_steps}: mean batch cost: {batch_cost}")
2148
+ return False
2149
+
2150
+ # Compute an Exponentially Weighted Average of the cost function to
2151
+ # monitor the convergence while discarding minibatch-local stochastic
2152
+ # variability: https://en.wikipedia.org/wiki/Moving_average
2153
+ if self._ewa_cost is None:
2154
+ self._ewa_cost = batch_cost
2155
+ else:
2156
+ alpha = batch_size / (n_samples + 1)
2157
+ alpha = min(alpha, 1)
2158
+ self._ewa_cost = self._ewa_cost * (1 - alpha) + batch_cost * alpha
2159
+
2160
+ if self.verbose:
2161
+ print(
2162
+ f"Minibatch step {step}/{n_steps}: mean batch cost: "
2163
+ f"{batch_cost}, ewa cost: {self._ewa_cost}"
2164
+ )
2165
+
2166
+ # Early stopping based on change of dictionary
2167
+ dict_diff = linalg.norm(new_dict - old_dict) / self._n_components
2168
+ if self.tol > 0 and dict_diff <= self.tol:
2169
+ if self.verbose:
2170
+ print(f"Converged (small dictionary change) at step {step}/{n_steps}")
2171
+ return True
2172
+
2173
+ # Early stopping heuristic due to lack of improvement on smoothed
2174
+ # cost function
2175
+ if self._ewa_cost_min is None or self._ewa_cost < self._ewa_cost_min:
2176
+ self._no_improvement = 0
2177
+ self._ewa_cost_min = self._ewa_cost
2178
+ else:
2179
+ self._no_improvement += 1
2180
+
2181
+ if (
2182
+ self.max_no_improvement is not None
2183
+ and self._no_improvement >= self.max_no_improvement
2184
+ ):
2185
+ if self.verbose:
2186
+ print(
2187
+ "Converged (lack of improvement in objective function) "
2188
+ f"at step {step}/{n_steps}"
2189
+ )
2190
+ return True
2191
+
2192
+ return False
2193
+
2194
+ @_fit_context(prefer_skip_nested_validation=True)
2195
+ def fit(self, X, y=None):
2196
+ """Fit the model from data in X.
2197
+
2198
+ Parameters
2199
+ ----------
2200
+ X : array-like of shape (n_samples, n_features)
2201
+ Training vector, where `n_samples` is the number of samples
2202
+ and `n_features` is the number of features.
2203
+
2204
+ y : Ignored
2205
+ Not used, present for API consistency by convention.
2206
+
2207
+ Returns
2208
+ -------
2209
+ self : object
2210
+ Returns the instance itself.
2211
+ """
2212
+ X = validate_data(
2213
+ self, X, dtype=[np.float64, np.float32], order="C", copy=False
2214
+ )
2215
+
2216
+ self._check_params(X)
2217
+ self._random_state = check_random_state(self.random_state)
2218
+
2219
+ dictionary = self._initialize_dict(X, self._random_state)
2220
+ old_dict = dictionary.copy()
2221
+
2222
+ if self.shuffle:
2223
+ X_train = X.copy()
2224
+ self._random_state.shuffle(X_train)
2225
+ else:
2226
+ X_train = X
2227
+
2228
+ n_samples, n_features = X_train.shape
2229
+
2230
+ if self.verbose:
2231
+ print("[dict_learning]")
2232
+
2233
+ # Inner stats
2234
+ self._A = np.zeros(
2235
+ (self._n_components, self._n_components), dtype=X_train.dtype
2236
+ )
2237
+ self._B = np.zeros((n_features, self._n_components), dtype=X_train.dtype)
2238
+
2239
+ # Attributes to monitor the convergence
2240
+ self._ewa_cost = None
2241
+ self._ewa_cost_min = None
2242
+ self._no_improvement = 0
2243
+
2244
+ batches = gen_batches(n_samples, self._batch_size)
2245
+ batches = itertools.cycle(batches)
2246
+ n_steps_per_iter = int(np.ceil(n_samples / self._batch_size))
2247
+ n_steps = self.max_iter * n_steps_per_iter
2248
+
2249
+ i = -1 # to allow max_iter = 0
2250
+
2251
+ for i, batch in zip(range(n_steps), batches):
2252
+ X_batch = X_train[batch]
2253
+
2254
+ batch_cost = self._minibatch_step(
2255
+ X_batch, dictionary, self._random_state, i
2256
+ )
2257
+
2258
+ if self._check_convergence(
2259
+ X_batch, batch_cost, dictionary, old_dict, n_samples, i, n_steps
2260
+ ):
2261
+ break
2262
+
2263
+ # XXX callback param added for backward compat in #18975 but a common
2264
+ # unified callback API should be preferred
2265
+ if self.callback is not None:
2266
+ self.callback(locals())
2267
+
2268
+ old_dict[:] = dictionary
2269
+
2270
+ self.n_steps_ = i + 1
2271
+ self.n_iter_ = np.ceil(self.n_steps_ / n_steps_per_iter)
2272
+ self.components_ = dictionary
2273
+
2274
+ return self
2275
+
2276
+ @_fit_context(prefer_skip_nested_validation=True)
2277
+ def partial_fit(self, X, y=None):
2278
+ """Update the model using the data in X as a mini-batch.
2279
+
2280
+ Parameters
2281
+ ----------
2282
+ X : array-like of shape (n_samples, n_features)
2283
+ Training vector, where `n_samples` is the number of samples
2284
+ and `n_features` is the number of features.
2285
+
2286
+ y : Ignored
2287
+ Not used, present for API consistency by convention.
2288
+
2289
+ Returns
2290
+ -------
2291
+ self : object
2292
+ Return the instance itself.
2293
+ """
2294
+ has_components = hasattr(self, "components_")
2295
+
2296
+ X = validate_data(
2297
+ self, X, dtype=[np.float64, np.float32], order="C", reset=not has_components
2298
+ )
2299
+
2300
+ if not has_components:
2301
+ # This instance has not been fitted yet (fit or partial_fit)
2302
+ self._check_params(X)
2303
+ self._random_state = check_random_state(self.random_state)
2304
+
2305
+ dictionary = self._initialize_dict(X, self._random_state)
2306
+
2307
+ self.n_steps_ = 0
2308
+
2309
+ self._A = np.zeros((self._n_components, self._n_components), dtype=X.dtype)
2310
+ self._B = np.zeros((X.shape[1], self._n_components), dtype=X.dtype)
2311
+ else:
2312
+ dictionary = self.components_
2313
+
2314
+ self._minibatch_step(X, dictionary, self._random_state, self.n_steps_)
2315
+
2316
+ self.components_ = dictionary
2317
+ self.n_steps_ += 1
2318
+
2319
+ return self
2320
+
2321
+ @property
2322
+ def _n_features_out(self):
2323
+ """Number of transformed output features."""
2324
+ return self.components_.shape[0]
2325
+
2326
+ def __sklearn_tags__(self):
2327
+ tags = super().__sklearn_tags__()
2328
+ tags.transformer_tags.preserves_dtype = ["float64", "float32"]
2329
+ return tags
miniconda3/envs/active_proaction/lib/python3.10/site-packages/sklearn/decomposition/_factor_analysis.py ADDED
@@ -0,0 +1,457 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Factor Analysis.
2
+
3
+ A latent linear variable model.
4
+
5
+ FactorAnalysis is similar to probabilistic PCA implemented by PCA.score
6
+ While PCA assumes Gaussian noise with the same variance for each
7
+ feature, the FactorAnalysis model assumes different variances for
8
+ each of them.
9
+
10
+ This implementation is based on David Barber's Book,
11
+ Bayesian Reasoning and Machine Learning,
12
+ http://www.cs.ucl.ac.uk/staff/d.barber/brml,
13
+ Algorithm 21.1
14
+ """
15
+
16
+ # Authors: The scikit-learn developers
17
+ # SPDX-License-Identifier: BSD-3-Clause
18
+
19
+ import warnings
20
+ from math import log, sqrt
21
+ from numbers import Integral, Real
22
+
23
+ import numpy as np
24
+ from scipy import linalg
25
+
26
+ from ..base import (
27
+ BaseEstimator,
28
+ ClassNamePrefixFeaturesOutMixin,
29
+ TransformerMixin,
30
+ _fit_context,
31
+ )
32
+ from ..exceptions import ConvergenceWarning
33
+ from ..utils import check_random_state
34
+ from ..utils._param_validation import Interval, StrOptions
35
+ from ..utils.extmath import _randomized_svd, fast_logdet, squared_norm
36
+ from ..utils.validation import check_is_fitted, validate_data
37
+
38
+
39
+ class FactorAnalysis(ClassNamePrefixFeaturesOutMixin, TransformerMixin, BaseEstimator):
40
+ """Factor Analysis (FA).
41
+
42
+ A simple linear generative model with Gaussian latent variables.
43
+
44
+ The observations are assumed to be caused by a linear transformation of
45
+ lower dimensional latent factors and added Gaussian noise.
46
+ Without loss of generality the factors are distributed according to a
47
+ Gaussian with zero mean and unit covariance. The noise is also zero mean
48
+ and has an arbitrary diagonal covariance matrix.
49
+
50
+ If we would restrict the model further, by assuming that the Gaussian
51
+ noise is even isotropic (all diagonal entries are the same) we would obtain
52
+ :class:`PCA`.
53
+
54
+ FactorAnalysis performs a maximum likelihood estimate of the so-called
55
+ `loading` matrix, the transformation of the latent variables to the
56
+ observed ones, using SVD based approach.
57
+
58
+ Read more in the :ref:`User Guide <FA>`.
59
+
60
+ .. versionadded:: 0.13
61
+
62
+ Parameters
63
+ ----------
64
+ n_components : int, default=None
65
+ Dimensionality of latent space, the number of components
66
+ of ``X`` that are obtained after ``transform``.
67
+ If None, n_components is set to the number of features.
68
+
69
+ tol : float, default=1e-2
70
+ Stopping tolerance for log-likelihood increase.
71
+
72
+ copy : bool, default=True
73
+ Whether to make a copy of X. If ``False``, the input X gets overwritten
74
+ during fitting.
75
+
76
+ max_iter : int, default=1000
77
+ Maximum number of iterations.
78
+
79
+ noise_variance_init : array-like of shape (n_features,), default=None
80
+ The initial guess of the noise variance for each feature.
81
+ If None, it defaults to np.ones(n_features).
82
+
83
+ svd_method : {'lapack', 'randomized'}, default='randomized'
84
+ Which SVD method to use. If 'lapack' use standard SVD from
85
+ scipy.linalg, if 'randomized' use fast ``randomized_svd`` function.
86
+ Defaults to 'randomized'. For most applications 'randomized' will
87
+ be sufficiently precise while providing significant speed gains.
88
+ Accuracy can also be improved by setting higher values for
89
+ `iterated_power`. If this is not sufficient, for maximum precision
90
+ you should choose 'lapack'.
91
+
92
+ iterated_power : int, default=3
93
+ Number of iterations for the power method. 3 by default. Only used
94
+ if ``svd_method`` equals 'randomized'.
95
+
96
+ rotation : {'varimax', 'quartimax'}, default=None
97
+ If not None, apply the indicated rotation. Currently, varimax and
98
+ quartimax are implemented. See
99
+ `"The varimax criterion for analytic rotation in factor analysis"
100
+ <https://link.springer.com/article/10.1007%2FBF02289233>`_
101
+ H. F. Kaiser, 1958.
102
+
103
+ .. versionadded:: 0.24
104
+
105
+ random_state : int or RandomState instance, default=0
106
+ Only used when ``svd_method`` equals 'randomized'. Pass an int for
107
+ reproducible results across multiple function calls.
108
+ See :term:`Glossary <random_state>`.
109
+
110
+ Attributes
111
+ ----------
112
+ components_ : ndarray of shape (n_components, n_features)
113
+ Components with maximum variance.
114
+
115
+ loglike_ : list of shape (n_iterations,)
116
+ The log likelihood at each iteration.
117
+
118
+ noise_variance_ : ndarray of shape (n_features,)
119
+ The estimated noise variance for each feature.
120
+
121
+ n_iter_ : int
122
+ Number of iterations run.
123
+
124
+ mean_ : ndarray of shape (n_features,)
125
+ Per-feature empirical mean, estimated from the training set.
126
+
127
+ n_features_in_ : int
128
+ Number of features seen during :term:`fit`.
129
+
130
+ .. versionadded:: 0.24
131
+
132
+ feature_names_in_ : ndarray of shape (`n_features_in_`,)
133
+ Names of features seen during :term:`fit`. Defined only when `X`
134
+ has feature names that are all strings.
135
+
136
+ .. versionadded:: 1.0
137
+
138
+ See Also
139
+ --------
140
+ PCA: Principal component analysis is also a latent linear variable model
141
+ which however assumes equal noise variance for each feature.
142
+ This extra assumption makes probabilistic PCA faster as it can be
143
+ computed in closed form.
144
+ FastICA: Independent component analysis, a latent variable model with
145
+ non-Gaussian latent variables.
146
+
147
+ References
148
+ ----------
149
+ - David Barber, Bayesian Reasoning and Machine Learning,
150
+ Algorithm 21.1.
151
+
152
+ - Christopher M. Bishop: Pattern Recognition and Machine Learning,
153
+ Chapter 12.2.4.
154
+
155
+ Examples
156
+ --------
157
+ >>> from sklearn.datasets import load_digits
158
+ >>> from sklearn.decomposition import FactorAnalysis
159
+ >>> X, _ = load_digits(return_X_y=True)
160
+ >>> transformer = FactorAnalysis(n_components=7, random_state=0)
161
+ >>> X_transformed = transformer.fit_transform(X)
162
+ >>> X_transformed.shape
163
+ (1797, 7)
164
+ """
165
+
166
+ _parameter_constraints: dict = {
167
+ "n_components": [Interval(Integral, 0, None, closed="left"), None],
168
+ "tol": [Interval(Real, 0.0, None, closed="left")],
169
+ "copy": ["boolean"],
170
+ "max_iter": [Interval(Integral, 1, None, closed="left")],
171
+ "noise_variance_init": ["array-like", None],
172
+ "svd_method": [StrOptions({"randomized", "lapack"})],
173
+ "iterated_power": [Interval(Integral, 0, None, closed="left")],
174
+ "rotation": [StrOptions({"varimax", "quartimax"}), None],
175
+ "random_state": ["random_state"],
176
+ }
177
+
178
+ def __init__(
179
+ self,
180
+ n_components=None,
181
+ *,
182
+ tol=1e-2,
183
+ copy=True,
184
+ max_iter=1000,
185
+ noise_variance_init=None,
186
+ svd_method="randomized",
187
+ iterated_power=3,
188
+ rotation=None,
189
+ random_state=0,
190
+ ):
191
+ self.n_components = n_components
192
+ self.copy = copy
193
+ self.tol = tol
194
+ self.max_iter = max_iter
195
+ self.svd_method = svd_method
196
+
197
+ self.noise_variance_init = noise_variance_init
198
+ self.iterated_power = iterated_power
199
+ self.random_state = random_state
200
+ self.rotation = rotation
201
+
202
+ @_fit_context(prefer_skip_nested_validation=True)
203
+ def fit(self, X, y=None):
204
+ """Fit the FactorAnalysis model to X using SVD based approach.
205
+
206
+ Parameters
207
+ ----------
208
+ X : array-like of shape (n_samples, n_features)
209
+ Training data.
210
+
211
+ y : Ignored
212
+ Ignored parameter.
213
+
214
+ Returns
215
+ -------
216
+ self : object
217
+ FactorAnalysis class instance.
218
+ """
219
+ X = validate_data(
220
+ self, X, copy=self.copy, dtype=np.float64, force_writeable=True
221
+ )
222
+
223
+ n_samples, n_features = X.shape
224
+ n_components = self.n_components
225
+ if n_components is None:
226
+ n_components = n_features
227
+
228
+ self.mean_ = np.mean(X, axis=0)
229
+ X -= self.mean_
230
+
231
+ # some constant terms
232
+ nsqrt = sqrt(n_samples)
233
+ llconst = n_features * log(2.0 * np.pi) + n_components
234
+ var = np.var(X, axis=0)
235
+
236
+ if self.noise_variance_init is None:
237
+ psi = np.ones(n_features, dtype=X.dtype)
238
+ else:
239
+ if len(self.noise_variance_init) != n_features:
240
+ raise ValueError(
241
+ "noise_variance_init dimension does not "
242
+ "with number of features : %d != %d"
243
+ % (len(self.noise_variance_init), n_features)
244
+ )
245
+ psi = np.array(self.noise_variance_init)
246
+
247
+ loglike = []
248
+ old_ll = -np.inf
249
+ SMALL = 1e-12
250
+
251
+ # we'll modify svd outputs to return unexplained variance
252
+ # to allow for unified computation of loglikelihood
253
+ if self.svd_method == "lapack":
254
+
255
+ def my_svd(X):
256
+ _, s, Vt = linalg.svd(X, full_matrices=False, check_finite=False)
257
+ return (
258
+ s[:n_components],
259
+ Vt[:n_components],
260
+ squared_norm(s[n_components:]),
261
+ )
262
+
263
+ else: # svd_method == "randomized"
264
+ random_state = check_random_state(self.random_state)
265
+
266
+ def my_svd(X):
267
+ _, s, Vt = _randomized_svd(
268
+ X,
269
+ n_components,
270
+ random_state=random_state,
271
+ n_iter=self.iterated_power,
272
+ )
273
+ return s, Vt, squared_norm(X) - squared_norm(s)
274
+
275
+ for i in range(self.max_iter):
276
+ # SMALL helps numerics
277
+ sqrt_psi = np.sqrt(psi) + SMALL
278
+ s, Vt, unexp_var = my_svd(X / (sqrt_psi * nsqrt))
279
+ s **= 2
280
+ # Use 'maximum' here to avoid sqrt problems.
281
+ W = np.sqrt(np.maximum(s - 1.0, 0.0))[:, np.newaxis] * Vt
282
+ del Vt
283
+ W *= sqrt_psi
284
+
285
+ # loglikelihood
286
+ ll = llconst + np.sum(np.log(s))
287
+ ll += unexp_var + np.sum(np.log(psi))
288
+ ll *= -n_samples / 2.0
289
+ loglike.append(ll)
290
+ if (ll - old_ll) < self.tol:
291
+ break
292
+ old_ll = ll
293
+
294
+ psi = np.maximum(var - np.sum(W**2, axis=0), SMALL)
295
+ else:
296
+ warnings.warn(
297
+ "FactorAnalysis did not converge."
298
+ " You might want"
299
+ " to increase the number of iterations.",
300
+ ConvergenceWarning,
301
+ )
302
+
303
+ self.components_ = W
304
+ if self.rotation is not None:
305
+ self.components_ = self._rotate(W)
306
+ self.noise_variance_ = psi
307
+ self.loglike_ = loglike
308
+ self.n_iter_ = i + 1
309
+ return self
310
+
311
+ def transform(self, X):
312
+ """Apply dimensionality reduction to X using the model.
313
+
314
+ Compute the expected mean of the latent variables.
315
+ See Barber, 21.2.33 (or Bishop, 12.66).
316
+
317
+ Parameters
318
+ ----------
319
+ X : array-like of shape (n_samples, n_features)
320
+ Training data.
321
+
322
+ Returns
323
+ -------
324
+ X_new : ndarray of shape (n_samples, n_components)
325
+ The latent variables of X.
326
+ """
327
+ check_is_fitted(self)
328
+
329
+ X = validate_data(self, X, reset=False)
330
+ Ih = np.eye(len(self.components_))
331
+
332
+ X_transformed = X - self.mean_
333
+
334
+ Wpsi = self.components_ / self.noise_variance_
335
+ cov_z = linalg.inv(Ih + np.dot(Wpsi, self.components_.T))
336
+ tmp = np.dot(X_transformed, Wpsi.T)
337
+ X_transformed = np.dot(tmp, cov_z)
338
+
339
+ return X_transformed
340
+
341
+ def get_covariance(self):
342
+ """Compute data covariance with the FactorAnalysis model.
343
+
344
+ ``cov = components_.T * components_ + diag(noise_variance)``
345
+
346
+ Returns
347
+ -------
348
+ cov : ndarray of shape (n_features, n_features)
349
+ Estimated covariance of data.
350
+ """
351
+ check_is_fitted(self)
352
+
353
+ cov = np.dot(self.components_.T, self.components_)
354
+ cov.flat[:: len(cov) + 1] += self.noise_variance_ # modify diag inplace
355
+ return cov
356
+
357
+ def get_precision(self):
358
+ """Compute data precision matrix with the FactorAnalysis model.
359
+
360
+ Returns
361
+ -------
362
+ precision : ndarray of shape (n_features, n_features)
363
+ Estimated precision of data.
364
+ """
365
+ check_is_fitted(self)
366
+
367
+ n_features = self.components_.shape[1]
368
+
369
+ # handle corner cases first
370
+ if self.n_components == 0:
371
+ return np.diag(1.0 / self.noise_variance_)
372
+ if self.n_components == n_features:
373
+ return linalg.inv(self.get_covariance())
374
+
375
+ # Get precision using matrix inversion lemma
376
+ components_ = self.components_
377
+ precision = np.dot(components_ / self.noise_variance_, components_.T)
378
+ precision.flat[:: len(precision) + 1] += 1.0
379
+ precision = np.dot(components_.T, np.dot(linalg.inv(precision), components_))
380
+ precision /= self.noise_variance_[:, np.newaxis]
381
+ precision /= -self.noise_variance_[np.newaxis, :]
382
+ precision.flat[:: len(precision) + 1] += 1.0 / self.noise_variance_
383
+ return precision
384
+
385
+ def score_samples(self, X):
386
+ """Compute the log-likelihood of each sample.
387
+
388
+ Parameters
389
+ ----------
390
+ X : ndarray of shape (n_samples, n_features)
391
+ The data.
392
+
393
+ Returns
394
+ -------
395
+ ll : ndarray of shape (n_samples,)
396
+ Log-likelihood of each sample under the current model.
397
+ """
398
+ check_is_fitted(self)
399
+ X = validate_data(self, X, reset=False)
400
+ Xr = X - self.mean_
401
+ precision = self.get_precision()
402
+ n_features = X.shape[1]
403
+ log_like = -0.5 * (Xr * (np.dot(Xr, precision))).sum(axis=1)
404
+ log_like -= 0.5 * (n_features * log(2.0 * np.pi) - fast_logdet(precision))
405
+ return log_like
406
+
407
+ def score(self, X, y=None):
408
+ """Compute the average log-likelihood of the samples.
409
+
410
+ Parameters
411
+ ----------
412
+ X : ndarray of shape (n_samples, n_features)
413
+ The data.
414
+
415
+ y : Ignored
416
+ Ignored parameter.
417
+
418
+ Returns
419
+ -------
420
+ ll : float
421
+ Average log-likelihood of the samples under the current model.
422
+ """
423
+ return np.mean(self.score_samples(X))
424
+
425
+ def _rotate(self, components, n_components=None, tol=1e-6):
426
+ "Rotate the factor analysis solution."
427
+ # note that tol is not exposed
428
+ return _ortho_rotation(components.T, method=self.rotation, tol=tol)[
429
+ : self.n_components
430
+ ]
431
+
432
+ @property
433
+ def _n_features_out(self):
434
+ """Number of transformed output features."""
435
+ return self.components_.shape[0]
436
+
437
+
438
+ def _ortho_rotation(components, method="varimax", tol=1e-6, max_iter=100):
439
+ """Return rotated components."""
440
+ nrow, ncol = components.shape
441
+ rotation_matrix = np.eye(ncol)
442
+ var = 0
443
+
444
+ for _ in range(max_iter):
445
+ comp_rot = np.dot(components, rotation_matrix)
446
+ if method == "varimax":
447
+ tmp = comp_rot * np.transpose((comp_rot**2).sum(axis=0) / nrow)
448
+ elif method == "quartimax":
449
+ tmp = 0
450
+ u, s, v = np.linalg.svd(np.dot(components.T, comp_rot**3 - tmp))
451
+ rotation_matrix = np.dot(u, v)
452
+ var_new = np.sum(s)
453
+ if var != 0 and var_new < var * (1 + tol):
454
+ break
455
+ var = var_new
456
+
457
+ return np.dot(components, rotation_matrix).T
miniconda3/envs/active_proaction/lib/python3.10/site-packages/sklearn/decomposition/_fastica.py ADDED
@@ -0,0 +1,804 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Python implementation of the fast ICA algorithms.
3
+
4
+ Reference: Tables 8.3 and 8.4 page 196 in the book:
5
+ Independent Component Analysis, by Hyvarinen et al.
6
+ """
7
+
8
+ # Authors: The scikit-learn developers
9
+ # SPDX-License-Identifier: BSD-3-Clause
10
+
11
+ import warnings
12
+ from numbers import Integral, Real
13
+
14
+ import numpy as np
15
+ from scipy import linalg
16
+
17
+ from ..base import (
18
+ BaseEstimator,
19
+ ClassNamePrefixFeaturesOutMixin,
20
+ TransformerMixin,
21
+ _fit_context,
22
+ )
23
+ from ..exceptions import ConvergenceWarning
24
+ from ..utils import as_float_array, check_array, check_random_state
25
+ from ..utils._param_validation import Interval, Options, StrOptions, validate_params
26
+ from ..utils.validation import check_is_fitted, validate_data
27
+
28
+ __all__ = ["FastICA", "fastica"]
29
+
30
+
31
+ def _gs_decorrelation(w, W, j):
32
+ """
33
+ Orthonormalize w wrt the first j rows of W.
34
+
35
+ Parameters
36
+ ----------
37
+ w : ndarray of shape (n,)
38
+ Array to be orthogonalized
39
+
40
+ W : ndarray of shape (p, n)
41
+ Null space definition
42
+
43
+ j : int < p
44
+ The no of (from the first) rows of Null space W wrt which w is
45
+ orthogonalized.
46
+
47
+ Notes
48
+ -----
49
+ Assumes that W is orthogonal
50
+ w changed in place
51
+ """
52
+ w -= np.linalg.multi_dot([w, W[:j].T, W[:j]])
53
+ return w
54
+
55
+
56
+ def _sym_decorrelation(W):
57
+ """Symmetric decorrelation
58
+ i.e. W <- (W * W.T) ^{-1/2} * W
59
+ """
60
+ s, u = linalg.eigh(np.dot(W, W.T))
61
+ # Avoid sqrt of negative values because of rounding errors. Note that
62
+ # np.sqrt(tiny) is larger than tiny and therefore this clipping also
63
+ # prevents division by zero in the next step.
64
+ s = np.clip(s, a_min=np.finfo(W.dtype).tiny, a_max=None)
65
+
66
+ # u (resp. s) contains the eigenvectors (resp. square roots of
67
+ # the eigenvalues) of W * W.T
68
+ return np.linalg.multi_dot([u * (1.0 / np.sqrt(s)), u.T, W])
69
+
70
+
71
+ def _ica_def(X, tol, g, fun_args, max_iter, w_init):
72
+ """Deflationary FastICA using fun approx to neg-entropy function
73
+
74
+ Used internally by FastICA.
75
+ """
76
+
77
+ n_components = w_init.shape[0]
78
+ W = np.zeros((n_components, n_components), dtype=X.dtype)
79
+ n_iter = []
80
+
81
+ # j is the index of the extracted component
82
+ for j in range(n_components):
83
+ w = w_init[j, :].copy()
84
+ w /= np.sqrt((w**2).sum())
85
+
86
+ for i in range(max_iter):
87
+ gwtx, g_wtx = g(np.dot(w.T, X), fun_args)
88
+
89
+ w1 = (X * gwtx).mean(axis=1) - g_wtx.mean() * w
90
+
91
+ _gs_decorrelation(w1, W, j)
92
+
93
+ w1 /= np.sqrt((w1**2).sum())
94
+
95
+ lim = np.abs(np.abs((w1 * w).sum()) - 1)
96
+ w = w1
97
+ if lim < tol:
98
+ break
99
+
100
+ n_iter.append(i + 1)
101
+ W[j, :] = w
102
+
103
+ return W, max(n_iter)
104
+
105
+
106
+ def _ica_par(X, tol, g, fun_args, max_iter, w_init):
107
+ """Parallel FastICA.
108
+
109
+ Used internally by FastICA --main loop
110
+
111
+ """
112
+ W = _sym_decorrelation(w_init)
113
+ del w_init
114
+ p_ = float(X.shape[1])
115
+ for ii in range(max_iter):
116
+ gwtx, g_wtx = g(np.dot(W, X), fun_args)
117
+ W1 = _sym_decorrelation(np.dot(gwtx, X.T) / p_ - g_wtx[:, np.newaxis] * W)
118
+ del gwtx, g_wtx
119
+ # builtin max, abs are faster than numpy counter parts.
120
+ # np.einsum allows having the lowest memory footprint.
121
+ # It is faster than np.diag(np.dot(W1, W.T)).
122
+ lim = max(abs(abs(np.einsum("ij,ij->i", W1, W)) - 1))
123
+ W = W1
124
+ if lim < tol:
125
+ break
126
+ else:
127
+ warnings.warn(
128
+ (
129
+ "FastICA did not converge. Consider increasing "
130
+ "tolerance or the maximum number of iterations."
131
+ ),
132
+ ConvergenceWarning,
133
+ )
134
+
135
+ return W, ii + 1
136
+
137
+
138
+ # Some standard non-linear functions.
139
+ # XXX: these should be optimized, as they can be a bottleneck.
140
+ def _logcosh(x, fun_args=None):
141
+ alpha = fun_args.get("alpha", 1.0) # comment it out?
142
+
143
+ x *= alpha
144
+ gx = np.tanh(x, x) # apply the tanh inplace
145
+ g_x = np.empty(x.shape[0], dtype=x.dtype)
146
+ # XXX compute in chunks to avoid extra allocation
147
+ for i, gx_i in enumerate(gx): # please don't vectorize.
148
+ g_x[i] = (alpha * (1 - gx_i**2)).mean()
149
+ return gx, g_x
150
+
151
+
152
+ def _exp(x, fun_args):
153
+ exp = np.exp(-(x**2) / 2)
154
+ gx = x * exp
155
+ g_x = (1 - x**2) * exp
156
+ return gx, g_x.mean(axis=-1)
157
+
158
+
159
+ def _cube(x, fun_args):
160
+ return x**3, (3 * x**2).mean(axis=-1)
161
+
162
+
163
+ @validate_params(
164
+ {
165
+ "X": ["array-like"],
166
+ "return_X_mean": ["boolean"],
167
+ "compute_sources": ["boolean"],
168
+ "return_n_iter": ["boolean"],
169
+ },
170
+ prefer_skip_nested_validation=False,
171
+ )
172
+ def fastica(
173
+ X,
174
+ n_components=None,
175
+ *,
176
+ algorithm="parallel",
177
+ whiten="unit-variance",
178
+ fun="logcosh",
179
+ fun_args=None,
180
+ max_iter=200,
181
+ tol=1e-04,
182
+ w_init=None,
183
+ whiten_solver="svd",
184
+ random_state=None,
185
+ return_X_mean=False,
186
+ compute_sources=True,
187
+ return_n_iter=False,
188
+ ):
189
+ """Perform Fast Independent Component Analysis.
190
+
191
+ The implementation is based on [1]_.
192
+
193
+ Read more in the :ref:`User Guide <ICA>`.
194
+
195
+ Parameters
196
+ ----------
197
+ X : array-like of shape (n_samples, n_features)
198
+ Training vector, where `n_samples` is the number of samples and
199
+ `n_features` is the number of features.
200
+
201
+ n_components : int, default=None
202
+ Number of components to use. If None is passed, all are used.
203
+
204
+ algorithm : {'parallel', 'deflation'}, default='parallel'
205
+ Specify which algorithm to use for FastICA.
206
+
207
+ whiten : str or bool, default='unit-variance'
208
+ Specify the whitening strategy to use.
209
+
210
+ - If 'arbitrary-variance', a whitening with variance
211
+ arbitrary is used.
212
+ - If 'unit-variance', the whitening matrix is rescaled to ensure that
213
+ each recovered source has unit variance.
214
+ - If False, the data is already considered to be whitened, and no
215
+ whitening is performed.
216
+
217
+ .. versionchanged:: 1.3
218
+ The default value of `whiten` changed to 'unit-variance' in 1.3.
219
+
220
+ fun : {'logcosh', 'exp', 'cube'} or callable, default='logcosh'
221
+ The functional form of the G function used in the
222
+ approximation to neg-entropy. Could be either 'logcosh', 'exp',
223
+ or 'cube'.
224
+ You can also provide your own function. It should return a tuple
225
+ containing the value of the function, and of its derivative, in the
226
+ point. The derivative should be averaged along its last dimension.
227
+ Example::
228
+
229
+ def my_g(x):
230
+ return x ** 3, (3 * x ** 2).mean(axis=-1)
231
+
232
+ fun_args : dict, default=None
233
+ Arguments to send to the functional form.
234
+ If empty or None and if fun='logcosh', fun_args will take value
235
+ {'alpha' : 1.0}.
236
+
237
+ max_iter : int, default=200
238
+ Maximum number of iterations to perform.
239
+
240
+ tol : float, default=1e-4
241
+ A positive scalar giving the tolerance at which the
242
+ un-mixing matrix is considered to have converged.
243
+
244
+ w_init : ndarray of shape (n_components, n_components), default=None
245
+ Initial un-mixing array. If `w_init=None`, then an array of values
246
+ drawn from a normal distribution is used.
247
+
248
+ whiten_solver : {"eigh", "svd"}, default="svd"
249
+ The solver to use for whitening.
250
+
251
+ - "svd" is more stable numerically if the problem is degenerate, and
252
+ often faster when `n_samples <= n_features`.
253
+
254
+ - "eigh" is generally more memory efficient when
255
+ `n_samples >= n_features`, and can be faster when
256
+ `n_samples >= 50 * n_features`.
257
+
258
+ .. versionadded:: 1.2
259
+
260
+ random_state : int, RandomState instance or None, default=None
261
+ Used to initialize ``w_init`` when not specified, with a
262
+ normal distribution. Pass an int, for reproducible results
263
+ across multiple function calls.
264
+ See :term:`Glossary <random_state>`.
265
+
266
+ return_X_mean : bool, default=False
267
+ If True, X_mean is returned too.
268
+
269
+ compute_sources : bool, default=True
270
+ If False, sources are not computed, but only the rotation matrix.
271
+ This can save memory when working with big data. Defaults to True.
272
+
273
+ return_n_iter : bool, default=False
274
+ Whether or not to return the number of iterations.
275
+
276
+ Returns
277
+ -------
278
+ K : ndarray of shape (n_components, n_features) or None
279
+ If whiten is 'True', K is the pre-whitening matrix that projects data
280
+ onto the first n_components principal components. If whiten is 'False',
281
+ K is 'None'.
282
+
283
+ W : ndarray of shape (n_components, n_components)
284
+ The square matrix that unmixes the data after whitening.
285
+ The mixing matrix is the pseudo-inverse of matrix ``W K``
286
+ if K is not None, else it is the inverse of W.
287
+
288
+ S : ndarray of shape (n_samples, n_components) or None
289
+ Estimated source matrix.
290
+
291
+ X_mean : ndarray of shape (n_features,)
292
+ The mean over features. Returned only if return_X_mean is True.
293
+
294
+ n_iter : int
295
+ If the algorithm is "deflation", n_iter is the
296
+ maximum number of iterations run across all components. Else
297
+ they are just the number of iterations taken to converge. This is
298
+ returned only when return_n_iter is set to `True`.
299
+
300
+ Notes
301
+ -----
302
+ The data matrix X is considered to be a linear combination of
303
+ non-Gaussian (independent) components i.e. X = AS where columns of S
304
+ contain the independent components and A is a linear mixing
305
+ matrix. In short ICA attempts to `un-mix' the data by estimating an
306
+ un-mixing matrix W where ``S = W K X.``
307
+ While FastICA was proposed to estimate as many sources
308
+ as features, it is possible to estimate less by setting
309
+ n_components < n_features. It this case K is not a square matrix
310
+ and the estimated A is the pseudo-inverse of ``W K``.
311
+
312
+ This implementation was originally made for data of shape
313
+ [n_features, n_samples]. Now the input is transposed
314
+ before the algorithm is applied. This makes it slightly
315
+ faster for Fortran-ordered input.
316
+
317
+ References
318
+ ----------
319
+ .. [1] A. Hyvarinen and E. Oja, "Fast Independent Component Analysis",
320
+ Algorithms and Applications, Neural Networks, 13(4-5), 2000,
321
+ pp. 411-430.
322
+
323
+ Examples
324
+ --------
325
+ >>> from sklearn.datasets import load_digits
326
+ >>> from sklearn.decomposition import fastica
327
+ >>> X, _ = load_digits(return_X_y=True)
328
+ >>> K, W, S = fastica(X, n_components=7, random_state=0, whiten='unit-variance')
329
+ >>> K.shape
330
+ (7, 64)
331
+ >>> W.shape
332
+ (7, 7)
333
+ >>> S.shape
334
+ (1797, 7)
335
+ """
336
+ est = FastICA(
337
+ n_components=n_components,
338
+ algorithm=algorithm,
339
+ whiten=whiten,
340
+ fun=fun,
341
+ fun_args=fun_args,
342
+ max_iter=max_iter,
343
+ tol=tol,
344
+ w_init=w_init,
345
+ whiten_solver=whiten_solver,
346
+ random_state=random_state,
347
+ )
348
+ est._validate_params()
349
+ S = est._fit_transform(X, compute_sources=compute_sources)
350
+
351
+ if est.whiten in ["unit-variance", "arbitrary-variance"]:
352
+ K = est.whitening_
353
+ X_mean = est.mean_
354
+ else:
355
+ K = None
356
+ X_mean = None
357
+
358
+ returned_values = [K, est._unmixing, S]
359
+ if return_X_mean:
360
+ returned_values.append(X_mean)
361
+ if return_n_iter:
362
+ returned_values.append(est.n_iter_)
363
+
364
+ return returned_values
365
+
366
+
367
+ class FastICA(ClassNamePrefixFeaturesOutMixin, TransformerMixin, BaseEstimator):
368
+ """FastICA: a fast algorithm for Independent Component Analysis.
369
+
370
+ The implementation is based on [1]_.
371
+
372
+ Read more in the :ref:`User Guide <ICA>`.
373
+
374
+ Parameters
375
+ ----------
376
+ n_components : int, default=None
377
+ Number of components to use. If None is passed, all are used.
378
+
379
+ algorithm : {'parallel', 'deflation'}, default='parallel'
380
+ Specify which algorithm to use for FastICA.
381
+
382
+ whiten : str or bool, default='unit-variance'
383
+ Specify the whitening strategy to use.
384
+
385
+ - If 'arbitrary-variance', a whitening with variance
386
+ arbitrary is used.
387
+ - If 'unit-variance', the whitening matrix is rescaled to ensure that
388
+ each recovered source has unit variance.
389
+ - If False, the data is already considered to be whitened, and no
390
+ whitening is performed.
391
+
392
+ .. versionchanged:: 1.3
393
+ The default value of `whiten` changed to 'unit-variance' in 1.3.
394
+
395
+ fun : {'logcosh', 'exp', 'cube'} or callable, default='logcosh'
396
+ The functional form of the G function used in the
397
+ approximation to neg-entropy. Could be either 'logcosh', 'exp',
398
+ or 'cube'.
399
+ You can also provide your own function. It should return a tuple
400
+ containing the value of the function, and of its derivative, in the
401
+ point. The derivative should be averaged along its last dimension.
402
+ Example::
403
+
404
+ def my_g(x):
405
+ return x ** 3, (3 * x ** 2).mean(axis=-1)
406
+
407
+ fun_args : dict, default=None
408
+ Arguments to send to the functional form.
409
+ If empty or None and if fun='logcosh', fun_args will take value
410
+ {'alpha' : 1.0}.
411
+
412
+ max_iter : int, default=200
413
+ Maximum number of iterations during fit.
414
+
415
+ tol : float, default=1e-4
416
+ A positive scalar giving the tolerance at which the
417
+ un-mixing matrix is considered to have converged.
418
+
419
+ w_init : array-like of shape (n_components, n_components), default=None
420
+ Initial un-mixing array. If `w_init=None`, then an array of values
421
+ drawn from a normal distribution is used.
422
+
423
+ whiten_solver : {"eigh", "svd"}, default="svd"
424
+ The solver to use for whitening.
425
+
426
+ - "svd" is more stable numerically if the problem is degenerate, and
427
+ often faster when `n_samples <= n_features`.
428
+
429
+ - "eigh" is generally more memory efficient when
430
+ `n_samples >= n_features`, and can be faster when
431
+ `n_samples >= 50 * n_features`.
432
+
433
+ .. versionadded:: 1.2
434
+
435
+ random_state : int, RandomState instance or None, default=None
436
+ Used to initialize ``w_init`` when not specified, with a
437
+ normal distribution. Pass an int, for reproducible results
438
+ across multiple function calls.
439
+ See :term:`Glossary <random_state>`.
440
+
441
+ Attributes
442
+ ----------
443
+ components_ : ndarray of shape (n_components, n_features)
444
+ The linear operator to apply to the data to get the independent
445
+ sources. This is equal to the unmixing matrix when ``whiten`` is
446
+ False, and equal to ``np.dot(unmixing_matrix, self.whitening_)`` when
447
+ ``whiten`` is True.
448
+
449
+ mixing_ : ndarray of shape (n_features, n_components)
450
+ The pseudo-inverse of ``components_``. It is the linear operator
451
+ that maps independent sources to the data.
452
+
453
+ mean_ : ndarray of shape(n_features,)
454
+ The mean over features. Only set if `self.whiten` is True.
455
+
456
+ n_features_in_ : int
457
+ Number of features seen during :term:`fit`.
458
+
459
+ .. versionadded:: 0.24
460
+
461
+ feature_names_in_ : ndarray of shape (`n_features_in_`,)
462
+ Names of features seen during :term:`fit`. Defined only when `X`
463
+ has feature names that are all strings.
464
+
465
+ .. versionadded:: 1.0
466
+
467
+ n_iter_ : int
468
+ If the algorithm is "deflation", n_iter is the
469
+ maximum number of iterations run across all components. Else
470
+ they are just the number of iterations taken to converge.
471
+
472
+ whitening_ : ndarray of shape (n_components, n_features)
473
+ Only set if whiten is 'True'. This is the pre-whitening matrix
474
+ that projects data onto the first `n_components` principal components.
475
+
476
+ See Also
477
+ --------
478
+ PCA : Principal component analysis (PCA).
479
+ IncrementalPCA : Incremental principal components analysis (IPCA).
480
+ KernelPCA : Kernel Principal component analysis (KPCA).
481
+ MiniBatchSparsePCA : Mini-batch Sparse Principal Components Analysis.
482
+ SparsePCA : Sparse Principal Components Analysis (SparsePCA).
483
+
484
+ References
485
+ ----------
486
+ .. [1] A. Hyvarinen and E. Oja, Independent Component Analysis:
487
+ Algorithms and Applications, Neural Networks, 13(4-5), 2000,
488
+ pp. 411-430.
489
+
490
+ Examples
491
+ --------
492
+ >>> from sklearn.datasets import load_digits
493
+ >>> from sklearn.decomposition import FastICA
494
+ >>> X, _ = load_digits(return_X_y=True)
495
+ >>> transformer = FastICA(n_components=7,
496
+ ... random_state=0,
497
+ ... whiten='unit-variance')
498
+ >>> X_transformed = transformer.fit_transform(X)
499
+ >>> X_transformed.shape
500
+ (1797, 7)
501
+ """
502
+
503
+ _parameter_constraints: dict = {
504
+ "n_components": [Interval(Integral, 1, None, closed="left"), None],
505
+ "algorithm": [StrOptions({"parallel", "deflation"})],
506
+ "whiten": [
507
+ StrOptions({"arbitrary-variance", "unit-variance"}),
508
+ Options(bool, {False}),
509
+ ],
510
+ "fun": [StrOptions({"logcosh", "exp", "cube"}), callable],
511
+ "fun_args": [dict, None],
512
+ "max_iter": [Interval(Integral, 1, None, closed="left")],
513
+ "tol": [Interval(Real, 0.0, None, closed="left")],
514
+ "w_init": ["array-like", None],
515
+ "whiten_solver": [StrOptions({"eigh", "svd"})],
516
+ "random_state": ["random_state"],
517
+ }
518
+
519
+ def __init__(
520
+ self,
521
+ n_components=None,
522
+ *,
523
+ algorithm="parallel",
524
+ whiten="unit-variance",
525
+ fun="logcosh",
526
+ fun_args=None,
527
+ max_iter=200,
528
+ tol=1e-4,
529
+ w_init=None,
530
+ whiten_solver="svd",
531
+ random_state=None,
532
+ ):
533
+ super().__init__()
534
+ self.n_components = n_components
535
+ self.algorithm = algorithm
536
+ self.whiten = whiten
537
+ self.fun = fun
538
+ self.fun_args = fun_args
539
+ self.max_iter = max_iter
540
+ self.tol = tol
541
+ self.w_init = w_init
542
+ self.whiten_solver = whiten_solver
543
+ self.random_state = random_state
544
+
545
+ def _fit_transform(self, X, compute_sources=False):
546
+ """Fit the model.
547
+
548
+ Parameters
549
+ ----------
550
+ X : array-like of shape (n_samples, n_features)
551
+ Training data, where `n_samples` is the number of samples
552
+ and `n_features` is the number of features.
553
+
554
+ compute_sources : bool, default=False
555
+ If False, sources are not computes but only the rotation matrix.
556
+ This can save memory when working with big data. Defaults to False.
557
+
558
+ Returns
559
+ -------
560
+ S : ndarray of shape (n_samples, n_components) or None
561
+ Sources matrix. `None` if `compute_sources` is `False`.
562
+ """
563
+ XT = validate_data(
564
+ self,
565
+ X,
566
+ copy=self.whiten,
567
+ dtype=[np.float64, np.float32],
568
+ ensure_min_samples=2,
569
+ ).T
570
+ fun_args = {} if self.fun_args is None else self.fun_args
571
+ random_state = check_random_state(self.random_state)
572
+
573
+ alpha = fun_args.get("alpha", 1.0)
574
+ if not 1 <= alpha <= 2:
575
+ raise ValueError("alpha must be in [1,2]")
576
+
577
+ if self.fun == "logcosh":
578
+ g = _logcosh
579
+ elif self.fun == "exp":
580
+ g = _exp
581
+ elif self.fun == "cube":
582
+ g = _cube
583
+ elif callable(self.fun):
584
+
585
+ def g(x, fun_args):
586
+ return self.fun(x, **fun_args)
587
+
588
+ n_features, n_samples = XT.shape
589
+ n_components = self.n_components
590
+ if not self.whiten and n_components is not None:
591
+ n_components = None
592
+ warnings.warn("Ignoring n_components with whiten=False.")
593
+
594
+ if n_components is None:
595
+ n_components = min(n_samples, n_features)
596
+ if n_components > min(n_samples, n_features):
597
+ n_components = min(n_samples, n_features)
598
+ warnings.warn(
599
+ "n_components is too large: it will be set to %s" % n_components
600
+ )
601
+
602
+ if self.whiten:
603
+ # Centering the features of X
604
+ X_mean = XT.mean(axis=-1)
605
+ XT -= X_mean[:, np.newaxis]
606
+
607
+ # Whitening and preprocessing by PCA
608
+ if self.whiten_solver == "eigh":
609
+ # Faster when num_samples >> n_features
610
+ d, u = linalg.eigh(XT.dot(X))
611
+ sort_indices = np.argsort(d)[::-1]
612
+ eps = np.finfo(d.dtype).eps * 10
613
+ degenerate_idx = d < eps
614
+ if np.any(degenerate_idx):
615
+ warnings.warn(
616
+ "There are some small singular values, using "
617
+ "whiten_solver = 'svd' might lead to more "
618
+ "accurate results."
619
+ )
620
+ d[degenerate_idx] = eps # For numerical issues
621
+ np.sqrt(d, out=d)
622
+ d, u = d[sort_indices], u[:, sort_indices]
623
+ elif self.whiten_solver == "svd":
624
+ u, d = linalg.svd(XT, full_matrices=False, check_finite=False)[:2]
625
+
626
+ # Give consistent eigenvectors for both svd solvers
627
+ u *= np.sign(u[0])
628
+
629
+ K = (u / d).T[:n_components] # see (6.33) p.140
630
+ del u, d
631
+ X1 = np.dot(K, XT)
632
+ # see (13.6) p.267 Here X1 is white and data
633
+ # in X has been projected onto a subspace by PCA
634
+ X1 *= np.sqrt(n_samples)
635
+ else:
636
+ # X must be casted to floats to avoid typing issues with numpy
637
+ # 2.0 and the line below
638
+ X1 = as_float_array(XT, copy=False) # copy has been taken care of
639
+
640
+ w_init = self.w_init
641
+ if w_init is None:
642
+ w_init = np.asarray(
643
+ random_state.normal(size=(n_components, n_components)), dtype=X1.dtype
644
+ )
645
+
646
+ else:
647
+ w_init = np.asarray(w_init)
648
+ if w_init.shape != (n_components, n_components):
649
+ raise ValueError(
650
+ "w_init has invalid shape -- should be %(shape)s"
651
+ % {"shape": (n_components, n_components)}
652
+ )
653
+
654
+ kwargs = {
655
+ "tol": self.tol,
656
+ "g": g,
657
+ "fun_args": fun_args,
658
+ "max_iter": self.max_iter,
659
+ "w_init": w_init,
660
+ }
661
+
662
+ if self.algorithm == "parallel":
663
+ W, n_iter = _ica_par(X1, **kwargs)
664
+ elif self.algorithm == "deflation":
665
+ W, n_iter = _ica_def(X1, **kwargs)
666
+ del X1
667
+
668
+ self.n_iter_ = n_iter
669
+
670
+ if compute_sources:
671
+ if self.whiten:
672
+ S = np.linalg.multi_dot([W, K, XT]).T
673
+ else:
674
+ S = np.dot(W, XT).T
675
+ else:
676
+ S = None
677
+
678
+ if self.whiten:
679
+ if self.whiten == "unit-variance":
680
+ if not compute_sources:
681
+ S = np.linalg.multi_dot([W, K, XT]).T
682
+ S_std = np.std(S, axis=0, keepdims=True)
683
+ S /= S_std
684
+ W /= S_std.T
685
+
686
+ self.components_ = np.dot(W, K)
687
+ self.mean_ = X_mean
688
+ self.whitening_ = K
689
+ else:
690
+ self.components_ = W
691
+
692
+ self.mixing_ = linalg.pinv(self.components_, check_finite=False)
693
+ self._unmixing = W
694
+
695
+ return S
696
+
697
+ @_fit_context(prefer_skip_nested_validation=True)
698
+ def fit_transform(self, X, y=None):
699
+ """Fit the model and recover the sources from X.
700
+
701
+ Parameters
702
+ ----------
703
+ X : array-like of shape (n_samples, n_features)
704
+ Training data, where `n_samples` is the number of samples
705
+ and `n_features` is the number of features.
706
+
707
+ y : Ignored
708
+ Not used, present for API consistency by convention.
709
+
710
+ Returns
711
+ -------
712
+ X_new : ndarray of shape (n_samples, n_components)
713
+ Estimated sources obtained by transforming the data with the
714
+ estimated unmixing matrix.
715
+ """
716
+ return self._fit_transform(X, compute_sources=True)
717
+
718
+ @_fit_context(prefer_skip_nested_validation=True)
719
+ def fit(self, X, y=None):
720
+ """Fit the model to X.
721
+
722
+ Parameters
723
+ ----------
724
+ X : array-like of shape (n_samples, n_features)
725
+ Training data, where `n_samples` is the number of samples
726
+ and `n_features` is the number of features.
727
+
728
+ y : Ignored
729
+ Not used, present for API consistency by convention.
730
+
731
+ Returns
732
+ -------
733
+ self : object
734
+ Returns the instance itself.
735
+ """
736
+ self._fit_transform(X, compute_sources=False)
737
+ return self
738
+
739
+ def transform(self, X, copy=True):
740
+ """Recover the sources from X (apply the unmixing matrix).
741
+
742
+ Parameters
743
+ ----------
744
+ X : array-like of shape (n_samples, n_features)
745
+ Data to transform, where `n_samples` is the number of samples
746
+ and `n_features` is the number of features.
747
+
748
+ copy : bool, default=True
749
+ If False, data passed to fit can be overwritten. Defaults to True.
750
+
751
+ Returns
752
+ -------
753
+ X_new : ndarray of shape (n_samples, n_components)
754
+ Estimated sources obtained by transforming the data with the
755
+ estimated unmixing matrix.
756
+ """
757
+ check_is_fitted(self)
758
+
759
+ X = validate_data(
760
+ self,
761
+ X,
762
+ copy=(copy and self.whiten),
763
+ dtype=[np.float64, np.float32],
764
+ reset=False,
765
+ )
766
+ if self.whiten:
767
+ X -= self.mean_
768
+
769
+ return np.dot(X, self.components_.T)
770
+
771
+ def inverse_transform(self, X, copy=True):
772
+ """Transform the sources back to the mixed data (apply mixing matrix).
773
+
774
+ Parameters
775
+ ----------
776
+ X : array-like of shape (n_samples, n_components)
777
+ Sources, where `n_samples` is the number of samples
778
+ and `n_components` is the number of components.
779
+ copy : bool, default=True
780
+ If False, data passed to fit are overwritten. Defaults to True.
781
+
782
+ Returns
783
+ -------
784
+ X_original : ndarray of shape (n_samples, n_features)
785
+ Reconstructed data obtained with the mixing matrix.
786
+ """
787
+ check_is_fitted(self)
788
+
789
+ X = check_array(X, copy=(copy and self.whiten), dtype=[np.float64, np.float32])
790
+ X = np.dot(X, self.mixing_.T)
791
+ if self.whiten:
792
+ X += self.mean_
793
+
794
+ return X
795
+
796
+ @property
797
+ def _n_features_out(self):
798
+ """Number of transformed output features."""
799
+ return self.components_.shape[0]
800
+
801
+ def __sklearn_tags__(self):
802
+ tags = super().__sklearn_tags__()
803
+ tags.transformer_tags.preserves_dtype = ["float64", "float32"]
804
+ return tags
miniconda3/envs/active_proaction/lib/python3.10/site-packages/sklearn/decomposition/_incremental_pca.py ADDED
@@ -0,0 +1,426 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Incremental Principal Components Analysis."""
2
+
3
+ # Authors: The scikit-learn developers
4
+ # SPDX-License-Identifier: BSD-3-Clause
5
+
6
+ from numbers import Integral
7
+
8
+ import numpy as np
9
+ from scipy import linalg, sparse
10
+
11
+ from sklearn.utils import metadata_routing
12
+
13
+ from ..base import _fit_context
14
+ from ..utils import gen_batches
15
+ from ..utils._param_validation import Interval
16
+ from ..utils.extmath import _incremental_mean_and_var, svd_flip
17
+ from ..utils.validation import validate_data
18
+ from ._base import _BasePCA
19
+
20
+
21
+ class IncrementalPCA(_BasePCA):
22
+ """Incremental principal components analysis (IPCA).
23
+
24
+ Linear dimensionality reduction using Singular Value Decomposition of
25
+ the data, keeping only the most significant singular vectors to
26
+ project the data to a lower dimensional space. The input data is centered
27
+ but not scaled for each feature before applying the SVD.
28
+
29
+ Depending on the size of the input data, this algorithm can be much more
30
+ memory efficient than a PCA, and allows sparse input.
31
+
32
+ This algorithm has constant memory complexity, on the order
33
+ of ``batch_size * n_features``, enabling use of np.memmap files without
34
+ loading the entire file into memory. For sparse matrices, the input
35
+ is converted to dense in batches (in order to be able to subtract the
36
+ mean) which avoids storing the entire dense matrix at any one time.
37
+
38
+ The computational overhead of each SVD is
39
+ ``O(batch_size * n_features ** 2)``, but only 2 * batch_size samples
40
+ remain in memory at a time. There will be ``n_samples / batch_size`` SVD
41
+ computations to get the principal components, versus 1 large SVD of
42
+ complexity ``O(n_samples * n_features ** 2)`` for PCA.
43
+
44
+ For a usage example, see
45
+ :ref:`sphx_glr_auto_examples_decomposition_plot_incremental_pca.py`.
46
+
47
+ Read more in the :ref:`User Guide <IncrementalPCA>`.
48
+
49
+ .. versionadded:: 0.16
50
+
51
+ Parameters
52
+ ----------
53
+ n_components : int, default=None
54
+ Number of components to keep. If ``n_components`` is ``None``,
55
+ then ``n_components`` is set to ``min(n_samples, n_features)``.
56
+
57
+ whiten : bool, default=False
58
+ When True (False by default) the ``components_`` vectors are divided
59
+ by ``n_samples`` times ``components_`` to ensure uncorrelated outputs
60
+ with unit component-wise variances.
61
+
62
+ Whitening will remove some information from the transformed signal
63
+ (the relative variance scales of the components) but can sometimes
64
+ improve the predictive accuracy of the downstream estimators by
65
+ making data respect some hard-wired assumptions.
66
+
67
+ copy : bool, default=True
68
+ If False, X will be overwritten. ``copy=False`` can be used to
69
+ save memory but is unsafe for general use.
70
+
71
+ batch_size : int, default=None
72
+ The number of samples to use for each batch. Only used when calling
73
+ ``fit``. If ``batch_size`` is ``None``, then ``batch_size``
74
+ is inferred from the data and set to ``5 * n_features``, to provide a
75
+ balance between approximation accuracy and memory consumption.
76
+
77
+ Attributes
78
+ ----------
79
+ components_ : ndarray of shape (n_components, n_features)
80
+ Principal axes in feature space, representing the directions of
81
+ maximum variance in the data. Equivalently, the right singular
82
+ vectors of the centered input data, parallel to its eigenvectors.
83
+ The components are sorted by decreasing ``explained_variance_``.
84
+
85
+ explained_variance_ : ndarray of shape (n_components,)
86
+ Variance explained by each of the selected components.
87
+
88
+ explained_variance_ratio_ : ndarray of shape (n_components,)
89
+ Percentage of variance explained by each of the selected components.
90
+ If all components are stored, the sum of explained variances is equal
91
+ to 1.0.
92
+
93
+ singular_values_ : ndarray of shape (n_components,)
94
+ The singular values corresponding to each of the selected components.
95
+ The singular values are equal to the 2-norms of the ``n_components``
96
+ variables in the lower-dimensional space.
97
+
98
+ mean_ : ndarray of shape (n_features,)
99
+ Per-feature empirical mean, aggregate over calls to ``partial_fit``.
100
+
101
+ var_ : ndarray of shape (n_features,)
102
+ Per-feature empirical variance, aggregate over calls to
103
+ ``partial_fit``.
104
+
105
+ noise_variance_ : float
106
+ The estimated noise covariance following the Probabilistic PCA model
107
+ from Tipping and Bishop 1999. See "Pattern Recognition and
108
+ Machine Learning" by C. Bishop, 12.2.1 p. 574 or
109
+ http://www.miketipping.com/papers/met-mppca.pdf.
110
+
111
+ n_components_ : int
112
+ The estimated number of components. Relevant when
113
+ ``n_components=None``.
114
+
115
+ n_samples_seen_ : int
116
+ The number of samples processed by the estimator. Will be reset on
117
+ new calls to fit, but increments across ``partial_fit`` calls.
118
+
119
+ batch_size_ : int
120
+ Inferred batch size from ``batch_size``.
121
+
122
+ n_features_in_ : int
123
+ Number of features seen during :term:`fit`.
124
+
125
+ .. versionadded:: 0.24
126
+
127
+ feature_names_in_ : ndarray of shape (`n_features_in_`,)
128
+ Names of features seen during :term:`fit`. Defined only when `X`
129
+ has feature names that are all strings.
130
+
131
+ .. versionadded:: 1.0
132
+
133
+ See Also
134
+ --------
135
+ PCA : Principal component analysis (PCA).
136
+ KernelPCA : Kernel Principal component analysis (KPCA).
137
+ SparsePCA : Sparse Principal Components Analysis (SparsePCA).
138
+ TruncatedSVD : Dimensionality reduction using truncated SVD.
139
+
140
+ Notes
141
+ -----
142
+ Implements the incremental PCA model from:
143
+ *D. Ross, J. Lim, R. Lin, M. Yang, Incremental Learning for Robust Visual
144
+ Tracking, International Journal of Computer Vision, Volume 77, Issue 1-3,
145
+ pp. 125-141, May 2008.*
146
+ See https://www.cs.toronto.edu/~dross/ivt/RossLimLinYang_ijcv.pdf
147
+
148
+ This model is an extension of the Sequential Karhunen-Loeve Transform from:
149
+ :doi:`A. Levy and M. Lindenbaum, Sequential Karhunen-Loeve Basis Extraction and
150
+ its Application to Images, IEEE Transactions on Image Processing, Volume 9,
151
+ Number 8, pp. 1371-1374, August 2000. <10.1109/83.855432>`
152
+
153
+ We have specifically abstained from an optimization used by authors of both
154
+ papers, a QR decomposition used in specific situations to reduce the
155
+ algorithmic complexity of the SVD. The source for this technique is
156
+ *Matrix Computations, Third Edition, G. Holub and C. Van Loan, Chapter 5,
157
+ section 5.4.4, pp 252-253.*. This technique has been omitted because it is
158
+ advantageous only when decomposing a matrix with ``n_samples`` (rows)
159
+ >= 5/3 * ``n_features`` (columns), and hurts the readability of the
160
+ implemented algorithm. This would be a good opportunity for future
161
+ optimization, if it is deemed necessary.
162
+
163
+ References
164
+ ----------
165
+ D. Ross, J. Lim, R. Lin, M. Yang. Incremental Learning for Robust Visual
166
+ Tracking, International Journal of Computer Vision, Volume 77,
167
+ Issue 1-3, pp. 125-141, May 2008.
168
+
169
+ G. Golub and C. Van Loan. Matrix Computations, Third Edition, Chapter 5,
170
+ Section 5.4.4, pp. 252-253.
171
+
172
+ Examples
173
+ --------
174
+ >>> from sklearn.datasets import load_digits
175
+ >>> from sklearn.decomposition import IncrementalPCA
176
+ >>> from scipy import sparse
177
+ >>> X, _ = load_digits(return_X_y=True)
178
+ >>> transformer = IncrementalPCA(n_components=7, batch_size=200)
179
+ >>> # either partially fit on smaller batches of data
180
+ >>> transformer.partial_fit(X[:100, :])
181
+ IncrementalPCA(batch_size=200, n_components=7)
182
+ >>> # or let the fit function itself divide the data into batches
183
+ >>> X_sparse = sparse.csr_matrix(X)
184
+ >>> X_transformed = transformer.fit_transform(X_sparse)
185
+ >>> X_transformed.shape
186
+ (1797, 7)
187
+ """
188
+
189
+ __metadata_request__partial_fit = {"check_input": metadata_routing.UNUSED}
190
+
191
+ _parameter_constraints: dict = {
192
+ "n_components": [Interval(Integral, 1, None, closed="left"), None],
193
+ "whiten": ["boolean"],
194
+ "copy": ["boolean"],
195
+ "batch_size": [Interval(Integral, 1, None, closed="left"), None],
196
+ }
197
+
198
+ def __init__(self, n_components=None, *, whiten=False, copy=True, batch_size=None):
199
+ self.n_components = n_components
200
+ self.whiten = whiten
201
+ self.copy = copy
202
+ self.batch_size = batch_size
203
+
204
+ @_fit_context(prefer_skip_nested_validation=True)
205
+ def fit(self, X, y=None):
206
+ """Fit the model with X, using minibatches of size batch_size.
207
+
208
+ Parameters
209
+ ----------
210
+ X : {array-like, sparse matrix} of shape (n_samples, n_features)
211
+ Training data, where `n_samples` is the number of samples and
212
+ `n_features` is the number of features.
213
+
214
+ y : Ignored
215
+ Not used, present for API consistency by convention.
216
+
217
+ Returns
218
+ -------
219
+ self : object
220
+ Returns the instance itself.
221
+ """
222
+ self.components_ = None
223
+ self.n_samples_seen_ = 0
224
+ self.mean_ = 0.0
225
+ self.var_ = 0.0
226
+ self.singular_values_ = None
227
+ self.explained_variance_ = None
228
+ self.explained_variance_ratio_ = None
229
+ self.noise_variance_ = None
230
+
231
+ X = validate_data(
232
+ self,
233
+ X,
234
+ accept_sparse=["csr", "csc", "lil"],
235
+ copy=self.copy,
236
+ dtype=[np.float64, np.float32],
237
+ force_writeable=True,
238
+ )
239
+ n_samples, n_features = X.shape
240
+
241
+ if self.batch_size is None:
242
+ self.batch_size_ = 5 * n_features
243
+ else:
244
+ self.batch_size_ = self.batch_size
245
+
246
+ for batch in gen_batches(
247
+ n_samples, self.batch_size_, min_batch_size=self.n_components or 0
248
+ ):
249
+ X_batch = X[batch]
250
+ if sparse.issparse(X_batch):
251
+ X_batch = X_batch.toarray()
252
+ self.partial_fit(X_batch, check_input=False)
253
+
254
+ return self
255
+
256
+ @_fit_context(prefer_skip_nested_validation=True)
257
+ def partial_fit(self, X, y=None, check_input=True):
258
+ """Incremental fit with X. All of X is processed as a single batch.
259
+
260
+ Parameters
261
+ ----------
262
+ X : array-like of shape (n_samples, n_features)
263
+ Training data, where `n_samples` is the number of samples and
264
+ `n_features` is the number of features.
265
+
266
+ y : Ignored
267
+ Not used, present for API consistency by convention.
268
+
269
+ check_input : bool, default=True
270
+ Run check_array on X.
271
+
272
+ Returns
273
+ -------
274
+ self : object
275
+ Returns the instance itself.
276
+ """
277
+ first_pass = not hasattr(self, "components_")
278
+
279
+ if check_input:
280
+ if sparse.issparse(X):
281
+ raise TypeError(
282
+ "IncrementalPCA.partial_fit does not support "
283
+ "sparse input. Either convert data to dense "
284
+ "or use IncrementalPCA.fit to do so in batches."
285
+ )
286
+ X = validate_data(
287
+ self,
288
+ X,
289
+ copy=self.copy,
290
+ dtype=[np.float64, np.float32],
291
+ force_writeable=True,
292
+ reset=first_pass,
293
+ )
294
+ n_samples, n_features = X.shape
295
+ if first_pass:
296
+ self.components_ = None
297
+
298
+ if self.n_components is None:
299
+ if self.components_ is None:
300
+ self.n_components_ = min(n_samples, n_features)
301
+ else:
302
+ self.n_components_ = self.components_.shape[0]
303
+ elif not self.n_components <= n_features:
304
+ raise ValueError(
305
+ "n_components=%r invalid for n_features=%d, need "
306
+ "more rows than columns for IncrementalPCA "
307
+ "processing" % (self.n_components, n_features)
308
+ )
309
+ elif self.n_components > n_samples and first_pass:
310
+ raise ValueError(
311
+ f"n_components={self.n_components} must be less or equal to "
312
+ f"the batch number of samples {n_samples} for the first "
313
+ "partial_fit call."
314
+ )
315
+ else:
316
+ self.n_components_ = self.n_components
317
+
318
+ if (self.components_ is not None) and (
319
+ self.components_.shape[0] != self.n_components_
320
+ ):
321
+ raise ValueError(
322
+ "Number of input features has changed from %i "
323
+ "to %i between calls to partial_fit! Try "
324
+ "setting n_components to a fixed value."
325
+ % (self.components_.shape[0], self.n_components_)
326
+ )
327
+
328
+ # This is the first partial_fit
329
+ if not hasattr(self, "n_samples_seen_"):
330
+ self.n_samples_seen_ = 0
331
+ self.mean_ = 0.0
332
+ self.var_ = 0.0
333
+
334
+ # Update stats - they are 0 if this is the first step
335
+ col_mean, col_var, n_total_samples = _incremental_mean_and_var(
336
+ X,
337
+ last_mean=self.mean_,
338
+ last_variance=self.var_,
339
+ last_sample_count=np.repeat(self.n_samples_seen_, X.shape[1]),
340
+ )
341
+ n_total_samples = n_total_samples[0]
342
+
343
+ # Whitening
344
+ if self.n_samples_seen_ == 0:
345
+ # If it is the first step, simply whiten X
346
+ X -= col_mean
347
+ else:
348
+ col_batch_mean = np.mean(X, axis=0)
349
+ X -= col_batch_mean
350
+ # Build matrix of combined previous basis and new data
351
+ mean_correction = np.sqrt(
352
+ (self.n_samples_seen_ / n_total_samples) * n_samples
353
+ ) * (self.mean_ - col_batch_mean)
354
+ X = np.vstack(
355
+ (
356
+ self.singular_values_.reshape((-1, 1)) * self.components_,
357
+ X,
358
+ mean_correction,
359
+ )
360
+ )
361
+
362
+ U, S, Vt = linalg.svd(X, full_matrices=False, check_finite=False)
363
+ U, Vt = svd_flip(U, Vt, u_based_decision=False)
364
+ explained_variance = S**2 / (n_total_samples - 1)
365
+ explained_variance_ratio = S**2 / np.sum(col_var * n_total_samples)
366
+
367
+ self.n_samples_seen_ = n_total_samples
368
+ self.components_ = Vt[: self.n_components_]
369
+ self.singular_values_ = S[: self.n_components_]
370
+ self.mean_ = col_mean
371
+ self.var_ = col_var
372
+ self.explained_variance_ = explained_variance[: self.n_components_]
373
+ self.explained_variance_ratio_ = explained_variance_ratio[: self.n_components_]
374
+ # we already checked `self.n_components <= n_samples` above
375
+ if self.n_components_ not in (n_samples, n_features):
376
+ self.noise_variance_ = explained_variance[self.n_components_ :].mean()
377
+ else:
378
+ self.noise_variance_ = 0.0
379
+ return self
380
+
381
+ def transform(self, X):
382
+ """Apply dimensionality reduction to X.
383
+
384
+ X is projected on the first principal components previously extracted
385
+ from a training set, using minibatches of size batch_size if X is
386
+ sparse.
387
+
388
+ Parameters
389
+ ----------
390
+ X : {array-like, sparse matrix} of shape (n_samples, n_features)
391
+ New data, where `n_samples` is the number of samples
392
+ and `n_features` is the number of features.
393
+
394
+ Returns
395
+ -------
396
+ X_new : ndarray of shape (n_samples, n_components)
397
+ Projection of X in the first principal components.
398
+
399
+ Examples
400
+ --------
401
+
402
+ >>> import numpy as np
403
+ >>> from sklearn.decomposition import IncrementalPCA
404
+ >>> X = np.array([[-1, -1], [-2, -1], [-3, -2],
405
+ ... [1, 1], [2, 1], [3, 2]])
406
+ >>> ipca = IncrementalPCA(n_components=2, batch_size=3)
407
+ >>> ipca.fit(X)
408
+ IncrementalPCA(batch_size=3, n_components=2)
409
+ >>> ipca.transform(X) # doctest: +SKIP
410
+ """
411
+ if sparse.issparse(X):
412
+ n_samples = X.shape[0]
413
+ output = []
414
+ for batch in gen_batches(
415
+ n_samples, self.batch_size_, min_batch_size=self.n_components or 0
416
+ ):
417
+ output.append(super().transform(X[batch].toarray()))
418
+ return np.vstack(output)
419
+ else:
420
+ return super().transform(X)
421
+
422
+ def __sklearn_tags__(self):
423
+ tags = super().__sklearn_tags__()
424
+ # Beware that fit accepts sparse data but partial_fit doesn't
425
+ tags.input_tags.sparse = True
426
+ return tags