Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/datasets/_arff_parser.py +543 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/datasets/_base.py +1636 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/datasets/_california_housing.py +248 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/datasets/_covtype.py +252 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/datasets/_kddcup99.py +429 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/datasets/_lfw.py +648 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/datasets/_olivetti_faces.py +184 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/datasets/_openml.py +1164 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/datasets/_rcv1.py +334 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/datasets/_samples_generator.py +2383 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/datasets/_species_distributions.py +289 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/datasets/_svmlight_format_fast.pyx +252 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/datasets/_svmlight_format_io.py +585 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/datasets/_twenty_newsgroups.py +625 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/datasets/data/__init__.py +2 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/datasets/data/breast_cancer.csv +0 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/datasets/data/iris.csv +151 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/datasets/data/linnerud_exercise.csv +21 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/datasets/data/linnerud_physiological.csv +21 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/datasets/data/wine_data.csv +179 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/datasets/descr/__init__.py +2 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/datasets/descr/breast_cancer.rst +118 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/datasets/descr/california_housing.rst +46 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/datasets/descr/covtype.rst +30 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/datasets/descr/diabetes.rst +38 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/datasets/descr/digits.rst +46 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/datasets/descr/iris.rst +63 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/datasets/descr/kddcup99.rst +94 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/datasets/descr/lfw.rst +124 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/datasets/descr/linnerud.rst +24 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/datasets/descr/olivetti_faces.rst +44 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/datasets/descr/rcv1.rst +72 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/datasets/descr/species_distributions.rst +40 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/datasets/descr/twenty_newsgroups.rst +248 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/datasets/descr/wine_data.rst +94 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/datasets/images/README.txt +18 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/datasets/images/__init__.py +2 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/datasets/meson.build +7 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/datasets/tests/__init__.py +0 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/datasets/tests/data/__init__.py +0 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/datasets/tests/data/openml/__init__.py +0 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/datasets/tests/data/openml/id_1/__init__.py +0 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/datasets/tests/data/openml/id_1119/__init__.py +0 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/datasets/tests/data/openml/id_1590/__init__.py +0 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/datasets/tests/data/openml/id_2/__init__.py +0 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/datasets/tests/data/openml/id_292/__init__.py +0 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/datasets/tests/data/openml/id_3/__init__.py +0 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/datasets/tests/data/openml/id_40589/__init__.py +0 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/datasets/tests/data/openml/id_40675/__init__.py +0 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/datasets/tests/data/openml/id_40945/__init__.py +0 -0
miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/datasets/_arff_parser.py
ADDED
|
@@ -0,0 +1,543 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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itertools
|
| 7 |
+
import re
|
| 8 |
+
from collections import OrderedDict
|
| 9 |
+
from collections.abc import Generator
|
| 10 |
+
from typing import List
|
| 11 |
+
|
| 12 |
+
import numpy as np
|
| 13 |
+
import scipy as sp
|
| 14 |
+
|
| 15 |
+
from ..externals import _arff
|
| 16 |
+
from ..externals._arff import ArffSparseDataType
|
| 17 |
+
from ..utils._chunking import chunk_generator, get_chunk_n_rows
|
| 18 |
+
from ..utils._optional_dependencies import check_pandas_support
|
| 19 |
+
from ..utils.fixes import pd_fillna
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def _split_sparse_columns(
|
| 23 |
+
arff_data: ArffSparseDataType, include_columns: List
|
| 24 |
+
) -> ArffSparseDataType:
|
| 25 |
+
"""Obtains several columns from sparse ARFF representation. Additionally,
|
| 26 |
+
the column indices are re-labelled, given the columns that are not
|
| 27 |
+
included. (e.g., when including [1, 2, 3], the columns will be relabelled
|
| 28 |
+
to [0, 1, 2]).
|
| 29 |
+
|
| 30 |
+
Parameters
|
| 31 |
+
----------
|
| 32 |
+
arff_data : tuple
|
| 33 |
+
A tuple of three lists of equal size; first list indicating the value,
|
| 34 |
+
second the x coordinate and the third the y coordinate.
|
| 35 |
+
|
| 36 |
+
include_columns : list
|
| 37 |
+
A list of columns to include.
|
| 38 |
+
|
| 39 |
+
Returns
|
| 40 |
+
-------
|
| 41 |
+
arff_data_new : tuple
|
| 42 |
+
Subset of arff data with only the include columns indicated by the
|
| 43 |
+
include_columns argument.
|
| 44 |
+
"""
|
| 45 |
+
arff_data_new: ArffSparseDataType = (list(), list(), list())
|
| 46 |
+
reindexed_columns = {
|
| 47 |
+
column_idx: array_idx for array_idx, column_idx in enumerate(include_columns)
|
| 48 |
+
}
|
| 49 |
+
for val, row_idx, col_idx in zip(arff_data[0], arff_data[1], arff_data[2]):
|
| 50 |
+
if col_idx in include_columns:
|
| 51 |
+
arff_data_new[0].append(val)
|
| 52 |
+
arff_data_new[1].append(row_idx)
|
| 53 |
+
arff_data_new[2].append(reindexed_columns[col_idx])
|
| 54 |
+
return arff_data_new
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def _sparse_data_to_array(
|
| 58 |
+
arff_data: ArffSparseDataType, include_columns: List
|
| 59 |
+
) -> np.ndarray:
|
| 60 |
+
# turns the sparse data back into an array (can't use toarray() function,
|
| 61 |
+
# as this does only work on numeric data)
|
| 62 |
+
num_obs = max(arff_data[1]) + 1
|
| 63 |
+
y_shape = (num_obs, len(include_columns))
|
| 64 |
+
reindexed_columns = {
|
| 65 |
+
column_idx: array_idx for array_idx, column_idx in enumerate(include_columns)
|
| 66 |
+
}
|
| 67 |
+
# TODO: improve for efficiency
|
| 68 |
+
y = np.empty(y_shape, dtype=np.float64)
|
| 69 |
+
for val, row_idx, col_idx in zip(arff_data[0], arff_data[1], arff_data[2]):
|
| 70 |
+
if col_idx in include_columns:
|
| 71 |
+
y[row_idx, reindexed_columns[col_idx]] = val
|
| 72 |
+
return y
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def _post_process_frame(frame, feature_names, target_names):
|
| 76 |
+
"""Post process a dataframe to select the desired columns in `X` and `y`.
|
| 77 |
+
|
| 78 |
+
Parameters
|
| 79 |
+
----------
|
| 80 |
+
frame : dataframe
|
| 81 |
+
The dataframe to split into `X` and `y`.
|
| 82 |
+
|
| 83 |
+
feature_names : list of str
|
| 84 |
+
The list of feature names to populate `X`.
|
| 85 |
+
|
| 86 |
+
target_names : list of str
|
| 87 |
+
The list of target names to populate `y`.
|
| 88 |
+
|
| 89 |
+
Returns
|
| 90 |
+
-------
|
| 91 |
+
X : dataframe
|
| 92 |
+
The dataframe containing the features.
|
| 93 |
+
|
| 94 |
+
y : {series, dataframe} or None
|
| 95 |
+
The series or dataframe containing the target.
|
| 96 |
+
"""
|
| 97 |
+
X = frame[feature_names]
|
| 98 |
+
if len(target_names) >= 2:
|
| 99 |
+
y = frame[target_names]
|
| 100 |
+
elif len(target_names) == 1:
|
| 101 |
+
y = frame[target_names[0]]
|
| 102 |
+
else:
|
| 103 |
+
y = None
|
| 104 |
+
return X, y
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def _liac_arff_parser(
|
| 108 |
+
gzip_file,
|
| 109 |
+
output_arrays_type,
|
| 110 |
+
openml_columns_info,
|
| 111 |
+
feature_names_to_select,
|
| 112 |
+
target_names_to_select,
|
| 113 |
+
shape=None,
|
| 114 |
+
):
|
| 115 |
+
"""ARFF parser using the LIAC-ARFF library coded purely in Python.
|
| 116 |
+
|
| 117 |
+
This parser is quite slow but consumes a generator. Currently it is needed
|
| 118 |
+
to parse sparse datasets. For dense datasets, it is recommended to instead
|
| 119 |
+
use the pandas-based parser, although it does not always handles the
|
| 120 |
+
dtypes exactly the same.
|
| 121 |
+
|
| 122 |
+
Parameters
|
| 123 |
+
----------
|
| 124 |
+
gzip_file : GzipFile instance
|
| 125 |
+
The file compressed to be read.
|
| 126 |
+
|
| 127 |
+
output_arrays_type : {"numpy", "sparse", "pandas"}
|
| 128 |
+
The type of the arrays that will be returned. The possibilities ara:
|
| 129 |
+
|
| 130 |
+
- `"numpy"`: both `X` and `y` will be NumPy arrays;
|
| 131 |
+
- `"sparse"`: `X` will be sparse matrix and `y` will be a NumPy array;
|
| 132 |
+
- `"pandas"`: `X` will be a pandas DataFrame and `y` will be either a
|
| 133 |
+
pandas Series or DataFrame.
|
| 134 |
+
|
| 135 |
+
columns_info : dict
|
| 136 |
+
The information provided by OpenML regarding the columns of the ARFF
|
| 137 |
+
file.
|
| 138 |
+
|
| 139 |
+
feature_names_to_select : list of str
|
| 140 |
+
A list of the feature names to be selected.
|
| 141 |
+
|
| 142 |
+
target_names_to_select : list of str
|
| 143 |
+
A list of the target names to be selected.
|
| 144 |
+
|
| 145 |
+
Returns
|
| 146 |
+
-------
|
| 147 |
+
X : {ndarray, sparse matrix, dataframe}
|
| 148 |
+
The data matrix.
|
| 149 |
+
|
| 150 |
+
y : {ndarray, dataframe, series}
|
| 151 |
+
The target.
|
| 152 |
+
|
| 153 |
+
frame : dataframe or None
|
| 154 |
+
A dataframe containing both `X` and `y`. `None` if
|
| 155 |
+
`output_array_type != "pandas"`.
|
| 156 |
+
|
| 157 |
+
categories : list of str or None
|
| 158 |
+
The names of the features that are categorical. `None` if
|
| 159 |
+
`output_array_type == "pandas"`.
|
| 160 |
+
"""
|
| 161 |
+
|
| 162 |
+
def _io_to_generator(gzip_file):
|
| 163 |
+
for line in gzip_file:
|
| 164 |
+
yield line.decode("utf-8")
|
| 165 |
+
|
| 166 |
+
stream = _io_to_generator(gzip_file)
|
| 167 |
+
|
| 168 |
+
# find which type (dense or sparse) ARFF type we will have to deal with
|
| 169 |
+
return_type = _arff.COO if output_arrays_type == "sparse" else _arff.DENSE_GEN
|
| 170 |
+
# we should not let LIAC-ARFF to encode the nominal attributes with NumPy
|
| 171 |
+
# arrays to have only numerical values.
|
| 172 |
+
encode_nominal = not (output_arrays_type == "pandas")
|
| 173 |
+
arff_container = _arff.load(
|
| 174 |
+
stream, return_type=return_type, encode_nominal=encode_nominal
|
| 175 |
+
)
|
| 176 |
+
columns_to_select = feature_names_to_select + target_names_to_select
|
| 177 |
+
|
| 178 |
+
categories = {
|
| 179 |
+
name: cat
|
| 180 |
+
for name, cat in arff_container["attributes"]
|
| 181 |
+
if isinstance(cat, list) and name in columns_to_select
|
| 182 |
+
}
|
| 183 |
+
if output_arrays_type == "pandas":
|
| 184 |
+
pd = check_pandas_support("fetch_openml with as_frame=True")
|
| 185 |
+
|
| 186 |
+
columns_info = OrderedDict(arff_container["attributes"])
|
| 187 |
+
columns_names = list(columns_info.keys())
|
| 188 |
+
|
| 189 |
+
# calculate chunksize
|
| 190 |
+
first_row = next(arff_container["data"])
|
| 191 |
+
first_df = pd.DataFrame([first_row], columns=columns_names, copy=False)
|
| 192 |
+
|
| 193 |
+
row_bytes = first_df.memory_usage(deep=True).sum()
|
| 194 |
+
chunksize = get_chunk_n_rows(row_bytes)
|
| 195 |
+
|
| 196 |
+
# read arff data with chunks
|
| 197 |
+
columns_to_keep = [col for col in columns_names if col in columns_to_select]
|
| 198 |
+
dfs = [first_df[columns_to_keep]]
|
| 199 |
+
for data in chunk_generator(arff_container["data"], chunksize):
|
| 200 |
+
dfs.append(
|
| 201 |
+
pd.DataFrame(data, columns=columns_names, copy=False)[columns_to_keep]
|
| 202 |
+
)
|
| 203 |
+
# dfs[0] contains only one row, which may not have enough data to infer to
|
| 204 |
+
# column's dtype. Here we use `dfs[1]` to configure the dtype in dfs[0]
|
| 205 |
+
if len(dfs) >= 2:
|
| 206 |
+
dfs[0] = dfs[0].astype(dfs[1].dtypes)
|
| 207 |
+
|
| 208 |
+
# liac-arff parser does not depend on NumPy and uses None to represent
|
| 209 |
+
# missing values. To be consistent with the pandas parser, we replace
|
| 210 |
+
# None with np.nan.
|
| 211 |
+
frame = pd.concat(dfs, ignore_index=True)
|
| 212 |
+
frame = pd_fillna(pd, frame)
|
| 213 |
+
del dfs, first_df
|
| 214 |
+
|
| 215 |
+
# cast the columns frame
|
| 216 |
+
dtypes = {}
|
| 217 |
+
for name in frame.columns:
|
| 218 |
+
column_dtype = openml_columns_info[name]["data_type"]
|
| 219 |
+
if column_dtype.lower() == "integer":
|
| 220 |
+
# Use a pandas extension array instead of np.int64 to be able
|
| 221 |
+
# to support missing values.
|
| 222 |
+
dtypes[name] = "Int64"
|
| 223 |
+
elif column_dtype.lower() == "nominal":
|
| 224 |
+
dtypes[name] = "category"
|
| 225 |
+
else:
|
| 226 |
+
dtypes[name] = frame.dtypes[name]
|
| 227 |
+
frame = frame.astype(dtypes)
|
| 228 |
+
|
| 229 |
+
X, y = _post_process_frame(
|
| 230 |
+
frame, feature_names_to_select, target_names_to_select
|
| 231 |
+
)
|
| 232 |
+
else:
|
| 233 |
+
arff_data = arff_container["data"]
|
| 234 |
+
|
| 235 |
+
feature_indices_to_select = [
|
| 236 |
+
int(openml_columns_info[col_name]["index"])
|
| 237 |
+
for col_name in feature_names_to_select
|
| 238 |
+
]
|
| 239 |
+
target_indices_to_select = [
|
| 240 |
+
int(openml_columns_info[col_name]["index"])
|
| 241 |
+
for col_name in target_names_to_select
|
| 242 |
+
]
|
| 243 |
+
|
| 244 |
+
if isinstance(arff_data, Generator):
|
| 245 |
+
if shape is None:
|
| 246 |
+
raise ValueError(
|
| 247 |
+
"shape must be provided when arr['data'] is a Generator"
|
| 248 |
+
)
|
| 249 |
+
if shape[0] == -1:
|
| 250 |
+
count = -1
|
| 251 |
+
else:
|
| 252 |
+
count = shape[0] * shape[1]
|
| 253 |
+
data = np.fromiter(
|
| 254 |
+
itertools.chain.from_iterable(arff_data),
|
| 255 |
+
dtype="float64",
|
| 256 |
+
count=count,
|
| 257 |
+
)
|
| 258 |
+
data = data.reshape(*shape)
|
| 259 |
+
X = data[:, feature_indices_to_select]
|
| 260 |
+
y = data[:, target_indices_to_select]
|
| 261 |
+
elif isinstance(arff_data, tuple):
|
| 262 |
+
arff_data_X = _split_sparse_columns(arff_data, feature_indices_to_select)
|
| 263 |
+
num_obs = max(arff_data[1]) + 1
|
| 264 |
+
X_shape = (num_obs, len(feature_indices_to_select))
|
| 265 |
+
X = sp.sparse.coo_matrix(
|
| 266 |
+
(arff_data_X[0], (arff_data_X[1], arff_data_X[2])),
|
| 267 |
+
shape=X_shape,
|
| 268 |
+
dtype=np.float64,
|
| 269 |
+
)
|
| 270 |
+
X = X.tocsr()
|
| 271 |
+
y = _sparse_data_to_array(arff_data, target_indices_to_select)
|
| 272 |
+
else:
|
| 273 |
+
# This should never happen
|
| 274 |
+
raise ValueError(
|
| 275 |
+
f"Unexpected type for data obtained from arff: {type(arff_data)}"
|
| 276 |
+
)
|
| 277 |
+
|
| 278 |
+
is_classification = {
|
| 279 |
+
col_name in categories for col_name in target_names_to_select
|
| 280 |
+
}
|
| 281 |
+
if not is_classification:
|
| 282 |
+
# No target
|
| 283 |
+
pass
|
| 284 |
+
elif all(is_classification):
|
| 285 |
+
y = np.hstack(
|
| 286 |
+
[
|
| 287 |
+
np.take(
|
| 288 |
+
np.asarray(categories.pop(col_name), dtype="O"),
|
| 289 |
+
y[:, i : i + 1].astype(int, copy=False),
|
| 290 |
+
)
|
| 291 |
+
for i, col_name in enumerate(target_names_to_select)
|
| 292 |
+
]
|
| 293 |
+
)
|
| 294 |
+
elif any(is_classification):
|
| 295 |
+
raise ValueError(
|
| 296 |
+
"Mix of nominal and non-nominal targets is not currently supported"
|
| 297 |
+
)
|
| 298 |
+
|
| 299 |
+
# reshape y back to 1-D array, if there is only 1 target column;
|
| 300 |
+
# back to None if there are not target columns
|
| 301 |
+
if y.shape[1] == 1:
|
| 302 |
+
y = y.reshape((-1,))
|
| 303 |
+
elif y.shape[1] == 0:
|
| 304 |
+
y = None
|
| 305 |
+
|
| 306 |
+
if output_arrays_type == "pandas":
|
| 307 |
+
return X, y, frame, None
|
| 308 |
+
return X, y, None, categories
|
| 309 |
+
|
| 310 |
+
|
| 311 |
+
def _pandas_arff_parser(
|
| 312 |
+
gzip_file,
|
| 313 |
+
output_arrays_type,
|
| 314 |
+
openml_columns_info,
|
| 315 |
+
feature_names_to_select,
|
| 316 |
+
target_names_to_select,
|
| 317 |
+
read_csv_kwargs=None,
|
| 318 |
+
):
|
| 319 |
+
"""ARFF parser using `pandas.read_csv`.
|
| 320 |
+
|
| 321 |
+
This parser uses the metadata fetched directly from OpenML and skips the metadata
|
| 322 |
+
headers of ARFF file itself. The data is loaded as a CSV file.
|
| 323 |
+
|
| 324 |
+
Parameters
|
| 325 |
+
----------
|
| 326 |
+
gzip_file : GzipFile instance
|
| 327 |
+
The GZip compressed file with the ARFF formatted payload.
|
| 328 |
+
|
| 329 |
+
output_arrays_type : {"numpy", "sparse", "pandas"}
|
| 330 |
+
The type of the arrays that will be returned. The possibilities are:
|
| 331 |
+
|
| 332 |
+
- `"numpy"`: both `X` and `y` will be NumPy arrays;
|
| 333 |
+
- `"sparse"`: `X` will be sparse matrix and `y` will be a NumPy array;
|
| 334 |
+
- `"pandas"`: `X` will be a pandas DataFrame and `y` will be either a
|
| 335 |
+
pandas Series or DataFrame.
|
| 336 |
+
|
| 337 |
+
openml_columns_info : dict
|
| 338 |
+
The information provided by OpenML regarding the columns of the ARFF
|
| 339 |
+
file.
|
| 340 |
+
|
| 341 |
+
feature_names_to_select : list of str
|
| 342 |
+
A list of the feature names to be selected to build `X`.
|
| 343 |
+
|
| 344 |
+
target_names_to_select : list of str
|
| 345 |
+
A list of the target names to be selected to build `y`.
|
| 346 |
+
|
| 347 |
+
read_csv_kwargs : dict, default=None
|
| 348 |
+
Keyword arguments to pass to `pandas.read_csv`. It allows to overwrite
|
| 349 |
+
the default options.
|
| 350 |
+
|
| 351 |
+
Returns
|
| 352 |
+
-------
|
| 353 |
+
X : {ndarray, sparse matrix, dataframe}
|
| 354 |
+
The data matrix.
|
| 355 |
+
|
| 356 |
+
y : {ndarray, dataframe, series}
|
| 357 |
+
The target.
|
| 358 |
+
|
| 359 |
+
frame : dataframe or None
|
| 360 |
+
A dataframe containing both `X` and `y`. `None` if
|
| 361 |
+
`output_array_type != "pandas"`.
|
| 362 |
+
|
| 363 |
+
categories : list of str or None
|
| 364 |
+
The names of the features that are categorical. `None` if
|
| 365 |
+
`output_array_type == "pandas"`.
|
| 366 |
+
"""
|
| 367 |
+
import pandas as pd
|
| 368 |
+
|
| 369 |
+
# read the file until the data section to skip the ARFF metadata headers
|
| 370 |
+
for line in gzip_file:
|
| 371 |
+
if line.decode("utf-8").lower().startswith("@data"):
|
| 372 |
+
break
|
| 373 |
+
|
| 374 |
+
dtypes = {}
|
| 375 |
+
for name in openml_columns_info:
|
| 376 |
+
column_dtype = openml_columns_info[name]["data_type"]
|
| 377 |
+
if column_dtype.lower() == "integer":
|
| 378 |
+
# Use Int64 to infer missing values from data
|
| 379 |
+
# XXX: this line is not covered by our tests. Is this really needed?
|
| 380 |
+
dtypes[name] = "Int64"
|
| 381 |
+
elif column_dtype.lower() == "nominal":
|
| 382 |
+
dtypes[name] = "category"
|
| 383 |
+
# since we will not pass `names` when reading the ARFF file, we need to translate
|
| 384 |
+
# `dtypes` from column names to column indices to pass to `pandas.read_csv`
|
| 385 |
+
dtypes_positional = {
|
| 386 |
+
col_idx: dtypes[name]
|
| 387 |
+
for col_idx, name in enumerate(openml_columns_info)
|
| 388 |
+
if name in dtypes
|
| 389 |
+
}
|
| 390 |
+
|
| 391 |
+
default_read_csv_kwargs = {
|
| 392 |
+
"header": None,
|
| 393 |
+
"index_col": False, # always force pandas to not use the first column as index
|
| 394 |
+
"na_values": ["?"], # missing values are represented by `?`
|
| 395 |
+
"keep_default_na": False, # only `?` is a missing value given the ARFF specs
|
| 396 |
+
"comment": "%", # skip line starting by `%` since they are comments
|
| 397 |
+
"quotechar": '"', # delimiter to use for quoted strings
|
| 398 |
+
"skipinitialspace": True, # skip spaces after delimiter to follow ARFF specs
|
| 399 |
+
"escapechar": "\\",
|
| 400 |
+
"dtype": dtypes_positional,
|
| 401 |
+
}
|
| 402 |
+
read_csv_kwargs = {**default_read_csv_kwargs, **(read_csv_kwargs or {})}
|
| 403 |
+
frame = pd.read_csv(gzip_file, **read_csv_kwargs)
|
| 404 |
+
try:
|
| 405 |
+
# Setting the columns while reading the file will select the N first columns
|
| 406 |
+
# and not raise a ParserError. Instead, we set the columns after reading the
|
| 407 |
+
# file and raise a ParserError if the number of columns does not match the
|
| 408 |
+
# number of columns in the metadata given by OpenML.
|
| 409 |
+
frame.columns = [name for name in openml_columns_info]
|
| 410 |
+
except ValueError as exc:
|
| 411 |
+
raise pd.errors.ParserError(
|
| 412 |
+
"The number of columns provided by OpenML does not match the number of "
|
| 413 |
+
"columns inferred by pandas when reading the file."
|
| 414 |
+
) from exc
|
| 415 |
+
|
| 416 |
+
columns_to_select = feature_names_to_select + target_names_to_select
|
| 417 |
+
columns_to_keep = [col for col in frame.columns if col in columns_to_select]
|
| 418 |
+
frame = frame[columns_to_keep]
|
| 419 |
+
|
| 420 |
+
# `pd.read_csv` automatically handles double quotes for quoting non-numeric
|
| 421 |
+
# CSV cell values. Contrary to LIAC-ARFF, `pd.read_csv` cannot be configured to
|
| 422 |
+
# consider either single quotes and double quotes as valid quoting chars at
|
| 423 |
+
# the same time since this case does not occur in regular (non-ARFF) CSV files.
|
| 424 |
+
# To mimic the behavior of LIAC-ARFF parser, we manually strip single quotes
|
| 425 |
+
# on categories as a post-processing steps if needed.
|
| 426 |
+
#
|
| 427 |
+
# Note however that we intentionally do not attempt to do this kind of manual
|
| 428 |
+
# post-processing of (non-categorical) string-typed columns because we cannot
|
| 429 |
+
# resolve the ambiguity of the case of CSV cell with nesting quoting such as
|
| 430 |
+
# `"'some string value'"` with pandas.
|
| 431 |
+
single_quote_pattern = re.compile(r"^'(?P<contents>.*)'$")
|
| 432 |
+
|
| 433 |
+
def strip_single_quotes(input_string):
|
| 434 |
+
match = re.search(single_quote_pattern, input_string)
|
| 435 |
+
if match is None:
|
| 436 |
+
return input_string
|
| 437 |
+
|
| 438 |
+
return match.group("contents")
|
| 439 |
+
|
| 440 |
+
categorical_columns = [
|
| 441 |
+
name
|
| 442 |
+
for name, dtype in frame.dtypes.items()
|
| 443 |
+
if isinstance(dtype, pd.CategoricalDtype)
|
| 444 |
+
]
|
| 445 |
+
for col in categorical_columns:
|
| 446 |
+
frame[col] = frame[col].cat.rename_categories(strip_single_quotes)
|
| 447 |
+
|
| 448 |
+
X, y = _post_process_frame(frame, feature_names_to_select, target_names_to_select)
|
| 449 |
+
|
| 450 |
+
if output_arrays_type == "pandas":
|
| 451 |
+
return X, y, frame, None
|
| 452 |
+
else:
|
| 453 |
+
X, y = X.to_numpy(), y.to_numpy()
|
| 454 |
+
|
| 455 |
+
categories = {
|
| 456 |
+
name: dtype.categories.tolist()
|
| 457 |
+
for name, dtype in frame.dtypes.items()
|
| 458 |
+
if isinstance(dtype, pd.CategoricalDtype)
|
| 459 |
+
}
|
| 460 |
+
return X, y, None, categories
|
| 461 |
+
|
| 462 |
+
|
| 463 |
+
def load_arff_from_gzip_file(
|
| 464 |
+
gzip_file,
|
| 465 |
+
parser,
|
| 466 |
+
output_type,
|
| 467 |
+
openml_columns_info,
|
| 468 |
+
feature_names_to_select,
|
| 469 |
+
target_names_to_select,
|
| 470 |
+
shape=None,
|
| 471 |
+
read_csv_kwargs=None,
|
| 472 |
+
):
|
| 473 |
+
"""Load a compressed ARFF file using a given parser.
|
| 474 |
+
|
| 475 |
+
Parameters
|
| 476 |
+
----------
|
| 477 |
+
gzip_file : GzipFile instance
|
| 478 |
+
The file compressed to be read.
|
| 479 |
+
|
| 480 |
+
parser : {"pandas", "liac-arff"}
|
| 481 |
+
The parser used to parse the ARFF file. "pandas" is recommended
|
| 482 |
+
but only supports loading dense datasets.
|
| 483 |
+
|
| 484 |
+
output_type : {"numpy", "sparse", "pandas"}
|
| 485 |
+
The type of the arrays that will be returned. The possibilities ara:
|
| 486 |
+
|
| 487 |
+
- `"numpy"`: both `X` and `y` will be NumPy arrays;
|
| 488 |
+
- `"sparse"`: `X` will be sparse matrix and `y` will be a NumPy array;
|
| 489 |
+
- `"pandas"`: `X` will be a pandas DataFrame and `y` will be either a
|
| 490 |
+
pandas Series or DataFrame.
|
| 491 |
+
|
| 492 |
+
openml_columns_info : dict
|
| 493 |
+
The information provided by OpenML regarding the columns of the ARFF
|
| 494 |
+
file.
|
| 495 |
+
|
| 496 |
+
feature_names_to_select : list of str
|
| 497 |
+
A list of the feature names to be selected.
|
| 498 |
+
|
| 499 |
+
target_names_to_select : list of str
|
| 500 |
+
A list of the target names to be selected.
|
| 501 |
+
|
| 502 |
+
read_csv_kwargs : dict, default=None
|
| 503 |
+
Keyword arguments to pass to `pandas.read_csv`. It allows to overwrite
|
| 504 |
+
the default options.
|
| 505 |
+
|
| 506 |
+
Returns
|
| 507 |
+
-------
|
| 508 |
+
X : {ndarray, sparse matrix, dataframe}
|
| 509 |
+
The data matrix.
|
| 510 |
+
|
| 511 |
+
y : {ndarray, dataframe, series}
|
| 512 |
+
The target.
|
| 513 |
+
|
| 514 |
+
frame : dataframe or None
|
| 515 |
+
A dataframe containing both `X` and `y`. `None` if
|
| 516 |
+
`output_array_type != "pandas"`.
|
| 517 |
+
|
| 518 |
+
categories : list of str or None
|
| 519 |
+
The names of the features that are categorical. `None` if
|
| 520 |
+
`output_array_type == "pandas"`.
|
| 521 |
+
"""
|
| 522 |
+
if parser == "liac-arff":
|
| 523 |
+
return _liac_arff_parser(
|
| 524 |
+
gzip_file,
|
| 525 |
+
output_type,
|
| 526 |
+
openml_columns_info,
|
| 527 |
+
feature_names_to_select,
|
| 528 |
+
target_names_to_select,
|
| 529 |
+
shape,
|
| 530 |
+
)
|
| 531 |
+
elif parser == "pandas":
|
| 532 |
+
return _pandas_arff_parser(
|
| 533 |
+
gzip_file,
|
| 534 |
+
output_type,
|
| 535 |
+
openml_columns_info,
|
| 536 |
+
feature_names_to_select,
|
| 537 |
+
target_names_to_select,
|
| 538 |
+
read_csv_kwargs,
|
| 539 |
+
)
|
| 540 |
+
else:
|
| 541 |
+
raise ValueError(
|
| 542 |
+
f"Unknown parser: '{parser}'. Should be 'liac-arff' or 'pandas'."
|
| 543 |
+
)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/datasets/_base.py
ADDED
|
@@ -0,0 +1,1636 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Base IO code for all datasets
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
# Authors: The scikit-learn developers
|
| 6 |
+
# SPDX-License-Identifier: BSD-3-Clause
|
| 7 |
+
|
| 8 |
+
import csv
|
| 9 |
+
import gzip
|
| 10 |
+
import hashlib
|
| 11 |
+
import os
|
| 12 |
+
import re
|
| 13 |
+
import shutil
|
| 14 |
+
import time
|
| 15 |
+
import unicodedata
|
| 16 |
+
import warnings
|
| 17 |
+
from collections import namedtuple
|
| 18 |
+
from importlib import resources
|
| 19 |
+
from numbers import Integral
|
| 20 |
+
from os import environ, listdir, makedirs
|
| 21 |
+
from os.path import expanduser, isdir, join, splitext
|
| 22 |
+
from pathlib import Path
|
| 23 |
+
from tempfile import NamedTemporaryFile
|
| 24 |
+
from urllib.error import URLError
|
| 25 |
+
from urllib.parse import urlparse
|
| 26 |
+
from urllib.request import urlretrieve
|
| 27 |
+
|
| 28 |
+
import numpy as np
|
| 29 |
+
|
| 30 |
+
from ..preprocessing import scale
|
| 31 |
+
from ..utils import Bunch, check_random_state
|
| 32 |
+
from ..utils._optional_dependencies import check_pandas_support
|
| 33 |
+
from ..utils._param_validation import Interval, StrOptions, validate_params
|
| 34 |
+
|
| 35 |
+
DATA_MODULE = "sklearn.datasets.data"
|
| 36 |
+
DESCR_MODULE = "sklearn.datasets.descr"
|
| 37 |
+
IMAGES_MODULE = "sklearn.datasets.images"
|
| 38 |
+
|
| 39 |
+
RemoteFileMetadata = namedtuple("RemoteFileMetadata", ["filename", "url", "checksum"])
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
@validate_params(
|
| 43 |
+
{
|
| 44 |
+
"data_home": [str, os.PathLike, None],
|
| 45 |
+
},
|
| 46 |
+
prefer_skip_nested_validation=True,
|
| 47 |
+
)
|
| 48 |
+
def get_data_home(data_home=None) -> str:
|
| 49 |
+
"""Return the path of the scikit-learn data directory.
|
| 50 |
+
|
| 51 |
+
This folder is used by some large dataset loaders to avoid downloading the
|
| 52 |
+
data several times.
|
| 53 |
+
|
| 54 |
+
By default the data directory is set to a folder named 'scikit_learn_data' in the
|
| 55 |
+
user home folder.
|
| 56 |
+
|
| 57 |
+
Alternatively, it can be set by the 'SCIKIT_LEARN_DATA' environment
|
| 58 |
+
variable or programmatically by giving an explicit folder path. The '~'
|
| 59 |
+
symbol is expanded to the user home folder.
|
| 60 |
+
|
| 61 |
+
If the folder does not already exist, it is automatically created.
|
| 62 |
+
|
| 63 |
+
Parameters
|
| 64 |
+
----------
|
| 65 |
+
data_home : str or path-like, default=None
|
| 66 |
+
The path to scikit-learn data directory. If `None`, the default path
|
| 67 |
+
is `~/scikit_learn_data`.
|
| 68 |
+
|
| 69 |
+
Returns
|
| 70 |
+
-------
|
| 71 |
+
data_home: str
|
| 72 |
+
The path to scikit-learn data directory.
|
| 73 |
+
|
| 74 |
+
Examples
|
| 75 |
+
--------
|
| 76 |
+
>>> import os
|
| 77 |
+
>>> from sklearn.datasets import get_data_home
|
| 78 |
+
>>> data_home_path = get_data_home()
|
| 79 |
+
>>> os.path.exists(data_home_path)
|
| 80 |
+
True
|
| 81 |
+
"""
|
| 82 |
+
if data_home is None:
|
| 83 |
+
data_home = environ.get("SCIKIT_LEARN_DATA", join("~", "scikit_learn_data"))
|
| 84 |
+
data_home = expanduser(data_home)
|
| 85 |
+
makedirs(data_home, exist_ok=True)
|
| 86 |
+
return data_home
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
@validate_params(
|
| 90 |
+
{
|
| 91 |
+
"data_home": [str, os.PathLike, None],
|
| 92 |
+
},
|
| 93 |
+
prefer_skip_nested_validation=True,
|
| 94 |
+
)
|
| 95 |
+
def clear_data_home(data_home=None):
|
| 96 |
+
"""Delete all the content of the data home cache.
|
| 97 |
+
|
| 98 |
+
Parameters
|
| 99 |
+
----------
|
| 100 |
+
data_home : str or path-like, default=None
|
| 101 |
+
The path to scikit-learn data directory. If `None`, the default path
|
| 102 |
+
is `~/scikit_learn_data`.
|
| 103 |
+
|
| 104 |
+
Examples
|
| 105 |
+
--------
|
| 106 |
+
>>> from sklearn.datasets import clear_data_home
|
| 107 |
+
>>> clear_data_home() # doctest: +SKIP
|
| 108 |
+
"""
|
| 109 |
+
data_home = get_data_home(data_home)
|
| 110 |
+
shutil.rmtree(data_home)
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def _convert_data_dataframe(
|
| 114 |
+
caller_name, data, target, feature_names, target_names, sparse_data=False
|
| 115 |
+
):
|
| 116 |
+
pd = check_pandas_support("{} with as_frame=True".format(caller_name))
|
| 117 |
+
if not sparse_data:
|
| 118 |
+
data_df = pd.DataFrame(data, columns=feature_names, copy=False)
|
| 119 |
+
else:
|
| 120 |
+
data_df = pd.DataFrame.sparse.from_spmatrix(data, columns=feature_names)
|
| 121 |
+
|
| 122 |
+
target_df = pd.DataFrame(target, columns=target_names)
|
| 123 |
+
combined_df = pd.concat([data_df, target_df], axis=1)
|
| 124 |
+
X = combined_df[feature_names]
|
| 125 |
+
y = combined_df[target_names]
|
| 126 |
+
if y.shape[1] == 1:
|
| 127 |
+
y = y.iloc[:, 0]
|
| 128 |
+
return combined_df, X, y
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
@validate_params(
|
| 132 |
+
{
|
| 133 |
+
"container_path": [str, os.PathLike],
|
| 134 |
+
"description": [str, None],
|
| 135 |
+
"categories": [list, None],
|
| 136 |
+
"load_content": ["boolean"],
|
| 137 |
+
"shuffle": ["boolean"],
|
| 138 |
+
"encoding": [str, None],
|
| 139 |
+
"decode_error": [StrOptions({"strict", "ignore", "replace"})],
|
| 140 |
+
"random_state": ["random_state"],
|
| 141 |
+
"allowed_extensions": [list, None],
|
| 142 |
+
},
|
| 143 |
+
prefer_skip_nested_validation=True,
|
| 144 |
+
)
|
| 145 |
+
def load_files(
|
| 146 |
+
container_path,
|
| 147 |
+
*,
|
| 148 |
+
description=None,
|
| 149 |
+
categories=None,
|
| 150 |
+
load_content=True,
|
| 151 |
+
shuffle=True,
|
| 152 |
+
encoding=None,
|
| 153 |
+
decode_error="strict",
|
| 154 |
+
random_state=0,
|
| 155 |
+
allowed_extensions=None,
|
| 156 |
+
):
|
| 157 |
+
"""Load text files with categories as subfolder names.
|
| 158 |
+
|
| 159 |
+
Individual samples are assumed to be files stored a two levels folder
|
| 160 |
+
structure such as the following:
|
| 161 |
+
|
| 162 |
+
.. code-block:: text
|
| 163 |
+
|
| 164 |
+
container_folder/
|
| 165 |
+
category_1_folder/
|
| 166 |
+
file_1.txt
|
| 167 |
+
file_2.txt
|
| 168 |
+
...
|
| 169 |
+
file_42.txt
|
| 170 |
+
category_2_folder/
|
| 171 |
+
file_43.txt
|
| 172 |
+
file_44.txt
|
| 173 |
+
...
|
| 174 |
+
|
| 175 |
+
The folder names are used as supervised signal label names. The individual
|
| 176 |
+
file names are not important.
|
| 177 |
+
|
| 178 |
+
This function does not try to extract features into a numpy array or scipy
|
| 179 |
+
sparse matrix. In addition, if load_content is false it does not try to
|
| 180 |
+
load the files in memory.
|
| 181 |
+
|
| 182 |
+
To use text files in a scikit-learn classification or clustering algorithm,
|
| 183 |
+
you will need to use the :mod:`~sklearn.feature_extraction.text` module to
|
| 184 |
+
build a feature extraction transformer that suits your problem.
|
| 185 |
+
|
| 186 |
+
If you set load_content=True, you should also specify the encoding of the
|
| 187 |
+
text using the 'encoding' parameter. For many modern text files, 'utf-8'
|
| 188 |
+
will be the correct encoding. If you leave encoding equal to None, then the
|
| 189 |
+
content will be made of bytes instead of Unicode, and you will not be able
|
| 190 |
+
to use most functions in :mod:`~sklearn.feature_extraction.text`.
|
| 191 |
+
|
| 192 |
+
Similar feature extractors should be built for other kind of unstructured
|
| 193 |
+
data input such as images, audio, video, ...
|
| 194 |
+
|
| 195 |
+
If you want files with a specific file extension (e.g. `.txt`) then you
|
| 196 |
+
can pass a list of those file extensions to `allowed_extensions`.
|
| 197 |
+
|
| 198 |
+
Read more in the :ref:`User Guide <datasets>`.
|
| 199 |
+
|
| 200 |
+
Parameters
|
| 201 |
+
----------
|
| 202 |
+
container_path : str
|
| 203 |
+
Path to the main folder holding one subfolder per category.
|
| 204 |
+
|
| 205 |
+
description : str, default=None
|
| 206 |
+
A paragraph describing the characteristic of the dataset: its source,
|
| 207 |
+
reference, etc.
|
| 208 |
+
|
| 209 |
+
categories : list of str, default=None
|
| 210 |
+
If None (default), load all the categories. If not None, list of
|
| 211 |
+
category names to load (other categories ignored).
|
| 212 |
+
|
| 213 |
+
load_content : bool, default=True
|
| 214 |
+
Whether to load or not the content of the different files. If true a
|
| 215 |
+
'data' attribute containing the text information is present in the data
|
| 216 |
+
structure returned. If not, a filenames attribute gives the path to the
|
| 217 |
+
files.
|
| 218 |
+
|
| 219 |
+
shuffle : bool, default=True
|
| 220 |
+
Whether or not to shuffle the data: might be important for models that
|
| 221 |
+
make the assumption that the samples are independent and identically
|
| 222 |
+
distributed (i.i.d.), such as stochastic gradient descent.
|
| 223 |
+
|
| 224 |
+
encoding : str, default=None
|
| 225 |
+
If None, do not try to decode the content of the files (e.g. for images
|
| 226 |
+
or other non-text content). If not None, encoding to use to decode text
|
| 227 |
+
files to Unicode if load_content is True.
|
| 228 |
+
|
| 229 |
+
decode_error : {'strict', 'ignore', 'replace'}, default='strict'
|
| 230 |
+
Instruction on what to do if a byte sequence is given to analyze that
|
| 231 |
+
contains characters not of the given `encoding`. Passed as keyword
|
| 232 |
+
argument 'errors' to bytes.decode.
|
| 233 |
+
|
| 234 |
+
random_state : int, RandomState instance or None, default=0
|
| 235 |
+
Determines random number generation for dataset shuffling. Pass an int
|
| 236 |
+
for reproducible output across multiple function calls.
|
| 237 |
+
See :term:`Glossary <random_state>`.
|
| 238 |
+
|
| 239 |
+
allowed_extensions : list of str, default=None
|
| 240 |
+
List of desired file extensions to filter the files to be loaded.
|
| 241 |
+
|
| 242 |
+
Returns
|
| 243 |
+
-------
|
| 244 |
+
data : :class:`~sklearn.utils.Bunch`
|
| 245 |
+
Dictionary-like object, with the following attributes.
|
| 246 |
+
|
| 247 |
+
data : list of str
|
| 248 |
+
Only present when `load_content=True`.
|
| 249 |
+
The raw text data to learn.
|
| 250 |
+
target : ndarray
|
| 251 |
+
The target labels (integer index).
|
| 252 |
+
target_names : list
|
| 253 |
+
The names of target classes.
|
| 254 |
+
DESCR : str
|
| 255 |
+
The full description of the dataset.
|
| 256 |
+
filenames: ndarray
|
| 257 |
+
The filenames holding the dataset.
|
| 258 |
+
|
| 259 |
+
Examples
|
| 260 |
+
--------
|
| 261 |
+
>>> from sklearn.datasets import load_files
|
| 262 |
+
>>> container_path = "./"
|
| 263 |
+
>>> load_files(container_path) # doctest: +SKIP
|
| 264 |
+
"""
|
| 265 |
+
|
| 266 |
+
target = []
|
| 267 |
+
target_names = []
|
| 268 |
+
filenames = []
|
| 269 |
+
|
| 270 |
+
folders = [
|
| 271 |
+
f for f in sorted(listdir(container_path)) if isdir(join(container_path, f))
|
| 272 |
+
]
|
| 273 |
+
|
| 274 |
+
if categories is not None:
|
| 275 |
+
folders = [f for f in folders if f in categories]
|
| 276 |
+
|
| 277 |
+
if allowed_extensions is not None:
|
| 278 |
+
allowed_extensions = frozenset(allowed_extensions)
|
| 279 |
+
|
| 280 |
+
for label, folder in enumerate(folders):
|
| 281 |
+
target_names.append(folder)
|
| 282 |
+
folder_path = join(container_path, folder)
|
| 283 |
+
files = sorted(listdir(folder_path))
|
| 284 |
+
if allowed_extensions is not None:
|
| 285 |
+
documents = [
|
| 286 |
+
join(folder_path, file)
|
| 287 |
+
for file in files
|
| 288 |
+
if os.path.splitext(file)[1] in allowed_extensions
|
| 289 |
+
]
|
| 290 |
+
else:
|
| 291 |
+
documents = [join(folder_path, file) for file in files]
|
| 292 |
+
target.extend(len(documents) * [label])
|
| 293 |
+
filenames.extend(documents)
|
| 294 |
+
|
| 295 |
+
# convert to array for fancy indexing
|
| 296 |
+
filenames = np.array(filenames)
|
| 297 |
+
target = np.array(target)
|
| 298 |
+
|
| 299 |
+
if shuffle:
|
| 300 |
+
random_state = check_random_state(random_state)
|
| 301 |
+
indices = np.arange(filenames.shape[0])
|
| 302 |
+
random_state.shuffle(indices)
|
| 303 |
+
filenames = filenames[indices]
|
| 304 |
+
target = target[indices]
|
| 305 |
+
|
| 306 |
+
if load_content:
|
| 307 |
+
data = []
|
| 308 |
+
for filename in filenames:
|
| 309 |
+
data.append(Path(filename).read_bytes())
|
| 310 |
+
if encoding is not None:
|
| 311 |
+
data = [d.decode(encoding, decode_error) for d in data]
|
| 312 |
+
return Bunch(
|
| 313 |
+
data=data,
|
| 314 |
+
filenames=filenames,
|
| 315 |
+
target_names=target_names,
|
| 316 |
+
target=target,
|
| 317 |
+
DESCR=description,
|
| 318 |
+
)
|
| 319 |
+
|
| 320 |
+
return Bunch(
|
| 321 |
+
filenames=filenames, target_names=target_names, target=target, DESCR=description
|
| 322 |
+
)
|
| 323 |
+
|
| 324 |
+
|
| 325 |
+
def load_csv_data(
|
| 326 |
+
data_file_name,
|
| 327 |
+
*,
|
| 328 |
+
data_module=DATA_MODULE,
|
| 329 |
+
descr_file_name=None,
|
| 330 |
+
descr_module=DESCR_MODULE,
|
| 331 |
+
encoding="utf-8",
|
| 332 |
+
):
|
| 333 |
+
"""Loads `data_file_name` from `data_module with `importlib.resources`.
|
| 334 |
+
|
| 335 |
+
Parameters
|
| 336 |
+
----------
|
| 337 |
+
data_file_name : str
|
| 338 |
+
Name of csv file to be loaded from `data_module/data_file_name`.
|
| 339 |
+
For example `'wine_data.csv'`.
|
| 340 |
+
|
| 341 |
+
data_module : str or module, default='sklearn.datasets.data'
|
| 342 |
+
Module where data lives. The default is `'sklearn.datasets.data'`.
|
| 343 |
+
|
| 344 |
+
descr_file_name : str, default=None
|
| 345 |
+
Name of rst file to be loaded from `descr_module/descr_file_name`.
|
| 346 |
+
For example `'wine_data.rst'`. See also :func:`load_descr`.
|
| 347 |
+
If not None, also returns the corresponding description of
|
| 348 |
+
the dataset.
|
| 349 |
+
|
| 350 |
+
descr_module : str or module, default='sklearn.datasets.descr'
|
| 351 |
+
Module where `descr_file_name` lives. See also :func:`load_descr`.
|
| 352 |
+
The default is `'sklearn.datasets.descr'`.
|
| 353 |
+
|
| 354 |
+
Returns
|
| 355 |
+
-------
|
| 356 |
+
data : ndarray of shape (n_samples, n_features)
|
| 357 |
+
A 2D array with each row representing one sample and each column
|
| 358 |
+
representing the features of a given sample.
|
| 359 |
+
|
| 360 |
+
target : ndarry of shape (n_samples,)
|
| 361 |
+
A 1D array holding target variables for all the samples in `data`.
|
| 362 |
+
For example target[0] is the target variable for data[0].
|
| 363 |
+
|
| 364 |
+
target_names : ndarry of shape (n_samples,)
|
| 365 |
+
A 1D array containing the names of the classifications. For example
|
| 366 |
+
target_names[0] is the name of the target[0] class.
|
| 367 |
+
|
| 368 |
+
descr : str, optional
|
| 369 |
+
Description of the dataset (the content of `descr_file_name`).
|
| 370 |
+
Only returned if `descr_file_name` is not None.
|
| 371 |
+
|
| 372 |
+
encoding : str, optional
|
| 373 |
+
Text encoding of the CSV file.
|
| 374 |
+
|
| 375 |
+
.. versionadded:: 1.4
|
| 376 |
+
"""
|
| 377 |
+
data_path = resources.files(data_module) / data_file_name
|
| 378 |
+
with data_path.open("r", encoding="utf-8") as csv_file:
|
| 379 |
+
data_file = csv.reader(csv_file)
|
| 380 |
+
temp = next(data_file)
|
| 381 |
+
n_samples = int(temp[0])
|
| 382 |
+
n_features = int(temp[1])
|
| 383 |
+
target_names = np.array(temp[2:])
|
| 384 |
+
data = np.empty((n_samples, n_features))
|
| 385 |
+
target = np.empty((n_samples,), dtype=int)
|
| 386 |
+
|
| 387 |
+
for i, ir in enumerate(data_file):
|
| 388 |
+
data[i] = np.asarray(ir[:-1], dtype=np.float64)
|
| 389 |
+
target[i] = np.asarray(ir[-1], dtype=int)
|
| 390 |
+
|
| 391 |
+
if descr_file_name is None:
|
| 392 |
+
return data, target, target_names
|
| 393 |
+
else:
|
| 394 |
+
assert descr_module is not None
|
| 395 |
+
descr = load_descr(descr_module=descr_module, descr_file_name=descr_file_name)
|
| 396 |
+
return data, target, target_names, descr
|
| 397 |
+
|
| 398 |
+
|
| 399 |
+
def load_gzip_compressed_csv_data(
|
| 400 |
+
data_file_name,
|
| 401 |
+
*,
|
| 402 |
+
data_module=DATA_MODULE,
|
| 403 |
+
descr_file_name=None,
|
| 404 |
+
descr_module=DESCR_MODULE,
|
| 405 |
+
encoding="utf-8",
|
| 406 |
+
**kwargs,
|
| 407 |
+
):
|
| 408 |
+
"""Loads gzip-compressed with `importlib.resources`.
|
| 409 |
+
|
| 410 |
+
1) Open resource file with `importlib.resources.open_binary`
|
| 411 |
+
2) Decompress file obj with `gzip.open`
|
| 412 |
+
3) Load decompressed data with `np.loadtxt`
|
| 413 |
+
|
| 414 |
+
Parameters
|
| 415 |
+
----------
|
| 416 |
+
data_file_name : str
|
| 417 |
+
Name of gzip-compressed csv file (`'*.csv.gz'`) to be loaded from
|
| 418 |
+
`data_module/data_file_name`. For example `'diabetes_data.csv.gz'`.
|
| 419 |
+
|
| 420 |
+
data_module : str or module, default='sklearn.datasets.data'
|
| 421 |
+
Module where data lives. The default is `'sklearn.datasets.data'`.
|
| 422 |
+
|
| 423 |
+
descr_file_name : str, default=None
|
| 424 |
+
Name of rst file to be loaded from `descr_module/descr_file_name`.
|
| 425 |
+
For example `'wine_data.rst'`. See also :func:`load_descr`.
|
| 426 |
+
If not None, also returns the corresponding description of
|
| 427 |
+
the dataset.
|
| 428 |
+
|
| 429 |
+
descr_module : str or module, default='sklearn.datasets.descr'
|
| 430 |
+
Module where `descr_file_name` lives. See also :func:`load_descr`.
|
| 431 |
+
The default is `'sklearn.datasets.descr'`.
|
| 432 |
+
|
| 433 |
+
encoding : str, default="utf-8"
|
| 434 |
+
Name of the encoding that the gzip-decompressed file will be
|
| 435 |
+
decoded with. The default is 'utf-8'.
|
| 436 |
+
|
| 437 |
+
**kwargs : dict, optional
|
| 438 |
+
Keyword arguments to be passed to `np.loadtxt`;
|
| 439 |
+
e.g. delimiter=','.
|
| 440 |
+
|
| 441 |
+
Returns
|
| 442 |
+
-------
|
| 443 |
+
data : ndarray of shape (n_samples, n_features)
|
| 444 |
+
A 2D array with each row representing one sample and each column
|
| 445 |
+
representing the features and/or target of a given sample.
|
| 446 |
+
|
| 447 |
+
descr : str, optional
|
| 448 |
+
Description of the dataset (the content of `descr_file_name`).
|
| 449 |
+
Only returned if `descr_file_name` is not None.
|
| 450 |
+
"""
|
| 451 |
+
data_path = resources.files(data_module) / data_file_name
|
| 452 |
+
with data_path.open("rb") as compressed_file:
|
| 453 |
+
compressed_file = gzip.open(compressed_file, mode="rt", encoding=encoding)
|
| 454 |
+
data = np.loadtxt(compressed_file, **kwargs)
|
| 455 |
+
|
| 456 |
+
if descr_file_name is None:
|
| 457 |
+
return data
|
| 458 |
+
else:
|
| 459 |
+
assert descr_module is not None
|
| 460 |
+
descr = load_descr(descr_module=descr_module, descr_file_name=descr_file_name)
|
| 461 |
+
return data, descr
|
| 462 |
+
|
| 463 |
+
|
| 464 |
+
def load_descr(descr_file_name, *, descr_module=DESCR_MODULE, encoding="utf-8"):
|
| 465 |
+
"""Load `descr_file_name` from `descr_module` with `importlib.resources`.
|
| 466 |
+
|
| 467 |
+
Parameters
|
| 468 |
+
----------
|
| 469 |
+
descr_file_name : str, default=None
|
| 470 |
+
Name of rst file to be loaded from `descr_module/descr_file_name`.
|
| 471 |
+
For example `'wine_data.rst'`. See also :func:`load_descr`.
|
| 472 |
+
If not None, also returns the corresponding description of
|
| 473 |
+
the dataset.
|
| 474 |
+
|
| 475 |
+
descr_module : str or module, default='sklearn.datasets.descr'
|
| 476 |
+
Module where `descr_file_name` lives. See also :func:`load_descr`.
|
| 477 |
+
The default is `'sklearn.datasets.descr'`.
|
| 478 |
+
|
| 479 |
+
encoding : str, default="utf-8"
|
| 480 |
+
Name of the encoding that `descr_file_name` will be decoded with.
|
| 481 |
+
The default is 'utf-8'.
|
| 482 |
+
|
| 483 |
+
.. versionadded:: 1.4
|
| 484 |
+
|
| 485 |
+
Returns
|
| 486 |
+
-------
|
| 487 |
+
fdescr : str
|
| 488 |
+
Content of `descr_file_name`.
|
| 489 |
+
"""
|
| 490 |
+
path = resources.files(descr_module) / descr_file_name
|
| 491 |
+
return path.read_text(encoding=encoding)
|
| 492 |
+
|
| 493 |
+
|
| 494 |
+
@validate_params(
|
| 495 |
+
{
|
| 496 |
+
"return_X_y": ["boolean"],
|
| 497 |
+
"as_frame": ["boolean"],
|
| 498 |
+
},
|
| 499 |
+
prefer_skip_nested_validation=True,
|
| 500 |
+
)
|
| 501 |
+
def load_wine(*, return_X_y=False, as_frame=False):
|
| 502 |
+
"""Load and return the wine dataset (classification).
|
| 503 |
+
|
| 504 |
+
.. versionadded:: 0.18
|
| 505 |
+
|
| 506 |
+
The wine dataset is a classic and very easy multi-class classification
|
| 507 |
+
dataset.
|
| 508 |
+
|
| 509 |
+
================= ==============
|
| 510 |
+
Classes 3
|
| 511 |
+
Samples per class [59,71,48]
|
| 512 |
+
Samples total 178
|
| 513 |
+
Dimensionality 13
|
| 514 |
+
Features real, positive
|
| 515 |
+
================= ==============
|
| 516 |
+
|
| 517 |
+
The copy of UCI ML Wine Data Set dataset is downloaded and modified to fit
|
| 518 |
+
standard format from:
|
| 519 |
+
https://archive.ics.uci.edu/ml/machine-learning-databases/wine/wine.data
|
| 520 |
+
|
| 521 |
+
Read more in the :ref:`User Guide <wine_dataset>`.
|
| 522 |
+
|
| 523 |
+
Parameters
|
| 524 |
+
----------
|
| 525 |
+
return_X_y : bool, default=False
|
| 526 |
+
If True, returns ``(data, target)`` instead of a Bunch object.
|
| 527 |
+
See below for more information about the `data` and `target` object.
|
| 528 |
+
|
| 529 |
+
as_frame : bool, default=False
|
| 530 |
+
If True, the data is a pandas DataFrame including columns with
|
| 531 |
+
appropriate dtypes (numeric). The target is
|
| 532 |
+
a pandas DataFrame or Series depending on the number of target columns.
|
| 533 |
+
If `return_X_y` is True, then (`data`, `target`) will be pandas
|
| 534 |
+
DataFrames or Series as described below.
|
| 535 |
+
|
| 536 |
+
.. versionadded:: 0.23
|
| 537 |
+
|
| 538 |
+
Returns
|
| 539 |
+
-------
|
| 540 |
+
data : :class:`~sklearn.utils.Bunch`
|
| 541 |
+
Dictionary-like object, with the following attributes.
|
| 542 |
+
|
| 543 |
+
data : {ndarray, dataframe} of shape (178, 13)
|
| 544 |
+
The data matrix. If `as_frame=True`, `data` will be a pandas
|
| 545 |
+
DataFrame.
|
| 546 |
+
target: {ndarray, Series} of shape (178,)
|
| 547 |
+
The classification target. If `as_frame=True`, `target` will be
|
| 548 |
+
a pandas Series.
|
| 549 |
+
feature_names: list
|
| 550 |
+
The names of the dataset columns.
|
| 551 |
+
target_names: list
|
| 552 |
+
The names of target classes.
|
| 553 |
+
frame: DataFrame of shape (178, 14)
|
| 554 |
+
Only present when `as_frame=True`. DataFrame with `data` and
|
| 555 |
+
`target`.
|
| 556 |
+
|
| 557 |
+
.. versionadded:: 0.23
|
| 558 |
+
DESCR: str
|
| 559 |
+
The full description of the dataset.
|
| 560 |
+
|
| 561 |
+
(data, target) : tuple if ``return_X_y`` is True
|
| 562 |
+
A tuple of two ndarrays by default. The first contains a 2D array of shape
|
| 563 |
+
(178, 13) with each row representing one sample and each column representing
|
| 564 |
+
the features. The second array of shape (178,) contains the target samples.
|
| 565 |
+
|
| 566 |
+
Examples
|
| 567 |
+
--------
|
| 568 |
+
Let's say you are interested in the samples 10, 80, and 140, and want to
|
| 569 |
+
know their class name.
|
| 570 |
+
|
| 571 |
+
>>> from sklearn.datasets import load_wine
|
| 572 |
+
>>> data = load_wine()
|
| 573 |
+
>>> data.target[[10, 80, 140]]
|
| 574 |
+
array([0, 1, 2])
|
| 575 |
+
>>> list(data.target_names)
|
| 576 |
+
[np.str_('class_0'), np.str_('class_1'), np.str_('class_2')]
|
| 577 |
+
"""
|
| 578 |
+
|
| 579 |
+
data, target, target_names, fdescr = load_csv_data(
|
| 580 |
+
data_file_name="wine_data.csv", descr_file_name="wine_data.rst"
|
| 581 |
+
)
|
| 582 |
+
|
| 583 |
+
feature_names = [
|
| 584 |
+
"alcohol",
|
| 585 |
+
"malic_acid",
|
| 586 |
+
"ash",
|
| 587 |
+
"alcalinity_of_ash",
|
| 588 |
+
"magnesium",
|
| 589 |
+
"total_phenols",
|
| 590 |
+
"flavanoids",
|
| 591 |
+
"nonflavanoid_phenols",
|
| 592 |
+
"proanthocyanins",
|
| 593 |
+
"color_intensity",
|
| 594 |
+
"hue",
|
| 595 |
+
"od280/od315_of_diluted_wines",
|
| 596 |
+
"proline",
|
| 597 |
+
]
|
| 598 |
+
|
| 599 |
+
frame = None
|
| 600 |
+
target_columns = [
|
| 601 |
+
"target",
|
| 602 |
+
]
|
| 603 |
+
if as_frame:
|
| 604 |
+
frame, data, target = _convert_data_dataframe(
|
| 605 |
+
"load_wine", data, target, feature_names, target_columns
|
| 606 |
+
)
|
| 607 |
+
|
| 608 |
+
if return_X_y:
|
| 609 |
+
return data, target
|
| 610 |
+
|
| 611 |
+
return Bunch(
|
| 612 |
+
data=data,
|
| 613 |
+
target=target,
|
| 614 |
+
frame=frame,
|
| 615 |
+
target_names=target_names,
|
| 616 |
+
DESCR=fdescr,
|
| 617 |
+
feature_names=feature_names,
|
| 618 |
+
)
|
| 619 |
+
|
| 620 |
+
|
| 621 |
+
@validate_params(
|
| 622 |
+
{"return_X_y": ["boolean"], "as_frame": ["boolean"]},
|
| 623 |
+
prefer_skip_nested_validation=True,
|
| 624 |
+
)
|
| 625 |
+
def load_iris(*, return_X_y=False, as_frame=False):
|
| 626 |
+
"""Load and return the iris dataset (classification).
|
| 627 |
+
|
| 628 |
+
The iris dataset is a classic and very easy multi-class classification
|
| 629 |
+
dataset.
|
| 630 |
+
|
| 631 |
+
================= ==============
|
| 632 |
+
Classes 3
|
| 633 |
+
Samples per class 50
|
| 634 |
+
Samples total 150
|
| 635 |
+
Dimensionality 4
|
| 636 |
+
Features real, positive
|
| 637 |
+
================= ==============
|
| 638 |
+
|
| 639 |
+
Read more in the :ref:`User Guide <iris_dataset>`.
|
| 640 |
+
|
| 641 |
+
.. versionchanged:: 0.20
|
| 642 |
+
Fixed two wrong data points according to Fisher's paper.
|
| 643 |
+
The new version is the same as in R, but not as in the UCI
|
| 644 |
+
Machine Learning Repository.
|
| 645 |
+
|
| 646 |
+
Parameters
|
| 647 |
+
----------
|
| 648 |
+
return_X_y : bool, default=False
|
| 649 |
+
If True, returns ``(data, target)`` instead of a Bunch object. See
|
| 650 |
+
below for more information about the `data` and `target` object.
|
| 651 |
+
|
| 652 |
+
.. versionadded:: 0.18
|
| 653 |
+
|
| 654 |
+
as_frame : bool, default=False
|
| 655 |
+
If True, the data is a pandas DataFrame including columns with
|
| 656 |
+
appropriate dtypes (numeric). The target is
|
| 657 |
+
a pandas DataFrame or Series depending on the number of target columns.
|
| 658 |
+
If `return_X_y` is True, then (`data`, `target`) will be pandas
|
| 659 |
+
DataFrames or Series as described below.
|
| 660 |
+
|
| 661 |
+
.. versionadded:: 0.23
|
| 662 |
+
|
| 663 |
+
Returns
|
| 664 |
+
-------
|
| 665 |
+
data : :class:`~sklearn.utils.Bunch`
|
| 666 |
+
Dictionary-like object, with the following attributes.
|
| 667 |
+
|
| 668 |
+
data : {ndarray, dataframe} of shape (150, 4)
|
| 669 |
+
The data matrix. If `as_frame=True`, `data` will be a pandas
|
| 670 |
+
DataFrame.
|
| 671 |
+
target: {ndarray, Series} of shape (150,)
|
| 672 |
+
The classification target. If `as_frame=True`, `target` will be
|
| 673 |
+
a pandas Series.
|
| 674 |
+
feature_names: list
|
| 675 |
+
The names of the dataset columns.
|
| 676 |
+
target_names: ndarray of shape (3, )
|
| 677 |
+
The names of target classes.
|
| 678 |
+
frame: DataFrame of shape (150, 5)
|
| 679 |
+
Only present when `as_frame=True`. DataFrame with `data` and
|
| 680 |
+
`target`.
|
| 681 |
+
|
| 682 |
+
.. versionadded:: 0.23
|
| 683 |
+
DESCR: str
|
| 684 |
+
The full description of the dataset.
|
| 685 |
+
filename: str
|
| 686 |
+
The path to the location of the data.
|
| 687 |
+
|
| 688 |
+
.. versionadded:: 0.20
|
| 689 |
+
|
| 690 |
+
(data, target) : tuple if ``return_X_y`` is True
|
| 691 |
+
A tuple of two ndarray. The first containing a 2D array of shape
|
| 692 |
+
(n_samples, n_features) with each row representing one sample and
|
| 693 |
+
each column representing the features. The second ndarray of shape
|
| 694 |
+
(n_samples,) containing the target samples.
|
| 695 |
+
|
| 696 |
+
.. versionadded:: 0.18
|
| 697 |
+
|
| 698 |
+
Examples
|
| 699 |
+
--------
|
| 700 |
+
Let's say you are interested in the samples 10, 25, and 50, and want to
|
| 701 |
+
know their class name.
|
| 702 |
+
|
| 703 |
+
>>> from sklearn.datasets import load_iris
|
| 704 |
+
>>> data = load_iris()
|
| 705 |
+
>>> data.target[[10, 25, 50]]
|
| 706 |
+
array([0, 0, 1])
|
| 707 |
+
>>> list(data.target_names)
|
| 708 |
+
[np.str_('setosa'), np.str_('versicolor'), np.str_('virginica')]
|
| 709 |
+
|
| 710 |
+
See :ref:`sphx_glr_auto_examples_decomposition_plot_pca_iris.py` for a more
|
| 711 |
+
detailed example of how to work with the iris dataset.
|
| 712 |
+
"""
|
| 713 |
+
data_file_name = "iris.csv"
|
| 714 |
+
data, target, target_names, fdescr = load_csv_data(
|
| 715 |
+
data_file_name=data_file_name, descr_file_name="iris.rst"
|
| 716 |
+
)
|
| 717 |
+
|
| 718 |
+
feature_names = [
|
| 719 |
+
"sepal length (cm)",
|
| 720 |
+
"sepal width (cm)",
|
| 721 |
+
"petal length (cm)",
|
| 722 |
+
"petal width (cm)",
|
| 723 |
+
]
|
| 724 |
+
|
| 725 |
+
frame = None
|
| 726 |
+
target_columns = [
|
| 727 |
+
"target",
|
| 728 |
+
]
|
| 729 |
+
if as_frame:
|
| 730 |
+
frame, data, target = _convert_data_dataframe(
|
| 731 |
+
"load_iris", data, target, feature_names, target_columns
|
| 732 |
+
)
|
| 733 |
+
|
| 734 |
+
if return_X_y:
|
| 735 |
+
return data, target
|
| 736 |
+
|
| 737 |
+
return Bunch(
|
| 738 |
+
data=data,
|
| 739 |
+
target=target,
|
| 740 |
+
frame=frame,
|
| 741 |
+
target_names=target_names,
|
| 742 |
+
DESCR=fdescr,
|
| 743 |
+
feature_names=feature_names,
|
| 744 |
+
filename=data_file_name,
|
| 745 |
+
data_module=DATA_MODULE,
|
| 746 |
+
)
|
| 747 |
+
|
| 748 |
+
|
| 749 |
+
@validate_params(
|
| 750 |
+
{"return_X_y": ["boolean"], "as_frame": ["boolean"]},
|
| 751 |
+
prefer_skip_nested_validation=True,
|
| 752 |
+
)
|
| 753 |
+
def load_breast_cancer(*, return_X_y=False, as_frame=False):
|
| 754 |
+
"""Load and return the breast cancer Wisconsin dataset (classification).
|
| 755 |
+
|
| 756 |
+
The breast cancer dataset is a classic and very easy binary classification
|
| 757 |
+
dataset.
|
| 758 |
+
|
| 759 |
+
================= ==============
|
| 760 |
+
Classes 2
|
| 761 |
+
Samples per class 212(M),357(B)
|
| 762 |
+
Samples total 569
|
| 763 |
+
Dimensionality 30
|
| 764 |
+
Features real, positive
|
| 765 |
+
================= ==============
|
| 766 |
+
|
| 767 |
+
The copy of UCI ML Breast Cancer Wisconsin (Diagnostic) dataset is
|
| 768 |
+
downloaded from:
|
| 769 |
+
https://archive.ics.uci.edu/dataset/17/breast+cancer+wisconsin+diagnostic
|
| 770 |
+
|
| 771 |
+
Read more in the :ref:`User Guide <breast_cancer_dataset>`.
|
| 772 |
+
|
| 773 |
+
Parameters
|
| 774 |
+
----------
|
| 775 |
+
return_X_y : bool, default=False
|
| 776 |
+
If True, returns ``(data, target)`` instead of a Bunch object.
|
| 777 |
+
See below for more information about the `data` and `target` object.
|
| 778 |
+
|
| 779 |
+
.. versionadded:: 0.18
|
| 780 |
+
|
| 781 |
+
as_frame : bool, default=False
|
| 782 |
+
If True, the data is a pandas DataFrame including columns with
|
| 783 |
+
appropriate dtypes (numeric). The target is
|
| 784 |
+
a pandas DataFrame or Series depending on the number of target columns.
|
| 785 |
+
If `return_X_y` is True, then (`data`, `target`) will be pandas
|
| 786 |
+
DataFrames or Series as described below.
|
| 787 |
+
|
| 788 |
+
.. versionadded:: 0.23
|
| 789 |
+
|
| 790 |
+
Returns
|
| 791 |
+
-------
|
| 792 |
+
data : :class:`~sklearn.utils.Bunch`
|
| 793 |
+
Dictionary-like object, with the following attributes.
|
| 794 |
+
|
| 795 |
+
data : {ndarray, dataframe} of shape (569, 30)
|
| 796 |
+
The data matrix. If `as_frame=True`, `data` will be a pandas
|
| 797 |
+
DataFrame.
|
| 798 |
+
target : {ndarray, Series} of shape (569,)
|
| 799 |
+
The classification target. If `as_frame=True`, `target` will be
|
| 800 |
+
a pandas Series.
|
| 801 |
+
feature_names : ndarray of shape (30,)
|
| 802 |
+
The names of the dataset columns.
|
| 803 |
+
target_names : ndarray of shape (2,)
|
| 804 |
+
The names of target classes.
|
| 805 |
+
frame : DataFrame of shape (569, 31)
|
| 806 |
+
Only present when `as_frame=True`. DataFrame with `data` and
|
| 807 |
+
`target`.
|
| 808 |
+
|
| 809 |
+
.. versionadded:: 0.23
|
| 810 |
+
DESCR : str
|
| 811 |
+
The full description of the dataset.
|
| 812 |
+
filename : str
|
| 813 |
+
The path to the location of the data.
|
| 814 |
+
|
| 815 |
+
.. versionadded:: 0.20
|
| 816 |
+
|
| 817 |
+
(data, target) : tuple if ``return_X_y`` is True
|
| 818 |
+
A tuple of two ndarrays by default. The first contains a 2D ndarray of
|
| 819 |
+
shape (569, 30) with each row representing one sample and each column
|
| 820 |
+
representing the features. The second ndarray of shape (569,) contains
|
| 821 |
+
the target samples. If `as_frame=True`, both arrays are pandas objects,
|
| 822 |
+
i.e. `X` a dataframe and `y` a series.
|
| 823 |
+
|
| 824 |
+
.. versionadded:: 0.18
|
| 825 |
+
|
| 826 |
+
Examples
|
| 827 |
+
--------
|
| 828 |
+
Let's say you are interested in the samples 10, 50, and 85, and want to
|
| 829 |
+
know their class name.
|
| 830 |
+
|
| 831 |
+
>>> from sklearn.datasets import load_breast_cancer
|
| 832 |
+
>>> data = load_breast_cancer()
|
| 833 |
+
>>> data.target[[10, 50, 85]]
|
| 834 |
+
array([0, 1, 0])
|
| 835 |
+
>>> list(data.target_names)
|
| 836 |
+
[np.str_('malignant'), np.str_('benign')]
|
| 837 |
+
"""
|
| 838 |
+
data_file_name = "breast_cancer.csv"
|
| 839 |
+
data, target, target_names, fdescr = load_csv_data(
|
| 840 |
+
data_file_name=data_file_name, descr_file_name="breast_cancer.rst"
|
| 841 |
+
)
|
| 842 |
+
|
| 843 |
+
feature_names = np.array(
|
| 844 |
+
[
|
| 845 |
+
"mean radius",
|
| 846 |
+
"mean texture",
|
| 847 |
+
"mean perimeter",
|
| 848 |
+
"mean area",
|
| 849 |
+
"mean smoothness",
|
| 850 |
+
"mean compactness",
|
| 851 |
+
"mean concavity",
|
| 852 |
+
"mean concave points",
|
| 853 |
+
"mean symmetry",
|
| 854 |
+
"mean fractal dimension",
|
| 855 |
+
"radius error",
|
| 856 |
+
"texture error",
|
| 857 |
+
"perimeter error",
|
| 858 |
+
"area error",
|
| 859 |
+
"smoothness error",
|
| 860 |
+
"compactness error",
|
| 861 |
+
"concavity error",
|
| 862 |
+
"concave points error",
|
| 863 |
+
"symmetry error",
|
| 864 |
+
"fractal dimension error",
|
| 865 |
+
"worst radius",
|
| 866 |
+
"worst texture",
|
| 867 |
+
"worst perimeter",
|
| 868 |
+
"worst area",
|
| 869 |
+
"worst smoothness",
|
| 870 |
+
"worst compactness",
|
| 871 |
+
"worst concavity",
|
| 872 |
+
"worst concave points",
|
| 873 |
+
"worst symmetry",
|
| 874 |
+
"worst fractal dimension",
|
| 875 |
+
]
|
| 876 |
+
)
|
| 877 |
+
|
| 878 |
+
frame = None
|
| 879 |
+
target_columns = [
|
| 880 |
+
"target",
|
| 881 |
+
]
|
| 882 |
+
if as_frame:
|
| 883 |
+
frame, data, target = _convert_data_dataframe(
|
| 884 |
+
"load_breast_cancer", data, target, feature_names, target_columns
|
| 885 |
+
)
|
| 886 |
+
|
| 887 |
+
if return_X_y:
|
| 888 |
+
return data, target
|
| 889 |
+
|
| 890 |
+
return Bunch(
|
| 891 |
+
data=data,
|
| 892 |
+
target=target,
|
| 893 |
+
frame=frame,
|
| 894 |
+
target_names=target_names,
|
| 895 |
+
DESCR=fdescr,
|
| 896 |
+
feature_names=feature_names,
|
| 897 |
+
filename=data_file_name,
|
| 898 |
+
data_module=DATA_MODULE,
|
| 899 |
+
)
|
| 900 |
+
|
| 901 |
+
|
| 902 |
+
@validate_params(
|
| 903 |
+
{
|
| 904 |
+
"n_class": [Interval(Integral, 1, 10, closed="both")],
|
| 905 |
+
"return_X_y": ["boolean"],
|
| 906 |
+
"as_frame": ["boolean"],
|
| 907 |
+
},
|
| 908 |
+
prefer_skip_nested_validation=True,
|
| 909 |
+
)
|
| 910 |
+
def load_digits(*, n_class=10, return_X_y=False, as_frame=False):
|
| 911 |
+
"""Load and return the digits dataset (classification).
|
| 912 |
+
|
| 913 |
+
Each datapoint is a 8x8 image of a digit.
|
| 914 |
+
|
| 915 |
+
================= ==============
|
| 916 |
+
Classes 10
|
| 917 |
+
Samples per class ~180
|
| 918 |
+
Samples total 1797
|
| 919 |
+
Dimensionality 64
|
| 920 |
+
Features integers 0-16
|
| 921 |
+
================= ==============
|
| 922 |
+
|
| 923 |
+
This is a copy of the test set of the UCI ML hand-written digits datasets
|
| 924 |
+
https://archive.ics.uci.edu/ml/datasets/Optical+Recognition+of+Handwritten+Digits
|
| 925 |
+
|
| 926 |
+
Read more in the :ref:`User Guide <digits_dataset>`.
|
| 927 |
+
|
| 928 |
+
Parameters
|
| 929 |
+
----------
|
| 930 |
+
n_class : int, default=10
|
| 931 |
+
The number of classes to return. Between 0 and 10.
|
| 932 |
+
|
| 933 |
+
return_X_y : bool, default=False
|
| 934 |
+
If True, returns ``(data, target)`` instead of a Bunch object.
|
| 935 |
+
See below for more information about the `data` and `target` object.
|
| 936 |
+
|
| 937 |
+
.. versionadded:: 0.18
|
| 938 |
+
|
| 939 |
+
as_frame : bool, default=False
|
| 940 |
+
If True, the data is a pandas DataFrame including columns with
|
| 941 |
+
appropriate dtypes (numeric). The target is
|
| 942 |
+
a pandas DataFrame or Series depending on the number of target columns.
|
| 943 |
+
If `return_X_y` is True, then (`data`, `target`) will be pandas
|
| 944 |
+
DataFrames or Series as described below.
|
| 945 |
+
|
| 946 |
+
.. versionadded:: 0.23
|
| 947 |
+
|
| 948 |
+
Returns
|
| 949 |
+
-------
|
| 950 |
+
data : :class:`~sklearn.utils.Bunch`
|
| 951 |
+
Dictionary-like object, with the following attributes.
|
| 952 |
+
|
| 953 |
+
data : {ndarray, dataframe} of shape (1797, 64)
|
| 954 |
+
The flattened data matrix. If `as_frame=True`, `data` will be
|
| 955 |
+
a pandas DataFrame.
|
| 956 |
+
target: {ndarray, Series} of shape (1797,)
|
| 957 |
+
The classification target. If `as_frame=True`, `target` will be
|
| 958 |
+
a pandas Series.
|
| 959 |
+
feature_names: list
|
| 960 |
+
The names of the dataset columns.
|
| 961 |
+
target_names: list
|
| 962 |
+
The names of target classes.
|
| 963 |
+
|
| 964 |
+
.. versionadded:: 0.20
|
| 965 |
+
|
| 966 |
+
frame: DataFrame of shape (1797, 65)
|
| 967 |
+
Only present when `as_frame=True`. DataFrame with `data` and
|
| 968 |
+
`target`.
|
| 969 |
+
|
| 970 |
+
.. versionadded:: 0.23
|
| 971 |
+
images: {ndarray} of shape (1797, 8, 8)
|
| 972 |
+
The raw image data.
|
| 973 |
+
DESCR: str
|
| 974 |
+
The full description of the dataset.
|
| 975 |
+
|
| 976 |
+
(data, target) : tuple if ``return_X_y`` is True
|
| 977 |
+
A tuple of two ndarrays by default. The first contains a 2D ndarray of
|
| 978 |
+
shape (1797, 64) with each row representing one sample and each column
|
| 979 |
+
representing the features. The second ndarray of shape (1797) contains
|
| 980 |
+
the target samples. If `as_frame=True`, both arrays are pandas objects,
|
| 981 |
+
i.e. `X` a dataframe and `y` a series.
|
| 982 |
+
|
| 983 |
+
.. versionadded:: 0.18
|
| 984 |
+
|
| 985 |
+
Examples
|
| 986 |
+
--------
|
| 987 |
+
To load the data and visualize the images::
|
| 988 |
+
|
| 989 |
+
>>> from sklearn.datasets import load_digits
|
| 990 |
+
>>> digits = load_digits()
|
| 991 |
+
>>> print(digits.data.shape)
|
| 992 |
+
(1797, 64)
|
| 993 |
+
>>> import matplotlib.pyplot as plt
|
| 994 |
+
>>> plt.matshow(digits.images[0], cmap="gray")
|
| 995 |
+
<...>
|
| 996 |
+
>>> plt.show()
|
| 997 |
+
"""
|
| 998 |
+
|
| 999 |
+
data, fdescr = load_gzip_compressed_csv_data(
|
| 1000 |
+
data_file_name="digits.csv.gz", descr_file_name="digits.rst", delimiter=","
|
| 1001 |
+
)
|
| 1002 |
+
|
| 1003 |
+
target = data[:, -1].astype(int, copy=False)
|
| 1004 |
+
flat_data = data[:, :-1]
|
| 1005 |
+
images = flat_data.view()
|
| 1006 |
+
images.shape = (-1, 8, 8)
|
| 1007 |
+
|
| 1008 |
+
if n_class < 10:
|
| 1009 |
+
idx = target < n_class
|
| 1010 |
+
flat_data, target = flat_data[idx], target[idx]
|
| 1011 |
+
images = images[idx]
|
| 1012 |
+
|
| 1013 |
+
feature_names = [
|
| 1014 |
+
"pixel_{}_{}".format(row_idx, col_idx)
|
| 1015 |
+
for row_idx in range(8)
|
| 1016 |
+
for col_idx in range(8)
|
| 1017 |
+
]
|
| 1018 |
+
|
| 1019 |
+
frame = None
|
| 1020 |
+
target_columns = [
|
| 1021 |
+
"target",
|
| 1022 |
+
]
|
| 1023 |
+
if as_frame:
|
| 1024 |
+
frame, flat_data, target = _convert_data_dataframe(
|
| 1025 |
+
"load_digits", flat_data, target, feature_names, target_columns
|
| 1026 |
+
)
|
| 1027 |
+
|
| 1028 |
+
if return_X_y:
|
| 1029 |
+
return flat_data, target
|
| 1030 |
+
|
| 1031 |
+
return Bunch(
|
| 1032 |
+
data=flat_data,
|
| 1033 |
+
target=target,
|
| 1034 |
+
frame=frame,
|
| 1035 |
+
feature_names=feature_names,
|
| 1036 |
+
target_names=np.arange(10),
|
| 1037 |
+
images=images,
|
| 1038 |
+
DESCR=fdescr,
|
| 1039 |
+
)
|
| 1040 |
+
|
| 1041 |
+
|
| 1042 |
+
@validate_params(
|
| 1043 |
+
{"return_X_y": ["boolean"], "as_frame": ["boolean"], "scaled": ["boolean"]},
|
| 1044 |
+
prefer_skip_nested_validation=True,
|
| 1045 |
+
)
|
| 1046 |
+
def load_diabetes(*, return_X_y=False, as_frame=False, scaled=True):
|
| 1047 |
+
"""Load and return the diabetes dataset (regression).
|
| 1048 |
+
|
| 1049 |
+
============== ==================
|
| 1050 |
+
Samples total 442
|
| 1051 |
+
Dimensionality 10
|
| 1052 |
+
Features real, -.2 < x < .2
|
| 1053 |
+
Targets integer 25 - 346
|
| 1054 |
+
============== ==================
|
| 1055 |
+
|
| 1056 |
+
.. note::
|
| 1057 |
+
The meaning of each feature (i.e. `feature_names`) might be unclear
|
| 1058 |
+
(especially for `ltg`) as the documentation of the original dataset is
|
| 1059 |
+
not explicit. We provide information that seems correct in regard with
|
| 1060 |
+
the scientific literature in this field of research.
|
| 1061 |
+
|
| 1062 |
+
Read more in the :ref:`User Guide <diabetes_dataset>`.
|
| 1063 |
+
|
| 1064 |
+
Parameters
|
| 1065 |
+
----------
|
| 1066 |
+
return_X_y : bool, default=False
|
| 1067 |
+
If True, returns ``(data, target)`` instead of a Bunch object.
|
| 1068 |
+
See below for more information about the `data` and `target` object.
|
| 1069 |
+
|
| 1070 |
+
.. versionadded:: 0.18
|
| 1071 |
+
|
| 1072 |
+
as_frame : bool, default=False
|
| 1073 |
+
If True, the data is a pandas DataFrame including columns with
|
| 1074 |
+
appropriate dtypes (numeric). The target is
|
| 1075 |
+
a pandas DataFrame or Series depending on the number of target columns.
|
| 1076 |
+
If `return_X_y` is True, then (`data`, `target`) will be pandas
|
| 1077 |
+
DataFrames or Series as described below.
|
| 1078 |
+
|
| 1079 |
+
.. versionadded:: 0.23
|
| 1080 |
+
|
| 1081 |
+
scaled : bool, default=True
|
| 1082 |
+
If True, the feature variables are mean centered and scaled by the
|
| 1083 |
+
standard deviation times the square root of `n_samples`.
|
| 1084 |
+
If False, raw data is returned for the feature variables.
|
| 1085 |
+
|
| 1086 |
+
.. versionadded:: 1.1
|
| 1087 |
+
|
| 1088 |
+
Returns
|
| 1089 |
+
-------
|
| 1090 |
+
data : :class:`~sklearn.utils.Bunch`
|
| 1091 |
+
Dictionary-like object, with the following attributes.
|
| 1092 |
+
|
| 1093 |
+
data : {ndarray, dataframe} of shape (442, 10)
|
| 1094 |
+
The data matrix. If `as_frame=True`, `data` will be a pandas
|
| 1095 |
+
DataFrame.
|
| 1096 |
+
target: {ndarray, Series} of shape (442,)
|
| 1097 |
+
The regression target. If `as_frame=True`, `target` will be
|
| 1098 |
+
a pandas Series.
|
| 1099 |
+
feature_names: list
|
| 1100 |
+
The names of the dataset columns.
|
| 1101 |
+
frame: DataFrame of shape (442, 11)
|
| 1102 |
+
Only present when `as_frame=True`. DataFrame with `data` and
|
| 1103 |
+
`target`.
|
| 1104 |
+
|
| 1105 |
+
.. versionadded:: 0.23
|
| 1106 |
+
DESCR: str
|
| 1107 |
+
The full description of the dataset.
|
| 1108 |
+
data_filename: str
|
| 1109 |
+
The path to the location of the data.
|
| 1110 |
+
target_filename: str
|
| 1111 |
+
The path to the location of the target.
|
| 1112 |
+
|
| 1113 |
+
(data, target) : tuple if ``return_X_y`` is True
|
| 1114 |
+
Returns a tuple of two ndarray of shape (n_samples, n_features)
|
| 1115 |
+
A 2D array with each row representing one sample and each column
|
| 1116 |
+
representing the features and/or target of a given sample.
|
| 1117 |
+
|
| 1118 |
+
.. versionadded:: 0.18
|
| 1119 |
+
|
| 1120 |
+
Examples
|
| 1121 |
+
--------
|
| 1122 |
+
>>> from sklearn.datasets import load_diabetes
|
| 1123 |
+
>>> diabetes = load_diabetes()
|
| 1124 |
+
>>> diabetes.target[:3]
|
| 1125 |
+
array([151., 75., 141.])
|
| 1126 |
+
>>> diabetes.data.shape
|
| 1127 |
+
(442, 10)
|
| 1128 |
+
"""
|
| 1129 |
+
data_filename = "diabetes_data_raw.csv.gz"
|
| 1130 |
+
target_filename = "diabetes_target.csv.gz"
|
| 1131 |
+
data = load_gzip_compressed_csv_data(data_filename)
|
| 1132 |
+
target = load_gzip_compressed_csv_data(target_filename)
|
| 1133 |
+
|
| 1134 |
+
if scaled:
|
| 1135 |
+
data = scale(data, copy=False)
|
| 1136 |
+
data /= data.shape[0] ** 0.5
|
| 1137 |
+
|
| 1138 |
+
fdescr = load_descr("diabetes.rst")
|
| 1139 |
+
|
| 1140 |
+
feature_names = ["age", "sex", "bmi", "bp", "s1", "s2", "s3", "s4", "s5", "s6"]
|
| 1141 |
+
|
| 1142 |
+
frame = None
|
| 1143 |
+
target_columns = [
|
| 1144 |
+
"target",
|
| 1145 |
+
]
|
| 1146 |
+
if as_frame:
|
| 1147 |
+
frame, data, target = _convert_data_dataframe(
|
| 1148 |
+
"load_diabetes", data, target, feature_names, target_columns
|
| 1149 |
+
)
|
| 1150 |
+
|
| 1151 |
+
if return_X_y:
|
| 1152 |
+
return data, target
|
| 1153 |
+
|
| 1154 |
+
return Bunch(
|
| 1155 |
+
data=data,
|
| 1156 |
+
target=target,
|
| 1157 |
+
frame=frame,
|
| 1158 |
+
DESCR=fdescr,
|
| 1159 |
+
feature_names=feature_names,
|
| 1160 |
+
data_filename=data_filename,
|
| 1161 |
+
target_filename=target_filename,
|
| 1162 |
+
data_module=DATA_MODULE,
|
| 1163 |
+
)
|
| 1164 |
+
|
| 1165 |
+
|
| 1166 |
+
@validate_params(
|
| 1167 |
+
{
|
| 1168 |
+
"return_X_y": ["boolean"],
|
| 1169 |
+
"as_frame": ["boolean"],
|
| 1170 |
+
},
|
| 1171 |
+
prefer_skip_nested_validation=True,
|
| 1172 |
+
)
|
| 1173 |
+
def load_linnerud(*, return_X_y=False, as_frame=False):
|
| 1174 |
+
"""Load and return the physical exercise Linnerud dataset.
|
| 1175 |
+
|
| 1176 |
+
This dataset is suitable for multi-output regression tasks.
|
| 1177 |
+
|
| 1178 |
+
============== ============================
|
| 1179 |
+
Samples total 20
|
| 1180 |
+
Dimensionality 3 (for both data and target)
|
| 1181 |
+
Features integer
|
| 1182 |
+
Targets integer
|
| 1183 |
+
============== ============================
|
| 1184 |
+
|
| 1185 |
+
Read more in the :ref:`User Guide <linnerrud_dataset>`.
|
| 1186 |
+
|
| 1187 |
+
Parameters
|
| 1188 |
+
----------
|
| 1189 |
+
return_X_y : bool, default=False
|
| 1190 |
+
If True, returns ``(data, target)`` instead of a Bunch object.
|
| 1191 |
+
See below for more information about the `data` and `target` object.
|
| 1192 |
+
|
| 1193 |
+
.. versionadded:: 0.18
|
| 1194 |
+
|
| 1195 |
+
as_frame : bool, default=False
|
| 1196 |
+
If True, the data is a pandas DataFrame including columns with
|
| 1197 |
+
appropriate dtypes (numeric, string or categorical). The target is
|
| 1198 |
+
a pandas DataFrame or Series depending on the number of target columns.
|
| 1199 |
+
If `return_X_y` is True, then (`data`, `target`) will be pandas
|
| 1200 |
+
DataFrames or Series as described below.
|
| 1201 |
+
|
| 1202 |
+
.. versionadded:: 0.23
|
| 1203 |
+
|
| 1204 |
+
Returns
|
| 1205 |
+
-------
|
| 1206 |
+
data : :class:`~sklearn.utils.Bunch`
|
| 1207 |
+
Dictionary-like object, with the following attributes.
|
| 1208 |
+
|
| 1209 |
+
data : {ndarray, dataframe} of shape (20, 3)
|
| 1210 |
+
The data matrix. If `as_frame=True`, `data` will be a pandas
|
| 1211 |
+
DataFrame.
|
| 1212 |
+
target: {ndarray, dataframe} of shape (20, 3)
|
| 1213 |
+
The regression targets. If `as_frame=True`, `target` will be
|
| 1214 |
+
a pandas DataFrame.
|
| 1215 |
+
feature_names: list
|
| 1216 |
+
The names of the dataset columns.
|
| 1217 |
+
target_names: list
|
| 1218 |
+
The names of the target columns.
|
| 1219 |
+
frame: DataFrame of shape (20, 6)
|
| 1220 |
+
Only present when `as_frame=True`. DataFrame with `data` and
|
| 1221 |
+
`target`.
|
| 1222 |
+
|
| 1223 |
+
.. versionadded:: 0.23
|
| 1224 |
+
DESCR: str
|
| 1225 |
+
The full description of the dataset.
|
| 1226 |
+
data_filename: str
|
| 1227 |
+
The path to the location of the data.
|
| 1228 |
+
target_filename: str
|
| 1229 |
+
The path to the location of the target.
|
| 1230 |
+
|
| 1231 |
+
.. versionadded:: 0.20
|
| 1232 |
+
|
| 1233 |
+
(data, target) : tuple if ``return_X_y`` is True
|
| 1234 |
+
Returns a tuple of two ndarrays or dataframe of shape
|
| 1235 |
+
`(20, 3)`. Each row represents one sample and each column represents the
|
| 1236 |
+
features in `X` and a target in `y` of a given sample.
|
| 1237 |
+
|
| 1238 |
+
.. versionadded:: 0.18
|
| 1239 |
+
|
| 1240 |
+
Examples
|
| 1241 |
+
--------
|
| 1242 |
+
>>> from sklearn.datasets import load_linnerud
|
| 1243 |
+
>>> linnerud = load_linnerud()
|
| 1244 |
+
>>> linnerud.data.shape
|
| 1245 |
+
(20, 3)
|
| 1246 |
+
>>> linnerud.target.shape
|
| 1247 |
+
(20, 3)
|
| 1248 |
+
"""
|
| 1249 |
+
data_filename = "linnerud_exercise.csv"
|
| 1250 |
+
target_filename = "linnerud_physiological.csv"
|
| 1251 |
+
|
| 1252 |
+
data_module_path = resources.files(DATA_MODULE)
|
| 1253 |
+
# Read header and data
|
| 1254 |
+
data_path = data_module_path / data_filename
|
| 1255 |
+
with data_path.open("r", encoding="utf-8") as f:
|
| 1256 |
+
header_exercise = f.readline().split()
|
| 1257 |
+
f.seek(0) # reset file obj
|
| 1258 |
+
data_exercise = np.loadtxt(f, skiprows=1)
|
| 1259 |
+
|
| 1260 |
+
target_path = data_module_path / target_filename
|
| 1261 |
+
with target_path.open("r", encoding="utf-8") as f:
|
| 1262 |
+
header_physiological = f.readline().split()
|
| 1263 |
+
f.seek(0) # reset file obj
|
| 1264 |
+
data_physiological = np.loadtxt(f, skiprows=1)
|
| 1265 |
+
|
| 1266 |
+
fdescr = load_descr("linnerud.rst")
|
| 1267 |
+
|
| 1268 |
+
frame = None
|
| 1269 |
+
if as_frame:
|
| 1270 |
+
(frame, data_exercise, data_physiological) = _convert_data_dataframe(
|
| 1271 |
+
"load_linnerud",
|
| 1272 |
+
data_exercise,
|
| 1273 |
+
data_physiological,
|
| 1274 |
+
header_exercise,
|
| 1275 |
+
header_physiological,
|
| 1276 |
+
)
|
| 1277 |
+
if return_X_y:
|
| 1278 |
+
return data_exercise, data_physiological
|
| 1279 |
+
|
| 1280 |
+
return Bunch(
|
| 1281 |
+
data=data_exercise,
|
| 1282 |
+
feature_names=header_exercise,
|
| 1283 |
+
target=data_physiological,
|
| 1284 |
+
target_names=header_physiological,
|
| 1285 |
+
frame=frame,
|
| 1286 |
+
DESCR=fdescr,
|
| 1287 |
+
data_filename=data_filename,
|
| 1288 |
+
target_filename=target_filename,
|
| 1289 |
+
data_module=DATA_MODULE,
|
| 1290 |
+
)
|
| 1291 |
+
|
| 1292 |
+
|
| 1293 |
+
def load_sample_images():
|
| 1294 |
+
"""Load sample images for image manipulation.
|
| 1295 |
+
|
| 1296 |
+
Loads both, ``china`` and ``flower``.
|
| 1297 |
+
|
| 1298 |
+
Read more in the :ref:`User Guide <sample_images>`.
|
| 1299 |
+
|
| 1300 |
+
Returns
|
| 1301 |
+
-------
|
| 1302 |
+
data : :class:`~sklearn.utils.Bunch`
|
| 1303 |
+
Dictionary-like object, with the following attributes.
|
| 1304 |
+
|
| 1305 |
+
images : list of ndarray of shape (427, 640, 3)
|
| 1306 |
+
The two sample image.
|
| 1307 |
+
filenames : list
|
| 1308 |
+
The filenames for the images.
|
| 1309 |
+
DESCR : str
|
| 1310 |
+
The full description of the dataset.
|
| 1311 |
+
|
| 1312 |
+
Examples
|
| 1313 |
+
--------
|
| 1314 |
+
To load the data and visualize the images:
|
| 1315 |
+
|
| 1316 |
+
>>> from sklearn.datasets import load_sample_images
|
| 1317 |
+
>>> dataset = load_sample_images() #doctest: +SKIP
|
| 1318 |
+
>>> len(dataset.images) #doctest: +SKIP
|
| 1319 |
+
2
|
| 1320 |
+
>>> first_img_data = dataset.images[0] #doctest: +SKIP
|
| 1321 |
+
>>> first_img_data.shape #doctest: +SKIP
|
| 1322 |
+
(427, 640, 3)
|
| 1323 |
+
>>> first_img_data.dtype #doctest: +SKIP
|
| 1324 |
+
dtype('uint8')
|
| 1325 |
+
"""
|
| 1326 |
+
try:
|
| 1327 |
+
from PIL import Image
|
| 1328 |
+
except ImportError:
|
| 1329 |
+
raise ImportError(
|
| 1330 |
+
"The Python Imaging Library (PIL) is required to load data "
|
| 1331 |
+
"from jpeg files. Please refer to "
|
| 1332 |
+
"https://pillow.readthedocs.io/en/stable/installation.html "
|
| 1333 |
+
"for installing PIL."
|
| 1334 |
+
)
|
| 1335 |
+
|
| 1336 |
+
descr = load_descr("README.txt", descr_module=IMAGES_MODULE)
|
| 1337 |
+
|
| 1338 |
+
filenames, images = [], []
|
| 1339 |
+
|
| 1340 |
+
jpg_paths = sorted(
|
| 1341 |
+
resource
|
| 1342 |
+
for resource in resources.files(IMAGES_MODULE).iterdir()
|
| 1343 |
+
if resource.is_file() and resource.match("*.jpg")
|
| 1344 |
+
)
|
| 1345 |
+
|
| 1346 |
+
for path in jpg_paths:
|
| 1347 |
+
filenames.append(str(path))
|
| 1348 |
+
with path.open("rb") as image_file:
|
| 1349 |
+
pil_image = Image.open(image_file)
|
| 1350 |
+
image = np.asarray(pil_image)
|
| 1351 |
+
images.append(image)
|
| 1352 |
+
|
| 1353 |
+
return Bunch(images=images, filenames=filenames, DESCR=descr)
|
| 1354 |
+
|
| 1355 |
+
|
| 1356 |
+
@validate_params(
|
| 1357 |
+
{
|
| 1358 |
+
"image_name": [StrOptions({"china.jpg", "flower.jpg"})],
|
| 1359 |
+
},
|
| 1360 |
+
prefer_skip_nested_validation=True,
|
| 1361 |
+
)
|
| 1362 |
+
def load_sample_image(image_name):
|
| 1363 |
+
"""Load the numpy array of a single sample image.
|
| 1364 |
+
|
| 1365 |
+
Read more in the :ref:`User Guide <sample_images>`.
|
| 1366 |
+
|
| 1367 |
+
Parameters
|
| 1368 |
+
----------
|
| 1369 |
+
image_name : {`china.jpg`, `flower.jpg`}
|
| 1370 |
+
The name of the sample image loaded.
|
| 1371 |
+
|
| 1372 |
+
Returns
|
| 1373 |
+
-------
|
| 1374 |
+
img : 3D array
|
| 1375 |
+
The image as a numpy array: height x width x color.
|
| 1376 |
+
|
| 1377 |
+
Examples
|
| 1378 |
+
--------
|
| 1379 |
+
|
| 1380 |
+
>>> from sklearn.datasets import load_sample_image
|
| 1381 |
+
>>> china = load_sample_image('china.jpg') # doctest: +SKIP
|
| 1382 |
+
>>> china.dtype # doctest: +SKIP
|
| 1383 |
+
dtype('uint8')
|
| 1384 |
+
>>> china.shape # doctest: +SKIP
|
| 1385 |
+
(427, 640, 3)
|
| 1386 |
+
>>> flower = load_sample_image('flower.jpg') # doctest: +SKIP
|
| 1387 |
+
>>> flower.dtype # doctest: +SKIP
|
| 1388 |
+
dtype('uint8')
|
| 1389 |
+
>>> flower.shape # doctest: +SKIP
|
| 1390 |
+
(427, 640, 3)
|
| 1391 |
+
"""
|
| 1392 |
+
images = load_sample_images()
|
| 1393 |
+
index = None
|
| 1394 |
+
for i, filename in enumerate(images.filenames):
|
| 1395 |
+
if filename.endswith(image_name):
|
| 1396 |
+
index = i
|
| 1397 |
+
break
|
| 1398 |
+
if index is None:
|
| 1399 |
+
raise AttributeError("Cannot find sample image: %s" % image_name)
|
| 1400 |
+
return images.images[index]
|
| 1401 |
+
|
| 1402 |
+
|
| 1403 |
+
def _pkl_filepath(*args, **kwargs):
|
| 1404 |
+
"""Return filename for Python 3 pickles
|
| 1405 |
+
|
| 1406 |
+
args[-1] is expected to be the ".pkl" filename. For compatibility with
|
| 1407 |
+
older scikit-learn versions, a suffix is inserted before the extension.
|
| 1408 |
+
|
| 1409 |
+
_pkl_filepath('/path/to/folder', 'filename.pkl') returns
|
| 1410 |
+
'/path/to/folder/filename_py3.pkl'
|
| 1411 |
+
|
| 1412 |
+
"""
|
| 1413 |
+
py3_suffix = kwargs.get("py3_suffix", "_py3")
|
| 1414 |
+
basename, ext = splitext(args[-1])
|
| 1415 |
+
basename += py3_suffix
|
| 1416 |
+
new_args = args[:-1] + (basename + ext,)
|
| 1417 |
+
return join(*new_args)
|
| 1418 |
+
|
| 1419 |
+
|
| 1420 |
+
def _sha256(path):
|
| 1421 |
+
"""Calculate the sha256 hash of the file at path."""
|
| 1422 |
+
sha256hash = hashlib.sha256()
|
| 1423 |
+
chunk_size = 8192
|
| 1424 |
+
with open(path, "rb") as f:
|
| 1425 |
+
while True:
|
| 1426 |
+
buffer = f.read(chunk_size)
|
| 1427 |
+
if not buffer:
|
| 1428 |
+
break
|
| 1429 |
+
sha256hash.update(buffer)
|
| 1430 |
+
return sha256hash.hexdigest()
|
| 1431 |
+
|
| 1432 |
+
|
| 1433 |
+
def _fetch_remote(remote, dirname=None, n_retries=3, delay=1):
|
| 1434 |
+
"""Helper function to download a remote dataset.
|
| 1435 |
+
|
| 1436 |
+
Fetch a dataset pointed by remote's url, save into path using remote's
|
| 1437 |
+
filename and ensure its integrity based on the SHA256 checksum of the
|
| 1438 |
+
downloaded file.
|
| 1439 |
+
|
| 1440 |
+
.. versionchanged:: 1.6
|
| 1441 |
+
|
| 1442 |
+
If the file already exists locally and the SHA256 checksums match, the
|
| 1443 |
+
path to the local file is returned without re-downloading.
|
| 1444 |
+
|
| 1445 |
+
Parameters
|
| 1446 |
+
----------
|
| 1447 |
+
remote : RemoteFileMetadata
|
| 1448 |
+
Named tuple containing remote dataset meta information: url, filename
|
| 1449 |
+
and checksum.
|
| 1450 |
+
|
| 1451 |
+
dirname : str or Path, default=None
|
| 1452 |
+
Directory to save the file to. If None, the current working directory
|
| 1453 |
+
is used.
|
| 1454 |
+
|
| 1455 |
+
n_retries : int, default=3
|
| 1456 |
+
Number of retries when HTTP errors are encountered.
|
| 1457 |
+
|
| 1458 |
+
.. versionadded:: 1.5
|
| 1459 |
+
|
| 1460 |
+
delay : int, default=1
|
| 1461 |
+
Number of seconds between retries.
|
| 1462 |
+
|
| 1463 |
+
.. versionadded:: 1.5
|
| 1464 |
+
|
| 1465 |
+
Returns
|
| 1466 |
+
-------
|
| 1467 |
+
file_path: Path
|
| 1468 |
+
Full path of the created file.
|
| 1469 |
+
"""
|
| 1470 |
+
if dirname is None:
|
| 1471 |
+
folder_path = Path(".")
|
| 1472 |
+
else:
|
| 1473 |
+
folder_path = Path(dirname)
|
| 1474 |
+
|
| 1475 |
+
file_path = folder_path / remote.filename
|
| 1476 |
+
|
| 1477 |
+
if file_path.exists():
|
| 1478 |
+
if remote.checksum is None:
|
| 1479 |
+
return file_path
|
| 1480 |
+
|
| 1481 |
+
checksum = _sha256(file_path)
|
| 1482 |
+
if checksum == remote.checksum:
|
| 1483 |
+
return file_path
|
| 1484 |
+
else:
|
| 1485 |
+
warnings.warn(
|
| 1486 |
+
f"SHA256 checksum of existing local file {file_path.name} "
|
| 1487 |
+
f"({checksum}) differs from expected ({remote.checksum}): "
|
| 1488 |
+
f"re-downloading from {remote.url} ."
|
| 1489 |
+
)
|
| 1490 |
+
|
| 1491 |
+
# We create a temporary file dedicated to this particular download to avoid
|
| 1492 |
+
# conflicts with parallel downloads. If the download is successful, the
|
| 1493 |
+
# temporary file is atomically renamed to the final file path (with
|
| 1494 |
+
# `shutil.move`). We therefore pass `delete=False` to `NamedTemporaryFile`.
|
| 1495 |
+
# Otherwise, garbage collecting temp_file would raise an error when
|
| 1496 |
+
# attempting to delete a file that was already renamed. If the download
|
| 1497 |
+
# fails or the result does not match the expected SHA256 digest, the
|
| 1498 |
+
# temporary file is removed manually in the except block.
|
| 1499 |
+
temp_file = NamedTemporaryFile(
|
| 1500 |
+
prefix=remote.filename + ".part_", dir=folder_path, delete=False
|
| 1501 |
+
)
|
| 1502 |
+
# Note that Python 3.12's `delete_on_close=True` is ignored as we set
|
| 1503 |
+
# `delete=False` explicitly. So after this line the empty temporary file still
|
| 1504 |
+
# exists on disk to make sure that it's uniquely reserved for this specific call of
|
| 1505 |
+
# `_fetch_remote` and therefore it protects against any corruption by parallel
|
| 1506 |
+
# calls.
|
| 1507 |
+
temp_file.close()
|
| 1508 |
+
try:
|
| 1509 |
+
temp_file_path = Path(temp_file.name)
|
| 1510 |
+
while True:
|
| 1511 |
+
try:
|
| 1512 |
+
urlretrieve(remote.url, temp_file_path)
|
| 1513 |
+
break
|
| 1514 |
+
except (URLError, TimeoutError):
|
| 1515 |
+
if n_retries == 0:
|
| 1516 |
+
# If no more retries are left, re-raise the caught exception.
|
| 1517 |
+
raise
|
| 1518 |
+
warnings.warn(f"Retry downloading from url: {remote.url}")
|
| 1519 |
+
n_retries -= 1
|
| 1520 |
+
time.sleep(delay)
|
| 1521 |
+
|
| 1522 |
+
checksum = _sha256(temp_file_path)
|
| 1523 |
+
if remote.checksum is not None and remote.checksum != checksum:
|
| 1524 |
+
raise OSError(
|
| 1525 |
+
f"The SHA256 checksum of {remote.filename} ({checksum}) "
|
| 1526 |
+
f"differs from expected ({remote.checksum})."
|
| 1527 |
+
)
|
| 1528 |
+
except (Exception, KeyboardInterrupt):
|
| 1529 |
+
os.unlink(temp_file.name)
|
| 1530 |
+
raise
|
| 1531 |
+
|
| 1532 |
+
# The following renaming is atomic whenever temp_file_path and
|
| 1533 |
+
# file_path are on the same filesystem. This should be the case most of
|
| 1534 |
+
# the time, but we still use shutil.move instead of os.rename in case
|
| 1535 |
+
# they are not.
|
| 1536 |
+
shutil.move(temp_file_path, file_path)
|
| 1537 |
+
|
| 1538 |
+
return file_path
|
| 1539 |
+
|
| 1540 |
+
|
| 1541 |
+
def _filter_filename(value, filter_dots=True):
|
| 1542 |
+
"""Derive a name that is safe to use as filename from the given string.
|
| 1543 |
+
|
| 1544 |
+
Adapted from the `slugify` function of django:
|
| 1545 |
+
https://github.com/django/django/blob/master/django/utils/text.py
|
| 1546 |
+
|
| 1547 |
+
Convert spaces or repeated dashes to single dashes. Replace characters that
|
| 1548 |
+
aren't alphanumerics, underscores, hyphens or dots by underscores. Convert
|
| 1549 |
+
to lowercase. Also strip leading and trailing whitespace, dashes, and
|
| 1550 |
+
underscores.
|
| 1551 |
+
"""
|
| 1552 |
+
value = unicodedata.normalize("NFKD", value).lower()
|
| 1553 |
+
if filter_dots:
|
| 1554 |
+
value = re.sub(r"[^\w\s-]+", "_", value)
|
| 1555 |
+
else:
|
| 1556 |
+
value = re.sub(r"[^.\w\s-]+", "_", value)
|
| 1557 |
+
value = re.sub(r"[\s-]+", "-", value)
|
| 1558 |
+
return value.strip("-_.")
|
| 1559 |
+
|
| 1560 |
+
|
| 1561 |
+
def _derive_folder_and_filename_from_url(url):
|
| 1562 |
+
parsed_url = urlparse(url)
|
| 1563 |
+
if not parsed_url.hostname:
|
| 1564 |
+
raise ValueError(f"Invalid URL: {url}")
|
| 1565 |
+
folder_components = [_filter_filename(parsed_url.hostname, filter_dots=False)]
|
| 1566 |
+
path = parsed_url.path
|
| 1567 |
+
|
| 1568 |
+
if "/" in path:
|
| 1569 |
+
base_folder, raw_filename = path.rsplit("/", 1)
|
| 1570 |
+
|
| 1571 |
+
base_folder = _filter_filename(base_folder)
|
| 1572 |
+
if base_folder:
|
| 1573 |
+
folder_components.append(base_folder)
|
| 1574 |
+
else:
|
| 1575 |
+
raw_filename = path
|
| 1576 |
+
|
| 1577 |
+
filename = _filter_filename(raw_filename, filter_dots=False)
|
| 1578 |
+
if not filename:
|
| 1579 |
+
filename = "downloaded_file"
|
| 1580 |
+
|
| 1581 |
+
return "/".join(folder_components), filename
|
| 1582 |
+
|
| 1583 |
+
|
| 1584 |
+
def fetch_file(
|
| 1585 |
+
url, folder=None, local_filename=None, sha256=None, n_retries=3, delay=1
|
| 1586 |
+
):
|
| 1587 |
+
"""Fetch a file from the web if not already present in the local folder.
|
| 1588 |
+
|
| 1589 |
+
If the file already exists locally (and the SHA256 checksums match when
|
| 1590 |
+
provided), the path to the local file is returned without re-downloading.
|
| 1591 |
+
|
| 1592 |
+
.. versionadded:: 1.6
|
| 1593 |
+
|
| 1594 |
+
Parameters
|
| 1595 |
+
----------
|
| 1596 |
+
url : str
|
| 1597 |
+
URL of the file to download.
|
| 1598 |
+
|
| 1599 |
+
folder : str or Path, default=None
|
| 1600 |
+
Directory to save the file to. If None, the file is downloaded in a
|
| 1601 |
+
folder with a name derived from the URL host name and path under
|
| 1602 |
+
scikit-learn data home folder.
|
| 1603 |
+
|
| 1604 |
+
local_filename : str, default=None
|
| 1605 |
+
Name of the file to save. If None, the filename is inferred from the
|
| 1606 |
+
URL.
|
| 1607 |
+
|
| 1608 |
+
sha256 : str, default=None
|
| 1609 |
+
SHA256 checksum of the file. If None, no checksum is verified.
|
| 1610 |
+
|
| 1611 |
+
n_retries : int, default=3
|
| 1612 |
+
Number of retries when HTTP errors are encountered.
|
| 1613 |
+
|
| 1614 |
+
delay : int, default=1
|
| 1615 |
+
Number of seconds between retries.
|
| 1616 |
+
|
| 1617 |
+
Returns
|
| 1618 |
+
-------
|
| 1619 |
+
file_path : Path
|
| 1620 |
+
Full path of the downloaded file.
|
| 1621 |
+
"""
|
| 1622 |
+
folder_from_url, filename_from_url = _derive_folder_and_filename_from_url(url)
|
| 1623 |
+
|
| 1624 |
+
if local_filename is None:
|
| 1625 |
+
local_filename = filename_from_url
|
| 1626 |
+
|
| 1627 |
+
if folder is None:
|
| 1628 |
+
folder = Path(get_data_home()) / folder_from_url
|
| 1629 |
+
makedirs(folder, exist_ok=True)
|
| 1630 |
+
|
| 1631 |
+
remote_metadata = RemoteFileMetadata(
|
| 1632 |
+
filename=local_filename, url=url, checksum=sha256
|
| 1633 |
+
)
|
| 1634 |
+
return _fetch_remote(
|
| 1635 |
+
remote_metadata, dirname=folder, n_retries=n_retries, delay=delay
|
| 1636 |
+
)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/datasets/_california_housing.py
ADDED
|
@@ -0,0 +1,248 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""California housing dataset.
|
| 2 |
+
|
| 3 |
+
The original database is available from StatLib
|
| 4 |
+
|
| 5 |
+
http://lib.stat.cmu.edu/datasets/
|
| 6 |
+
|
| 7 |
+
The data contains 20,640 observations on 9 variables.
|
| 8 |
+
|
| 9 |
+
This dataset contains the average house value as target variable
|
| 10 |
+
and the following input variables (features): average income,
|
| 11 |
+
housing average age, average rooms, average bedrooms, population,
|
| 12 |
+
average occupation, latitude, and longitude in that order.
|
| 13 |
+
|
| 14 |
+
References
|
| 15 |
+
----------
|
| 16 |
+
|
| 17 |
+
Pace, R. Kelley and Ronald Barry, Sparse Spatial Autoregressions,
|
| 18 |
+
Statistics and Probability Letters, 33:291-297, 1997.
|
| 19 |
+
|
| 20 |
+
"""
|
| 21 |
+
|
| 22 |
+
# Authors: The scikit-learn developers
|
| 23 |
+
# SPDX-License-Identifier: BSD-3-Clause
|
| 24 |
+
|
| 25 |
+
import logging
|
| 26 |
+
import tarfile
|
| 27 |
+
from numbers import Integral, Real
|
| 28 |
+
from os import PathLike, makedirs, remove
|
| 29 |
+
from os.path import exists
|
| 30 |
+
|
| 31 |
+
import joblib
|
| 32 |
+
import numpy as np
|
| 33 |
+
|
| 34 |
+
from ..utils import Bunch
|
| 35 |
+
from ..utils._param_validation import Interval, validate_params
|
| 36 |
+
from . import get_data_home
|
| 37 |
+
from ._base import (
|
| 38 |
+
RemoteFileMetadata,
|
| 39 |
+
_convert_data_dataframe,
|
| 40 |
+
_fetch_remote,
|
| 41 |
+
_pkl_filepath,
|
| 42 |
+
load_descr,
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
# The original data can be found at:
|
| 46 |
+
# https://www.dcc.fc.up.pt/~ltorgo/Regression/cal_housing.tgz
|
| 47 |
+
ARCHIVE = RemoteFileMetadata(
|
| 48 |
+
filename="cal_housing.tgz",
|
| 49 |
+
url="https://ndownloader.figshare.com/files/5976036",
|
| 50 |
+
checksum="aaa5c9a6afe2225cc2aed2723682ae403280c4a3695a2ddda4ffb5d8215ea681",
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
logger = logging.getLogger(__name__)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
@validate_params(
|
| 57 |
+
{
|
| 58 |
+
"data_home": [str, PathLike, None],
|
| 59 |
+
"download_if_missing": ["boolean"],
|
| 60 |
+
"return_X_y": ["boolean"],
|
| 61 |
+
"as_frame": ["boolean"],
|
| 62 |
+
"n_retries": [Interval(Integral, 1, None, closed="left")],
|
| 63 |
+
"delay": [Interval(Real, 0.0, None, closed="neither")],
|
| 64 |
+
},
|
| 65 |
+
prefer_skip_nested_validation=True,
|
| 66 |
+
)
|
| 67 |
+
def fetch_california_housing(
|
| 68 |
+
*,
|
| 69 |
+
data_home=None,
|
| 70 |
+
download_if_missing=True,
|
| 71 |
+
return_X_y=False,
|
| 72 |
+
as_frame=False,
|
| 73 |
+
n_retries=3,
|
| 74 |
+
delay=1.0,
|
| 75 |
+
):
|
| 76 |
+
"""Load the California housing dataset (regression).
|
| 77 |
+
|
| 78 |
+
============== ==============
|
| 79 |
+
Samples total 20640
|
| 80 |
+
Dimensionality 8
|
| 81 |
+
Features real
|
| 82 |
+
Target real 0.15 - 5.
|
| 83 |
+
============== ==============
|
| 84 |
+
|
| 85 |
+
Read more in the :ref:`User Guide <california_housing_dataset>`.
|
| 86 |
+
|
| 87 |
+
Parameters
|
| 88 |
+
----------
|
| 89 |
+
data_home : str or path-like, default=None
|
| 90 |
+
Specify another download and cache folder for the datasets. By default
|
| 91 |
+
all scikit-learn data is stored in '~/scikit_learn_data' subfolders.
|
| 92 |
+
|
| 93 |
+
download_if_missing : bool, default=True
|
| 94 |
+
If False, raise an OSError if the data is not locally available
|
| 95 |
+
instead of trying to download the data from the source site.
|
| 96 |
+
|
| 97 |
+
return_X_y : bool, default=False
|
| 98 |
+
If True, returns ``(data.data, data.target)`` instead of a Bunch
|
| 99 |
+
object.
|
| 100 |
+
|
| 101 |
+
.. versionadded:: 0.20
|
| 102 |
+
|
| 103 |
+
as_frame : bool, default=False
|
| 104 |
+
If True, the data is a pandas DataFrame including columns with
|
| 105 |
+
appropriate dtypes (numeric, string or categorical). The target is
|
| 106 |
+
a pandas DataFrame or Series depending on the number of target_columns.
|
| 107 |
+
|
| 108 |
+
.. versionadded:: 0.23
|
| 109 |
+
|
| 110 |
+
n_retries : int, default=3
|
| 111 |
+
Number of retries when HTTP errors are encountered.
|
| 112 |
+
|
| 113 |
+
.. versionadded:: 1.5
|
| 114 |
+
|
| 115 |
+
delay : float, default=1.0
|
| 116 |
+
Number of seconds between retries.
|
| 117 |
+
|
| 118 |
+
.. versionadded:: 1.5
|
| 119 |
+
|
| 120 |
+
Returns
|
| 121 |
+
-------
|
| 122 |
+
dataset : :class:`~sklearn.utils.Bunch`
|
| 123 |
+
Dictionary-like object, with the following attributes.
|
| 124 |
+
|
| 125 |
+
data : ndarray, shape (20640, 8)
|
| 126 |
+
Each row corresponding to the 8 feature values in order.
|
| 127 |
+
If ``as_frame`` is True, ``data`` is a pandas object.
|
| 128 |
+
target : numpy array of shape (20640,)
|
| 129 |
+
Each value corresponds to the average
|
| 130 |
+
house value in units of 100,000.
|
| 131 |
+
If ``as_frame`` is True, ``target`` is a pandas object.
|
| 132 |
+
feature_names : list of length 8
|
| 133 |
+
Array of ordered feature names used in the dataset.
|
| 134 |
+
DESCR : str
|
| 135 |
+
Description of the California housing dataset.
|
| 136 |
+
frame : pandas DataFrame
|
| 137 |
+
Only present when `as_frame=True`. DataFrame with ``data`` and
|
| 138 |
+
``target``.
|
| 139 |
+
|
| 140 |
+
.. versionadded:: 0.23
|
| 141 |
+
|
| 142 |
+
(data, target) : tuple if ``return_X_y`` is True
|
| 143 |
+
A tuple of two ndarray. The first containing a 2D array of
|
| 144 |
+
shape (n_samples, n_features) with each row representing one
|
| 145 |
+
sample and each column representing the features. The second
|
| 146 |
+
ndarray of shape (n_samples,) containing the target samples.
|
| 147 |
+
|
| 148 |
+
.. versionadded:: 0.20
|
| 149 |
+
|
| 150 |
+
Notes
|
| 151 |
+
-----
|
| 152 |
+
|
| 153 |
+
This dataset consists of 20,640 samples and 9 features.
|
| 154 |
+
|
| 155 |
+
Examples
|
| 156 |
+
--------
|
| 157 |
+
>>> from sklearn.datasets import fetch_california_housing
|
| 158 |
+
>>> housing = fetch_california_housing()
|
| 159 |
+
>>> print(housing.data.shape, housing.target.shape)
|
| 160 |
+
(20640, 8) (20640,)
|
| 161 |
+
>>> print(housing.feature_names[0:6])
|
| 162 |
+
['MedInc', 'HouseAge', 'AveRooms', 'AveBedrms', 'Population', 'AveOccup']
|
| 163 |
+
"""
|
| 164 |
+
data_home = get_data_home(data_home=data_home)
|
| 165 |
+
if not exists(data_home):
|
| 166 |
+
makedirs(data_home)
|
| 167 |
+
|
| 168 |
+
filepath = _pkl_filepath(data_home, "cal_housing.pkz")
|
| 169 |
+
if not exists(filepath):
|
| 170 |
+
if not download_if_missing:
|
| 171 |
+
raise OSError("Data not found and `download_if_missing` is False")
|
| 172 |
+
|
| 173 |
+
logger.info(
|
| 174 |
+
"Downloading Cal. housing from {} to {}".format(ARCHIVE.url, data_home)
|
| 175 |
+
)
|
| 176 |
+
|
| 177 |
+
archive_path = _fetch_remote(
|
| 178 |
+
ARCHIVE,
|
| 179 |
+
dirname=data_home,
|
| 180 |
+
n_retries=n_retries,
|
| 181 |
+
delay=delay,
|
| 182 |
+
)
|
| 183 |
+
|
| 184 |
+
with tarfile.open(mode="r:gz", name=archive_path) as f:
|
| 185 |
+
cal_housing = np.loadtxt(
|
| 186 |
+
f.extractfile("CaliforniaHousing/cal_housing.data"), delimiter=","
|
| 187 |
+
)
|
| 188 |
+
# Columns are not in the same order compared to the previous
|
| 189 |
+
# URL resource on lib.stat.cmu.edu
|
| 190 |
+
columns_index = [8, 7, 2, 3, 4, 5, 6, 1, 0]
|
| 191 |
+
cal_housing = cal_housing[:, columns_index]
|
| 192 |
+
|
| 193 |
+
joblib.dump(cal_housing, filepath, compress=6)
|
| 194 |
+
remove(archive_path)
|
| 195 |
+
|
| 196 |
+
else:
|
| 197 |
+
cal_housing = joblib.load(filepath)
|
| 198 |
+
|
| 199 |
+
feature_names = [
|
| 200 |
+
"MedInc",
|
| 201 |
+
"HouseAge",
|
| 202 |
+
"AveRooms",
|
| 203 |
+
"AveBedrms",
|
| 204 |
+
"Population",
|
| 205 |
+
"AveOccup",
|
| 206 |
+
"Latitude",
|
| 207 |
+
"Longitude",
|
| 208 |
+
]
|
| 209 |
+
|
| 210 |
+
target, data = cal_housing[:, 0], cal_housing[:, 1:]
|
| 211 |
+
|
| 212 |
+
# avg rooms = total rooms / households
|
| 213 |
+
data[:, 2] /= data[:, 5]
|
| 214 |
+
|
| 215 |
+
# avg bed rooms = total bed rooms / households
|
| 216 |
+
data[:, 3] /= data[:, 5]
|
| 217 |
+
|
| 218 |
+
# avg occupancy = population / households
|
| 219 |
+
data[:, 5] = data[:, 4] / data[:, 5]
|
| 220 |
+
|
| 221 |
+
# target in units of 100,000
|
| 222 |
+
target = target / 100000.0
|
| 223 |
+
|
| 224 |
+
descr = load_descr("california_housing.rst")
|
| 225 |
+
|
| 226 |
+
X = data
|
| 227 |
+
y = target
|
| 228 |
+
|
| 229 |
+
frame = None
|
| 230 |
+
target_names = [
|
| 231 |
+
"MedHouseVal",
|
| 232 |
+
]
|
| 233 |
+
if as_frame:
|
| 234 |
+
frame, X, y = _convert_data_dataframe(
|
| 235 |
+
"fetch_california_housing", data, target, feature_names, target_names
|
| 236 |
+
)
|
| 237 |
+
|
| 238 |
+
if return_X_y:
|
| 239 |
+
return X, y
|
| 240 |
+
|
| 241 |
+
return Bunch(
|
| 242 |
+
data=X,
|
| 243 |
+
target=y,
|
| 244 |
+
frame=frame,
|
| 245 |
+
target_names=target_names,
|
| 246 |
+
feature_names=feature_names,
|
| 247 |
+
DESCR=descr,
|
| 248 |
+
)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/datasets/_covtype.py
ADDED
|
@@ -0,0 +1,252 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Forest covertype dataset.
|
| 2 |
+
|
| 3 |
+
A classic dataset for classification benchmarks, featuring categorical and
|
| 4 |
+
real-valued features.
|
| 5 |
+
|
| 6 |
+
The dataset page is available from UCI Machine Learning Repository
|
| 7 |
+
|
| 8 |
+
https://archive.ics.uci.edu/ml/datasets/Covertype
|
| 9 |
+
|
| 10 |
+
Courtesy of Jock A. Blackard and Colorado State University.
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
# Authors: The scikit-learn developers
|
| 14 |
+
# SPDX-License-Identifier: BSD-3-Clause
|
| 15 |
+
|
| 16 |
+
import logging
|
| 17 |
+
import os
|
| 18 |
+
from gzip import GzipFile
|
| 19 |
+
from numbers import Integral, Real
|
| 20 |
+
from os.path import exists, join
|
| 21 |
+
from tempfile import TemporaryDirectory
|
| 22 |
+
|
| 23 |
+
import joblib
|
| 24 |
+
import numpy as np
|
| 25 |
+
|
| 26 |
+
from ..utils import Bunch, check_random_state
|
| 27 |
+
from ..utils._param_validation import Interval, validate_params
|
| 28 |
+
from . import get_data_home
|
| 29 |
+
from ._base import (
|
| 30 |
+
RemoteFileMetadata,
|
| 31 |
+
_convert_data_dataframe,
|
| 32 |
+
_fetch_remote,
|
| 33 |
+
_pkl_filepath,
|
| 34 |
+
load_descr,
|
| 35 |
+
)
|
| 36 |
+
|
| 37 |
+
# The original data can be found in:
|
| 38 |
+
# https://archive.ics.uci.edu/ml/machine-learning-databases/covtype/covtype.data.gz
|
| 39 |
+
ARCHIVE = RemoteFileMetadata(
|
| 40 |
+
filename="covtype.data.gz",
|
| 41 |
+
url="https://ndownloader.figshare.com/files/5976039",
|
| 42 |
+
checksum="614360d0257557dd1792834a85a1cdebfadc3c4f30b011d56afee7ffb5b15771",
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
logger = logging.getLogger(__name__)
|
| 46 |
+
|
| 47 |
+
# Column names reference:
|
| 48 |
+
# https://archive.ics.uci.edu/ml/machine-learning-databases/covtype/covtype.info
|
| 49 |
+
FEATURE_NAMES = [
|
| 50 |
+
"Elevation",
|
| 51 |
+
"Aspect",
|
| 52 |
+
"Slope",
|
| 53 |
+
"Horizontal_Distance_To_Hydrology",
|
| 54 |
+
"Vertical_Distance_To_Hydrology",
|
| 55 |
+
"Horizontal_Distance_To_Roadways",
|
| 56 |
+
"Hillshade_9am",
|
| 57 |
+
"Hillshade_Noon",
|
| 58 |
+
"Hillshade_3pm",
|
| 59 |
+
"Horizontal_Distance_To_Fire_Points",
|
| 60 |
+
]
|
| 61 |
+
FEATURE_NAMES += [f"Wilderness_Area_{i}" for i in range(4)]
|
| 62 |
+
FEATURE_NAMES += [f"Soil_Type_{i}" for i in range(40)]
|
| 63 |
+
TARGET_NAMES = ["Cover_Type"]
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
@validate_params(
|
| 67 |
+
{
|
| 68 |
+
"data_home": [str, os.PathLike, None],
|
| 69 |
+
"download_if_missing": ["boolean"],
|
| 70 |
+
"random_state": ["random_state"],
|
| 71 |
+
"shuffle": ["boolean"],
|
| 72 |
+
"return_X_y": ["boolean"],
|
| 73 |
+
"as_frame": ["boolean"],
|
| 74 |
+
"n_retries": [Interval(Integral, 1, None, closed="left")],
|
| 75 |
+
"delay": [Interval(Real, 0.0, None, closed="neither")],
|
| 76 |
+
},
|
| 77 |
+
prefer_skip_nested_validation=True,
|
| 78 |
+
)
|
| 79 |
+
def fetch_covtype(
|
| 80 |
+
*,
|
| 81 |
+
data_home=None,
|
| 82 |
+
download_if_missing=True,
|
| 83 |
+
random_state=None,
|
| 84 |
+
shuffle=False,
|
| 85 |
+
return_X_y=False,
|
| 86 |
+
as_frame=False,
|
| 87 |
+
n_retries=3,
|
| 88 |
+
delay=1.0,
|
| 89 |
+
):
|
| 90 |
+
"""Load the covertype dataset (classification).
|
| 91 |
+
|
| 92 |
+
Download it if necessary.
|
| 93 |
+
|
| 94 |
+
================= ============
|
| 95 |
+
Classes 7
|
| 96 |
+
Samples total 581012
|
| 97 |
+
Dimensionality 54
|
| 98 |
+
Features int
|
| 99 |
+
================= ============
|
| 100 |
+
|
| 101 |
+
Read more in the :ref:`User Guide <covtype_dataset>`.
|
| 102 |
+
|
| 103 |
+
Parameters
|
| 104 |
+
----------
|
| 105 |
+
data_home : str or path-like, default=None
|
| 106 |
+
Specify another download and cache folder for the datasets. By default
|
| 107 |
+
all scikit-learn data is stored in '~/scikit_learn_data' subfolders.
|
| 108 |
+
|
| 109 |
+
download_if_missing : bool, default=True
|
| 110 |
+
If False, raise an OSError if the data is not locally available
|
| 111 |
+
instead of trying to download the data from the source site.
|
| 112 |
+
|
| 113 |
+
random_state : int, RandomState instance or None, default=None
|
| 114 |
+
Determines random number generation for dataset shuffling. Pass an int
|
| 115 |
+
for reproducible output across multiple function calls.
|
| 116 |
+
See :term:`Glossary <random_state>`.
|
| 117 |
+
|
| 118 |
+
shuffle : bool, default=False
|
| 119 |
+
Whether to shuffle dataset.
|
| 120 |
+
|
| 121 |
+
return_X_y : bool, default=False
|
| 122 |
+
If True, returns ``(data.data, data.target)`` instead of a Bunch
|
| 123 |
+
object.
|
| 124 |
+
|
| 125 |
+
.. versionadded:: 0.20
|
| 126 |
+
|
| 127 |
+
as_frame : bool, default=False
|
| 128 |
+
If True, the data is a pandas DataFrame including columns with
|
| 129 |
+
appropriate dtypes (numeric). The target is a pandas DataFrame or
|
| 130 |
+
Series depending on the number of target columns. If `return_X_y` is
|
| 131 |
+
True, then (`data`, `target`) will be pandas DataFrames or Series as
|
| 132 |
+
described below.
|
| 133 |
+
|
| 134 |
+
.. versionadded:: 0.24
|
| 135 |
+
|
| 136 |
+
n_retries : int, default=3
|
| 137 |
+
Number of retries when HTTP errors are encountered.
|
| 138 |
+
|
| 139 |
+
.. versionadded:: 1.5
|
| 140 |
+
|
| 141 |
+
delay : float, default=1.0
|
| 142 |
+
Number of seconds between retries.
|
| 143 |
+
|
| 144 |
+
.. versionadded:: 1.5
|
| 145 |
+
|
| 146 |
+
Returns
|
| 147 |
+
-------
|
| 148 |
+
dataset : :class:`~sklearn.utils.Bunch`
|
| 149 |
+
Dictionary-like object, with the following attributes.
|
| 150 |
+
|
| 151 |
+
data : ndarray of shape (581012, 54)
|
| 152 |
+
Each row corresponds to the 54 features in the dataset.
|
| 153 |
+
target : ndarray of shape (581012,)
|
| 154 |
+
Each value corresponds to one of
|
| 155 |
+
the 7 forest covertypes with values
|
| 156 |
+
ranging between 1 to 7.
|
| 157 |
+
frame : dataframe of shape (581012, 55)
|
| 158 |
+
Only present when `as_frame=True`. Contains `data` and `target`.
|
| 159 |
+
DESCR : str
|
| 160 |
+
Description of the forest covertype dataset.
|
| 161 |
+
feature_names : list
|
| 162 |
+
The names of the dataset columns.
|
| 163 |
+
target_names: list
|
| 164 |
+
The names of the target columns.
|
| 165 |
+
|
| 166 |
+
(data, target) : tuple if ``return_X_y`` is True
|
| 167 |
+
A tuple of two ndarray. The first containing a 2D array of
|
| 168 |
+
shape (n_samples, n_features) with each row representing one
|
| 169 |
+
sample and each column representing the features. The second
|
| 170 |
+
ndarray of shape (n_samples,) containing the target samples.
|
| 171 |
+
|
| 172 |
+
.. versionadded:: 0.20
|
| 173 |
+
|
| 174 |
+
Examples
|
| 175 |
+
--------
|
| 176 |
+
>>> from sklearn.datasets import fetch_covtype
|
| 177 |
+
>>> cov_type = fetch_covtype()
|
| 178 |
+
>>> cov_type.data.shape
|
| 179 |
+
(581012, 54)
|
| 180 |
+
>>> cov_type.target.shape
|
| 181 |
+
(581012,)
|
| 182 |
+
>>> # Let's check the 4 first feature names
|
| 183 |
+
>>> cov_type.feature_names[:4]
|
| 184 |
+
['Elevation', 'Aspect', 'Slope', 'Horizontal_Distance_To_Hydrology']
|
| 185 |
+
"""
|
| 186 |
+
data_home = get_data_home(data_home=data_home)
|
| 187 |
+
covtype_dir = join(data_home, "covertype")
|
| 188 |
+
samples_path = _pkl_filepath(covtype_dir, "samples")
|
| 189 |
+
targets_path = _pkl_filepath(covtype_dir, "targets")
|
| 190 |
+
available = exists(samples_path) and exists(targets_path)
|
| 191 |
+
|
| 192 |
+
if download_if_missing and not available:
|
| 193 |
+
os.makedirs(covtype_dir, exist_ok=True)
|
| 194 |
+
|
| 195 |
+
# Creating temp_dir as a direct subdirectory of the target directory
|
| 196 |
+
# guarantees that both reside on the same filesystem, so that we can use
|
| 197 |
+
# os.rename to atomically move the data files to their target location.
|
| 198 |
+
with TemporaryDirectory(dir=covtype_dir) as temp_dir:
|
| 199 |
+
logger.info(f"Downloading {ARCHIVE.url}")
|
| 200 |
+
archive_path = _fetch_remote(
|
| 201 |
+
ARCHIVE, dirname=temp_dir, n_retries=n_retries, delay=delay
|
| 202 |
+
)
|
| 203 |
+
Xy = np.genfromtxt(GzipFile(filename=archive_path), delimiter=",")
|
| 204 |
+
|
| 205 |
+
X = Xy[:, :-1]
|
| 206 |
+
y = Xy[:, -1].astype(np.int32, copy=False)
|
| 207 |
+
|
| 208 |
+
samples_tmp_path = _pkl_filepath(temp_dir, "samples")
|
| 209 |
+
joblib.dump(X, samples_tmp_path, compress=9)
|
| 210 |
+
os.rename(samples_tmp_path, samples_path)
|
| 211 |
+
|
| 212 |
+
targets_tmp_path = _pkl_filepath(temp_dir, "targets")
|
| 213 |
+
joblib.dump(y, targets_tmp_path, compress=9)
|
| 214 |
+
os.rename(targets_tmp_path, targets_path)
|
| 215 |
+
|
| 216 |
+
elif not available and not download_if_missing:
|
| 217 |
+
raise OSError("Data not found and `download_if_missing` is False")
|
| 218 |
+
try:
|
| 219 |
+
X, y
|
| 220 |
+
except NameError:
|
| 221 |
+
X = joblib.load(samples_path)
|
| 222 |
+
y = joblib.load(targets_path)
|
| 223 |
+
|
| 224 |
+
if shuffle:
|
| 225 |
+
ind = np.arange(X.shape[0])
|
| 226 |
+
rng = check_random_state(random_state)
|
| 227 |
+
rng.shuffle(ind)
|
| 228 |
+
X = X[ind]
|
| 229 |
+
y = y[ind]
|
| 230 |
+
|
| 231 |
+
fdescr = load_descr("covtype.rst")
|
| 232 |
+
|
| 233 |
+
frame = None
|
| 234 |
+
if as_frame:
|
| 235 |
+
frame, X, y = _convert_data_dataframe(
|
| 236 |
+
caller_name="fetch_covtype",
|
| 237 |
+
data=X,
|
| 238 |
+
target=y,
|
| 239 |
+
feature_names=FEATURE_NAMES,
|
| 240 |
+
target_names=TARGET_NAMES,
|
| 241 |
+
)
|
| 242 |
+
if return_X_y:
|
| 243 |
+
return X, y
|
| 244 |
+
|
| 245 |
+
return Bunch(
|
| 246 |
+
data=X,
|
| 247 |
+
target=y,
|
| 248 |
+
frame=frame,
|
| 249 |
+
target_names=TARGET_NAMES,
|
| 250 |
+
feature_names=FEATURE_NAMES,
|
| 251 |
+
DESCR=fdescr,
|
| 252 |
+
)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/datasets/_kddcup99.py
ADDED
|
@@ -0,0 +1,429 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""KDDCUP 99 dataset.
|
| 2 |
+
|
| 3 |
+
A classic dataset for anomaly detection.
|
| 4 |
+
|
| 5 |
+
The dataset page is available from UCI Machine Learning Repository
|
| 6 |
+
|
| 7 |
+
https://archive.ics.uci.edu/ml/machine-learning-databases/kddcup99-mld/kddcup.data.gz
|
| 8 |
+
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
# Authors: The scikit-learn developers
|
| 12 |
+
# SPDX-License-Identifier: BSD-3-Clause
|
| 13 |
+
|
| 14 |
+
import errno
|
| 15 |
+
import logging
|
| 16 |
+
import os
|
| 17 |
+
from gzip import GzipFile
|
| 18 |
+
from numbers import Integral, Real
|
| 19 |
+
from os.path import exists, join
|
| 20 |
+
|
| 21 |
+
import joblib
|
| 22 |
+
import numpy as np
|
| 23 |
+
|
| 24 |
+
from ..utils import Bunch, check_random_state
|
| 25 |
+
from ..utils import shuffle as shuffle_method
|
| 26 |
+
from ..utils._param_validation import Interval, StrOptions, validate_params
|
| 27 |
+
from . import get_data_home
|
| 28 |
+
from ._base import (
|
| 29 |
+
RemoteFileMetadata,
|
| 30 |
+
_convert_data_dataframe,
|
| 31 |
+
_fetch_remote,
|
| 32 |
+
load_descr,
|
| 33 |
+
)
|
| 34 |
+
|
| 35 |
+
# The original data can be found at:
|
| 36 |
+
# https://archive.ics.uci.edu/ml/machine-learning-databases/kddcup99-mld/kddcup.data.gz
|
| 37 |
+
ARCHIVE = RemoteFileMetadata(
|
| 38 |
+
filename="kddcup99_data",
|
| 39 |
+
url="https://ndownloader.figshare.com/files/5976045",
|
| 40 |
+
checksum="3b6c942aa0356c0ca35b7b595a26c89d343652c9db428893e7494f837b274292",
|
| 41 |
+
)
|
| 42 |
+
|
| 43 |
+
# The original data can be found at:
|
| 44 |
+
# https://archive.ics.uci.edu/ml/machine-learning-databases/kddcup99-mld/kddcup.data_10_percent.gz
|
| 45 |
+
ARCHIVE_10_PERCENT = RemoteFileMetadata(
|
| 46 |
+
filename="kddcup99_10_data",
|
| 47 |
+
url="https://ndownloader.figshare.com/files/5976042",
|
| 48 |
+
checksum="8045aca0d84e70e622d1148d7df782496f6333bf6eb979a1b0837c42a9fd9561",
|
| 49 |
+
)
|
| 50 |
+
|
| 51 |
+
logger = logging.getLogger(__name__)
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
@validate_params(
|
| 55 |
+
{
|
| 56 |
+
"subset": [StrOptions({"SA", "SF", "http", "smtp"}), None],
|
| 57 |
+
"data_home": [str, os.PathLike, None],
|
| 58 |
+
"shuffle": ["boolean"],
|
| 59 |
+
"random_state": ["random_state"],
|
| 60 |
+
"percent10": ["boolean"],
|
| 61 |
+
"download_if_missing": ["boolean"],
|
| 62 |
+
"return_X_y": ["boolean"],
|
| 63 |
+
"as_frame": ["boolean"],
|
| 64 |
+
"n_retries": [Interval(Integral, 1, None, closed="left")],
|
| 65 |
+
"delay": [Interval(Real, 0.0, None, closed="neither")],
|
| 66 |
+
},
|
| 67 |
+
prefer_skip_nested_validation=True,
|
| 68 |
+
)
|
| 69 |
+
def fetch_kddcup99(
|
| 70 |
+
*,
|
| 71 |
+
subset=None,
|
| 72 |
+
data_home=None,
|
| 73 |
+
shuffle=False,
|
| 74 |
+
random_state=None,
|
| 75 |
+
percent10=True,
|
| 76 |
+
download_if_missing=True,
|
| 77 |
+
return_X_y=False,
|
| 78 |
+
as_frame=False,
|
| 79 |
+
n_retries=3,
|
| 80 |
+
delay=1.0,
|
| 81 |
+
):
|
| 82 |
+
"""Load the kddcup99 dataset (classification).
|
| 83 |
+
|
| 84 |
+
Download it if necessary.
|
| 85 |
+
|
| 86 |
+
================= ====================================
|
| 87 |
+
Classes 23
|
| 88 |
+
Samples total 4898431
|
| 89 |
+
Dimensionality 41
|
| 90 |
+
Features discrete (int) or continuous (float)
|
| 91 |
+
================= ====================================
|
| 92 |
+
|
| 93 |
+
Read more in the :ref:`User Guide <kddcup99_dataset>`.
|
| 94 |
+
|
| 95 |
+
.. versionadded:: 0.18
|
| 96 |
+
|
| 97 |
+
Parameters
|
| 98 |
+
----------
|
| 99 |
+
subset : {'SA', 'SF', 'http', 'smtp'}, default=None
|
| 100 |
+
To return the corresponding classical subsets of kddcup 99.
|
| 101 |
+
If None, return the entire kddcup 99 dataset.
|
| 102 |
+
|
| 103 |
+
data_home : str or path-like, default=None
|
| 104 |
+
Specify another download and cache folder for the datasets. By default
|
| 105 |
+
all scikit-learn data is stored in '~/scikit_learn_data' subfolders.
|
| 106 |
+
|
| 107 |
+
.. versionadded:: 0.19
|
| 108 |
+
|
| 109 |
+
shuffle : bool, default=False
|
| 110 |
+
Whether to shuffle dataset.
|
| 111 |
+
|
| 112 |
+
random_state : int, RandomState instance or None, default=None
|
| 113 |
+
Determines random number generation for dataset shuffling and for
|
| 114 |
+
selection of abnormal samples if `subset='SA'`. Pass an int for
|
| 115 |
+
reproducible output across multiple function calls.
|
| 116 |
+
See :term:`Glossary <random_state>`.
|
| 117 |
+
|
| 118 |
+
percent10 : bool, default=True
|
| 119 |
+
Whether to load only 10 percent of the data.
|
| 120 |
+
|
| 121 |
+
download_if_missing : bool, default=True
|
| 122 |
+
If False, raise an OSError if the data is not locally available
|
| 123 |
+
instead of trying to download the data from the source site.
|
| 124 |
+
|
| 125 |
+
return_X_y : bool, default=False
|
| 126 |
+
If True, returns ``(data, target)`` instead of a Bunch object. See
|
| 127 |
+
below for more information about the `data` and `target` object.
|
| 128 |
+
|
| 129 |
+
.. versionadded:: 0.20
|
| 130 |
+
|
| 131 |
+
as_frame : bool, default=False
|
| 132 |
+
If `True`, returns a pandas Dataframe for the ``data`` and ``target``
|
| 133 |
+
objects in the `Bunch` returned object; `Bunch` return object will also
|
| 134 |
+
have a ``frame`` member.
|
| 135 |
+
|
| 136 |
+
.. versionadded:: 0.24
|
| 137 |
+
|
| 138 |
+
n_retries : int, default=3
|
| 139 |
+
Number of retries when HTTP errors are encountered.
|
| 140 |
+
|
| 141 |
+
.. versionadded:: 1.5
|
| 142 |
+
|
| 143 |
+
delay : float, default=1.0
|
| 144 |
+
Number of seconds between retries.
|
| 145 |
+
|
| 146 |
+
.. versionadded:: 1.5
|
| 147 |
+
|
| 148 |
+
Returns
|
| 149 |
+
-------
|
| 150 |
+
data : :class:`~sklearn.utils.Bunch`
|
| 151 |
+
Dictionary-like object, with the following attributes.
|
| 152 |
+
|
| 153 |
+
data : {ndarray, dataframe} of shape (494021, 41)
|
| 154 |
+
The data matrix to learn. If `as_frame=True`, `data` will be a
|
| 155 |
+
pandas DataFrame.
|
| 156 |
+
target : {ndarray, series} of shape (494021,)
|
| 157 |
+
The regression target for each sample. If `as_frame=True`, `target`
|
| 158 |
+
will be a pandas Series.
|
| 159 |
+
frame : dataframe of shape (494021, 42)
|
| 160 |
+
Only present when `as_frame=True`. Contains `data` and `target`.
|
| 161 |
+
DESCR : str
|
| 162 |
+
The full description of the dataset.
|
| 163 |
+
feature_names : list
|
| 164 |
+
The names of the dataset columns
|
| 165 |
+
target_names: list
|
| 166 |
+
The names of the target columns
|
| 167 |
+
|
| 168 |
+
(data, target) : tuple if ``return_X_y`` is True
|
| 169 |
+
A tuple of two ndarray. The first containing a 2D array of
|
| 170 |
+
shape (n_samples, n_features) with each row representing one
|
| 171 |
+
sample and each column representing the features. The second
|
| 172 |
+
ndarray of shape (n_samples,) containing the target samples.
|
| 173 |
+
|
| 174 |
+
.. versionadded:: 0.20
|
| 175 |
+
"""
|
| 176 |
+
data_home = get_data_home(data_home=data_home)
|
| 177 |
+
kddcup99 = _fetch_brute_kddcup99(
|
| 178 |
+
data_home=data_home,
|
| 179 |
+
percent10=percent10,
|
| 180 |
+
download_if_missing=download_if_missing,
|
| 181 |
+
n_retries=n_retries,
|
| 182 |
+
delay=delay,
|
| 183 |
+
)
|
| 184 |
+
|
| 185 |
+
data = kddcup99.data
|
| 186 |
+
target = kddcup99.target
|
| 187 |
+
feature_names = kddcup99.feature_names
|
| 188 |
+
target_names = kddcup99.target_names
|
| 189 |
+
|
| 190 |
+
if subset == "SA":
|
| 191 |
+
s = target == b"normal."
|
| 192 |
+
t = np.logical_not(s)
|
| 193 |
+
normal_samples = data[s, :]
|
| 194 |
+
normal_targets = target[s]
|
| 195 |
+
abnormal_samples = data[t, :]
|
| 196 |
+
abnormal_targets = target[t]
|
| 197 |
+
|
| 198 |
+
n_samples_abnormal = abnormal_samples.shape[0]
|
| 199 |
+
# selected abnormal samples:
|
| 200 |
+
random_state = check_random_state(random_state)
|
| 201 |
+
r = random_state.randint(0, n_samples_abnormal, 3377)
|
| 202 |
+
abnormal_samples = abnormal_samples[r]
|
| 203 |
+
abnormal_targets = abnormal_targets[r]
|
| 204 |
+
|
| 205 |
+
data = np.r_[normal_samples, abnormal_samples]
|
| 206 |
+
target = np.r_[normal_targets, abnormal_targets]
|
| 207 |
+
|
| 208 |
+
if subset == "SF" or subset == "http" or subset == "smtp":
|
| 209 |
+
# select all samples with positive logged_in attribute:
|
| 210 |
+
s = data[:, 11] == 1
|
| 211 |
+
data = np.c_[data[s, :11], data[s, 12:]]
|
| 212 |
+
feature_names = feature_names[:11] + feature_names[12:]
|
| 213 |
+
target = target[s]
|
| 214 |
+
|
| 215 |
+
data[:, 0] = np.log((data[:, 0] + 0.1).astype(float, copy=False))
|
| 216 |
+
data[:, 4] = np.log((data[:, 4] + 0.1).astype(float, copy=False))
|
| 217 |
+
data[:, 5] = np.log((data[:, 5] + 0.1).astype(float, copy=False))
|
| 218 |
+
|
| 219 |
+
if subset == "http":
|
| 220 |
+
s = data[:, 2] == b"http"
|
| 221 |
+
data = data[s]
|
| 222 |
+
target = target[s]
|
| 223 |
+
data = np.c_[data[:, 0], data[:, 4], data[:, 5]]
|
| 224 |
+
feature_names = [feature_names[0], feature_names[4], feature_names[5]]
|
| 225 |
+
|
| 226 |
+
if subset == "smtp":
|
| 227 |
+
s = data[:, 2] == b"smtp"
|
| 228 |
+
data = data[s]
|
| 229 |
+
target = target[s]
|
| 230 |
+
data = np.c_[data[:, 0], data[:, 4], data[:, 5]]
|
| 231 |
+
feature_names = [feature_names[0], feature_names[4], feature_names[5]]
|
| 232 |
+
|
| 233 |
+
if subset == "SF":
|
| 234 |
+
data = np.c_[data[:, 0], data[:, 2], data[:, 4], data[:, 5]]
|
| 235 |
+
feature_names = [
|
| 236 |
+
feature_names[0],
|
| 237 |
+
feature_names[2],
|
| 238 |
+
feature_names[4],
|
| 239 |
+
feature_names[5],
|
| 240 |
+
]
|
| 241 |
+
|
| 242 |
+
if shuffle:
|
| 243 |
+
data, target = shuffle_method(data, target, random_state=random_state)
|
| 244 |
+
|
| 245 |
+
fdescr = load_descr("kddcup99.rst")
|
| 246 |
+
|
| 247 |
+
frame = None
|
| 248 |
+
if as_frame:
|
| 249 |
+
frame, data, target = _convert_data_dataframe(
|
| 250 |
+
"fetch_kddcup99", data, target, feature_names, target_names
|
| 251 |
+
)
|
| 252 |
+
|
| 253 |
+
if return_X_y:
|
| 254 |
+
return data, target
|
| 255 |
+
|
| 256 |
+
return Bunch(
|
| 257 |
+
data=data,
|
| 258 |
+
target=target,
|
| 259 |
+
frame=frame,
|
| 260 |
+
target_names=target_names,
|
| 261 |
+
feature_names=feature_names,
|
| 262 |
+
DESCR=fdescr,
|
| 263 |
+
)
|
| 264 |
+
|
| 265 |
+
|
| 266 |
+
def _fetch_brute_kddcup99(
|
| 267 |
+
data_home=None, download_if_missing=True, percent10=True, n_retries=3, delay=1.0
|
| 268 |
+
):
|
| 269 |
+
"""Load the kddcup99 dataset, downloading it if necessary.
|
| 270 |
+
|
| 271 |
+
Parameters
|
| 272 |
+
----------
|
| 273 |
+
data_home : str, default=None
|
| 274 |
+
Specify another download and cache folder for the datasets. By default
|
| 275 |
+
all scikit-learn data is stored in '~/scikit_learn_data' subfolders.
|
| 276 |
+
|
| 277 |
+
download_if_missing : bool, default=True
|
| 278 |
+
If False, raise an OSError if the data is not locally available
|
| 279 |
+
instead of trying to download the data from the source site.
|
| 280 |
+
|
| 281 |
+
percent10 : bool, default=True
|
| 282 |
+
Whether to load only 10 percent of the data.
|
| 283 |
+
|
| 284 |
+
n_retries : int, default=3
|
| 285 |
+
Number of retries when HTTP errors are encountered.
|
| 286 |
+
|
| 287 |
+
delay : float, default=1.0
|
| 288 |
+
Number of seconds between retries.
|
| 289 |
+
|
| 290 |
+
Returns
|
| 291 |
+
-------
|
| 292 |
+
dataset : :class:`~sklearn.utils.Bunch`
|
| 293 |
+
Dictionary-like object, with the following attributes.
|
| 294 |
+
|
| 295 |
+
data : ndarray of shape (494021, 41)
|
| 296 |
+
Each row corresponds to the 41 features in the dataset.
|
| 297 |
+
target : ndarray of shape (494021,)
|
| 298 |
+
Each value corresponds to one of the 21 attack types or to the
|
| 299 |
+
label 'normal.'.
|
| 300 |
+
feature_names : list
|
| 301 |
+
The names of the dataset columns
|
| 302 |
+
target_names: list
|
| 303 |
+
The names of the target columns
|
| 304 |
+
DESCR : str
|
| 305 |
+
Description of the kddcup99 dataset.
|
| 306 |
+
|
| 307 |
+
"""
|
| 308 |
+
|
| 309 |
+
data_home = get_data_home(data_home=data_home)
|
| 310 |
+
dir_suffix = "-py3"
|
| 311 |
+
|
| 312 |
+
if percent10:
|
| 313 |
+
kddcup_dir = join(data_home, "kddcup99_10" + dir_suffix)
|
| 314 |
+
archive = ARCHIVE_10_PERCENT
|
| 315 |
+
else:
|
| 316 |
+
kddcup_dir = join(data_home, "kddcup99" + dir_suffix)
|
| 317 |
+
archive = ARCHIVE
|
| 318 |
+
|
| 319 |
+
samples_path = join(kddcup_dir, "samples")
|
| 320 |
+
targets_path = join(kddcup_dir, "targets")
|
| 321 |
+
available = exists(samples_path)
|
| 322 |
+
|
| 323 |
+
dt = [
|
| 324 |
+
("duration", int),
|
| 325 |
+
("protocol_type", "S4"),
|
| 326 |
+
("service", "S11"),
|
| 327 |
+
("flag", "S6"),
|
| 328 |
+
("src_bytes", int),
|
| 329 |
+
("dst_bytes", int),
|
| 330 |
+
("land", int),
|
| 331 |
+
("wrong_fragment", int),
|
| 332 |
+
("urgent", int),
|
| 333 |
+
("hot", int),
|
| 334 |
+
("num_failed_logins", int),
|
| 335 |
+
("logged_in", int),
|
| 336 |
+
("num_compromised", int),
|
| 337 |
+
("root_shell", int),
|
| 338 |
+
("su_attempted", int),
|
| 339 |
+
("num_root", int),
|
| 340 |
+
("num_file_creations", int),
|
| 341 |
+
("num_shells", int),
|
| 342 |
+
("num_access_files", int),
|
| 343 |
+
("num_outbound_cmds", int),
|
| 344 |
+
("is_host_login", int),
|
| 345 |
+
("is_guest_login", int),
|
| 346 |
+
("count", int),
|
| 347 |
+
("srv_count", int),
|
| 348 |
+
("serror_rate", float),
|
| 349 |
+
("srv_serror_rate", float),
|
| 350 |
+
("rerror_rate", float),
|
| 351 |
+
("srv_rerror_rate", float),
|
| 352 |
+
("same_srv_rate", float),
|
| 353 |
+
("diff_srv_rate", float),
|
| 354 |
+
("srv_diff_host_rate", float),
|
| 355 |
+
("dst_host_count", int),
|
| 356 |
+
("dst_host_srv_count", int),
|
| 357 |
+
("dst_host_same_srv_rate", float),
|
| 358 |
+
("dst_host_diff_srv_rate", float),
|
| 359 |
+
("dst_host_same_src_port_rate", float),
|
| 360 |
+
("dst_host_srv_diff_host_rate", float),
|
| 361 |
+
("dst_host_serror_rate", float),
|
| 362 |
+
("dst_host_srv_serror_rate", float),
|
| 363 |
+
("dst_host_rerror_rate", float),
|
| 364 |
+
("dst_host_srv_rerror_rate", float),
|
| 365 |
+
("labels", "S16"),
|
| 366 |
+
]
|
| 367 |
+
|
| 368 |
+
column_names = [c[0] for c in dt]
|
| 369 |
+
target_names = column_names[-1]
|
| 370 |
+
feature_names = column_names[:-1]
|
| 371 |
+
|
| 372 |
+
if available:
|
| 373 |
+
try:
|
| 374 |
+
X = joblib.load(samples_path)
|
| 375 |
+
y = joblib.load(targets_path)
|
| 376 |
+
except Exception as e:
|
| 377 |
+
raise OSError(
|
| 378 |
+
"The cache for fetch_kddcup99 is invalid, please delete "
|
| 379 |
+
f"{kddcup_dir} and run the fetch_kddcup99 again"
|
| 380 |
+
) from e
|
| 381 |
+
|
| 382 |
+
elif download_if_missing:
|
| 383 |
+
_mkdirp(kddcup_dir)
|
| 384 |
+
logger.info("Downloading %s" % archive.url)
|
| 385 |
+
_fetch_remote(archive, dirname=kddcup_dir, n_retries=n_retries, delay=delay)
|
| 386 |
+
DT = np.dtype(dt)
|
| 387 |
+
logger.debug("extracting archive")
|
| 388 |
+
archive_path = join(kddcup_dir, archive.filename)
|
| 389 |
+
file_ = GzipFile(filename=archive_path, mode="r")
|
| 390 |
+
Xy = []
|
| 391 |
+
for line in file_.readlines():
|
| 392 |
+
line = line.decode()
|
| 393 |
+
Xy.append(line.replace("\n", "").split(","))
|
| 394 |
+
file_.close()
|
| 395 |
+
logger.debug("extraction done")
|
| 396 |
+
os.remove(archive_path)
|
| 397 |
+
|
| 398 |
+
Xy = np.asarray(Xy, dtype=object)
|
| 399 |
+
for j in range(42):
|
| 400 |
+
Xy[:, j] = Xy[:, j].astype(DT[j])
|
| 401 |
+
|
| 402 |
+
X = Xy[:, :-1]
|
| 403 |
+
y = Xy[:, -1]
|
| 404 |
+
# XXX bug when compress!=0:
|
| 405 |
+
# (error: 'Incorrect data length while decompressing[...] the file
|
| 406 |
+
# could be corrupted.')
|
| 407 |
+
|
| 408 |
+
joblib.dump(X, samples_path, compress=0)
|
| 409 |
+
joblib.dump(y, targets_path, compress=0)
|
| 410 |
+
else:
|
| 411 |
+
raise OSError("Data not found and `download_if_missing` is False")
|
| 412 |
+
|
| 413 |
+
return Bunch(
|
| 414 |
+
data=X,
|
| 415 |
+
target=y,
|
| 416 |
+
feature_names=feature_names,
|
| 417 |
+
target_names=[target_names],
|
| 418 |
+
)
|
| 419 |
+
|
| 420 |
+
|
| 421 |
+
def _mkdirp(d):
|
| 422 |
+
"""Ensure directory d exists (like mkdir -p on Unix)
|
| 423 |
+
No guarantee that the directory is writable.
|
| 424 |
+
"""
|
| 425 |
+
try:
|
| 426 |
+
os.mak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ous people collected
|
| 4 |
+
over the internet, all details are available on the official website:
|
| 5 |
+
|
| 6 |
+
http://vis-www.cs.umass.edu/lfw/
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
# Authors: The scikit-learn developers
|
| 10 |
+
# SPDX-License-Identifier: BSD-3-Clause
|
| 11 |
+
|
| 12 |
+
import logging
|
| 13 |
+
from numbers import Integral, Real
|
| 14 |
+
from os import PathLike, listdir, makedirs, remove
|
| 15 |
+
from os.path import exists, isdir, join
|
| 16 |
+
|
| 17 |
+
import numpy as np
|
| 18 |
+
from joblib import Memory
|
| 19 |
+
|
| 20 |
+
from ..utils import Bunch
|
| 21 |
+
from ..utils._param_validation import Hidden, Interval, StrOptions, validate_params
|
| 22 |
+
from ..utils.fixes import tarfile_extractall
|
| 23 |
+
from ._base import (
|
| 24 |
+
RemoteFileMetadata,
|
| 25 |
+
_fetch_remote,
|
| 26 |
+
get_data_home,
|
| 27 |
+
load_descr,
|
| 28 |
+
)
|
| 29 |
+
|
| 30 |
+
logger = logging.getLogger(__name__)
|
| 31 |
+
|
| 32 |
+
# The original data can be found in:
|
| 33 |
+
# http://vis-www.cs.umass.edu/lfw/lfw.tgz
|
| 34 |
+
ARCHIVE = RemoteFileMetadata(
|
| 35 |
+
filename="lfw.tgz",
|
| 36 |
+
url="https://ndownloader.figshare.com/files/5976018",
|
| 37 |
+
checksum="055f7d9c632d7370e6fb4afc7468d40f970c34a80d4c6f50ffec63f5a8d536c0",
|
| 38 |
+
)
|
| 39 |
+
|
| 40 |
+
# The original funneled data can be found in:
|
| 41 |
+
# http://vis-www.cs.umass.edu/lfw/lfw-funneled.tgz
|
| 42 |
+
FUNNELED_ARCHIVE = RemoteFileMetadata(
|
| 43 |
+
filename="lfw-funneled.tgz",
|
| 44 |
+
url="https://ndownloader.figshare.com/files/5976015",
|
| 45 |
+
checksum="b47c8422c8cded889dc5a13418c4bc2abbda121092b3533a83306f90d900100a",
|
| 46 |
+
)
|
| 47 |
+
|
| 48 |
+
# The original target data can be found in:
|
| 49 |
+
# http://vis-www.cs.umass.edu/lfw/pairsDevTrain.txt',
|
| 50 |
+
# http://vis-www.cs.umass.edu/lfw/pairsDevTest.txt',
|
| 51 |
+
# http://vis-www.cs.umass.edu/lfw/pairs.txt',
|
| 52 |
+
TARGETS = (
|
| 53 |
+
RemoteFileMetadata(
|
| 54 |
+
filename="pairsDevTrain.txt",
|
| 55 |
+
url="https://ndownloader.figshare.com/files/5976012",
|
| 56 |
+
checksum="1d454dada7dfeca0e7eab6f65dc4e97a6312d44cf142207be28d688be92aabfa",
|
| 57 |
+
),
|
| 58 |
+
RemoteFileMetadata(
|
| 59 |
+
filename="pairsDevTest.txt",
|
| 60 |
+
url="https://ndownloader.figshare.com/files/5976009",
|
| 61 |
+
checksum="7cb06600ea8b2814ac26e946201cdb304296262aad67d046a16a7ec85d0ff87c",
|
| 62 |
+
),
|
| 63 |
+
RemoteFileMetadata(
|
| 64 |
+
filename="pairs.txt",
|
| 65 |
+
url="https://ndownloader.figshare.com/files/5976006",
|
| 66 |
+
checksum="ea42330c62c92989f9d7c03237ed5d591365e89b3e649747777b70e692dc1592",
|
| 67 |
+
),
|
| 68 |
+
)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
#
|
| 72 |
+
# Common private utilities for data fetching from the original LFW website
|
| 73 |
+
# local disk caching, and image decoding.
|
| 74 |
+
#
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def _check_fetch_lfw(
|
| 78 |
+
data_home=None, funneled=True, download_if_missing=True, n_retries=3, delay=1.0
|
| 79 |
+
):
|
| 80 |
+
"""Helper function to download any missing LFW data"""
|
| 81 |
+
|
| 82 |
+
data_home = get_data_home(data_home=data_home)
|
| 83 |
+
lfw_home = join(data_home, "lfw_home")
|
| 84 |
+
|
| 85 |
+
if not exists(lfw_home):
|
| 86 |
+
makedirs(lfw_home)
|
| 87 |
+
|
| 88 |
+
for target in TARGETS:
|
| 89 |
+
target_filepath = join(lfw_home, target.filename)
|
| 90 |
+
if not exists(target_filepath):
|
| 91 |
+
if download_if_missing:
|
| 92 |
+
logger.info("Downloading LFW metadata: %s", target.url)
|
| 93 |
+
_fetch_remote(
|
| 94 |
+
target, dirname=lfw_home, n_retries=n_retries, delay=delay
|
| 95 |
+
)
|
| 96 |
+
else:
|
| 97 |
+
raise OSError("%s is missing" % target_filepath)
|
| 98 |
+
|
| 99 |
+
if funneled:
|
| 100 |
+
data_folder_path = join(lfw_home, "lfw_funneled")
|
| 101 |
+
archive = FUNNELED_ARCHIVE
|
| 102 |
+
else:
|
| 103 |
+
data_folder_path = join(lfw_home, "lfw")
|
| 104 |
+
archive = ARCHIVE
|
| 105 |
+
|
| 106 |
+
if not exists(data_folder_path):
|
| 107 |
+
archive_path = join(lfw_home, archive.filename)
|
| 108 |
+
if not exists(archive_path):
|
| 109 |
+
if download_if_missing:
|
| 110 |
+
logger.info("Downloading LFW data (~200MB): %s", archive.url)
|
| 111 |
+
_fetch_remote(
|
| 112 |
+
archive, dirname=lfw_home, n_retries=n_retries, delay=delay
|
| 113 |
+
)
|
| 114 |
+
else:
|
| 115 |
+
raise OSError("%s is missing" % archive_path)
|
| 116 |
+
|
| 117 |
+
import tarfile
|
| 118 |
+
|
| 119 |
+
logger.debug("Decompressing the data archive to %s", data_folder_path)
|
| 120 |
+
with tarfile.open(archive_path, "r:gz") as fp:
|
| 121 |
+
tarfile_extractall(fp, path=lfw_home)
|
| 122 |
+
|
| 123 |
+
remove(archive_path)
|
| 124 |
+
|
| 125 |
+
return lfw_home, data_folder_path
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def _load_imgs(file_paths, slice_, color, resize):
|
| 129 |
+
"""Internally used to load images"""
|
| 130 |
+
try:
|
| 131 |
+
from PIL import Image
|
| 132 |
+
except ImportError:
|
| 133 |
+
raise ImportError(
|
| 134 |
+
"The Python Imaging Library (PIL) is required to load data "
|
| 135 |
+
"from jpeg files. Please refer to "
|
| 136 |
+
"https://pillow.readthedocs.io/en/stable/installation.html "
|
| 137 |
+
"for installing PIL."
|
| 138 |
+
)
|
| 139 |
+
|
| 140 |
+
# compute the portion of the images to load to respect the slice_ parameter
|
| 141 |
+
# given by the caller
|
| 142 |
+
default_slice = (slice(0, 250), slice(0, 250))
|
| 143 |
+
if slice_ is None:
|
| 144 |
+
slice_ = default_slice
|
| 145 |
+
else:
|
| 146 |
+
slice_ = tuple(s or ds for s, ds in zip(slice_, default_slice))
|
| 147 |
+
|
| 148 |
+
h_slice, w_slice = slice_
|
| 149 |
+
h = (h_slice.stop - h_slice.start) // (h_slice.step or 1)
|
| 150 |
+
w = (w_slice.stop - w_slice.start) // (w_slice.step or 1)
|
| 151 |
+
|
| 152 |
+
if resize is not None:
|
| 153 |
+
resize = float(resize)
|
| 154 |
+
h = int(resize * h)
|
| 155 |
+
w = int(resize * w)
|
| 156 |
+
|
| 157 |
+
# allocate some contiguous memory to host the decoded image slices
|
| 158 |
+
n_faces = len(file_paths)
|
| 159 |
+
if not color:
|
| 160 |
+
faces = np.zeros((n_faces, h, w), dtype=np.float32)
|
| 161 |
+
else:
|
| 162 |
+
faces = np.zeros((n_faces, h, w, 3), dtype=np.float32)
|
| 163 |
+
|
| 164 |
+
# iterate over the collected file path to load the jpeg files as numpy
|
| 165 |
+
# arrays
|
| 166 |
+
for i, file_path in enumerate(file_paths):
|
| 167 |
+
if i % 1000 == 0:
|
| 168 |
+
logger.debug("Loading face #%05d / %05d", i + 1, n_faces)
|
| 169 |
+
|
| 170 |
+
# Checks if jpeg reading worked. Refer to issue #3594 for more
|
| 171 |
+
# details.
|
| 172 |
+
pil_img = Image.open(file_path)
|
| 173 |
+
pil_img = pil_img.crop(
|
| 174 |
+
(w_slice.start, h_slice.start, w_slice.stop, h_slice.stop)
|
| 175 |
+
)
|
| 176 |
+
if resize is not None:
|
| 177 |
+
pil_img = pil_img.resize((w, h))
|
| 178 |
+
face = np.asarray(pil_img, dtype=np.float32)
|
| 179 |
+
|
| 180 |
+
if face.ndim == 0:
|
| 181 |
+
raise RuntimeError(
|
| 182 |
+
"Failed to read the image file %s, "
|
| 183 |
+
"Please make sure that libjpeg is installed" % file_path
|
| 184 |
+
)
|
| 185 |
+
|
| 186 |
+
face /= 255.0 # scale uint8 coded colors to the [0.0, 1.0] floats
|
| 187 |
+
if not color:
|
| 188 |
+
# average the color channels to compute a gray levels
|
| 189 |
+
# representation
|
| 190 |
+
face = face.mean(axis=2)
|
| 191 |
+
|
| 192 |
+
faces[i, ...] = face
|
| 193 |
+
|
| 194 |
+
return faces
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
#
|
| 198 |
+
# Task #1: Face Identification on picture with names
|
| 199 |
+
#
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
def _fetch_lfw_people(
|
| 203 |
+
data_folder_path, slice_=None, color=False, resize=None, min_faces_per_person=0
|
| 204 |
+
):
|
| 205 |
+
"""Perform the actual data loading for the lfw people dataset
|
| 206 |
+
|
| 207 |
+
This operation is meant to be cached by a joblib wrapper.
|
| 208 |
+
"""
|
| 209 |
+
# scan the data folder content to retain people with more that
|
| 210 |
+
# `min_faces_per_person` face pictures
|
| 211 |
+
person_names, file_paths = [], []
|
| 212 |
+
for person_name in sorted(listdir(data_folder_path)):
|
| 213 |
+
folder_path = join(data_folder_path, person_name)
|
| 214 |
+
if not isdir(folder_path):
|
| 215 |
+
continue
|
| 216 |
+
paths = [join(folder_path, f) for f in sorted(listdir(folder_path))]
|
| 217 |
+
n_pictures = len(paths)
|
| 218 |
+
if n_pictures >= min_faces_per_person:
|
| 219 |
+
person_name = person_name.replace("_", " ")
|
| 220 |
+
person_names.extend([person_name] * n_pictures)
|
| 221 |
+
file_paths.extend(paths)
|
| 222 |
+
|
| 223 |
+
n_faces = len(file_paths)
|
| 224 |
+
if n_faces == 0:
|
| 225 |
+
raise ValueError(
|
| 226 |
+
"min_faces_per_person=%d is too restrictive" % min_faces_per_person
|
| 227 |
+
)
|
| 228 |
+
|
| 229 |
+
target_names = np.unique(person_names)
|
| 230 |
+
target = np.searchsorted(target_names, person_names)
|
| 231 |
+
|
| 232 |
+
faces = _load_imgs(file_paths, slice_, color, resize)
|
| 233 |
+
|
| 234 |
+
# shuffle the faces with a deterministic RNG scheme to avoid having
|
| 235 |
+
# all faces of the same person in a row, as it would break some
|
| 236 |
+
# cross validation and learning algorithms such as SGD and online
|
| 237 |
+
# k-means that make an IID assumption
|
| 238 |
+
|
| 239 |
+
indices = np.arange(n_faces)
|
| 240 |
+
np.random.RandomState(42).shuffle(indices)
|
| 241 |
+
faces, target = faces[indices], target[indices]
|
| 242 |
+
return faces, target, target_names
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
@validate_params(
|
| 246 |
+
{
|
| 247 |
+
"data_home": [str, PathLike, None],
|
| 248 |
+
"funneled": ["boolean"],
|
| 249 |
+
"resize": [Interval(Real, 0, None, closed="neither"), None],
|
| 250 |
+
"min_faces_per_person": [Interval(Integral, 0, None, closed="left"), None],
|
| 251 |
+
"color": ["boolean"],
|
| 252 |
+
"slice_": [tuple, Hidden(None)],
|
| 253 |
+
"download_if_missing": ["boolean"],
|
| 254 |
+
"return_X_y": ["boolean"],
|
| 255 |
+
"n_retries": [Interval(Integral, 1, None, closed="left")],
|
| 256 |
+
"delay": [Interval(Real, 0.0, None, closed="neither")],
|
| 257 |
+
},
|
| 258 |
+
prefer_skip_nested_validation=True,
|
| 259 |
+
)
|
| 260 |
+
def fetch_lfw_people(
|
| 261 |
+
*,
|
| 262 |
+
data_home=None,
|
| 263 |
+
funneled=True,
|
| 264 |
+
resize=0.5,
|
| 265 |
+
min_faces_per_person=0,
|
| 266 |
+
color=False,
|
| 267 |
+
slice_=(slice(70, 195), slice(78, 172)),
|
| 268 |
+
download_if_missing=True,
|
| 269 |
+
return_X_y=False,
|
| 270 |
+
n_retries=3,
|
| 271 |
+
delay=1.0,
|
| 272 |
+
):
|
| 273 |
+
"""Load the Labeled Faces in the Wild (LFW) people dataset \
|
| 274 |
+
(classification).
|
| 275 |
+
|
| 276 |
+
Download it if necessary.
|
| 277 |
+
|
| 278 |
+
================= =======================
|
| 279 |
+
Classes 5749
|
| 280 |
+
Samples total 13233
|
| 281 |
+
Dimensionality 5828
|
| 282 |
+
Features real, between 0 and 255
|
| 283 |
+
================= =======================
|
| 284 |
+
|
| 285 |
+
For a usage example of this dataset, see
|
| 286 |
+
:ref:`sphx_glr_auto_examples_applications_plot_face_recognition.py`.
|
| 287 |
+
|
| 288 |
+
Read more in the :ref:`User Guide <labeled_faces_in_the_wild_dataset>`.
|
| 289 |
+
|
| 290 |
+
Parameters
|
| 291 |
+
----------
|
| 292 |
+
data_home : str or path-like, default=None
|
| 293 |
+
Specify another download and cache folder for the datasets. By default
|
| 294 |
+
all scikit-learn data is stored in '~/scikit_learn_data' subfolders.
|
| 295 |
+
|
| 296 |
+
funneled : bool, default=True
|
| 297 |
+
Download and use the funneled variant of the dataset.
|
| 298 |
+
|
| 299 |
+
resize : float or None, default=0.5
|
| 300 |
+
Ratio used to resize the each face picture. If `None`, no resizing is
|
| 301 |
+
performed.
|
| 302 |
+
|
| 303 |
+
min_faces_per_person : int, default=None
|
| 304 |
+
The extracted dataset will only retain pictures of people that have at
|
| 305 |
+
least `min_faces_per_person` different pictures.
|
| 306 |
+
|
| 307 |
+
color : bool, default=False
|
| 308 |
+
Keep the 3 RGB channels instead of averaging them to a single
|
| 309 |
+
gray level channel. If color is True the shape of the data has
|
| 310 |
+
one more dimension than the shape with color = False.
|
| 311 |
+
|
| 312 |
+
slice_ : tuple of slice, default=(slice(70, 195), slice(78, 172))
|
| 313 |
+
Provide a custom 2D slice (height, width) to extract the
|
| 314 |
+
'interesting' part of the jpeg files and avoid use statistical
|
| 315 |
+
correlation from the background.
|
| 316 |
+
|
| 317 |
+
download_if_missing : bool, default=True
|
| 318 |
+
If False, raise an OSError if the data is not locally available
|
| 319 |
+
instead of trying to download the data from the source site.
|
| 320 |
+
|
| 321 |
+
return_X_y : bool, default=False
|
| 322 |
+
If True, returns ``(dataset.data, dataset.target)`` instead of a Bunch
|
| 323 |
+
object. See below for more information about the `dataset.data` and
|
| 324 |
+
`dataset.target` object.
|
| 325 |
+
|
| 326 |
+
.. versionadded:: 0.20
|
| 327 |
+
|
| 328 |
+
n_retries : int, default=3
|
| 329 |
+
Number of retries when HTTP errors are encountered.
|
| 330 |
+
|
| 331 |
+
.. versionadded:: 1.5
|
| 332 |
+
|
| 333 |
+
delay : float, default=1.0
|
| 334 |
+
Number of seconds between retries.
|
| 335 |
+
|
| 336 |
+
.. versionadded:: 1.5
|
| 337 |
+
|
| 338 |
+
Returns
|
| 339 |
+
-------
|
| 340 |
+
dataset : :class:`~sklearn.utils.Bunch`
|
| 341 |
+
Dictionary-like object, with the following attributes.
|
| 342 |
+
|
| 343 |
+
data : numpy array of shape (13233, 2914)
|
| 344 |
+
Each row corresponds to a ravelled face image
|
| 345 |
+
of original size 62 x 47 pixels.
|
| 346 |
+
Changing the ``slice_`` or resize parameters will change the
|
| 347 |
+
shape of the output.
|
| 348 |
+
images : numpy array of shape (13233, 62, 47)
|
| 349 |
+
Each row is a face image corresponding to one of the 5749 people in
|
| 350 |
+
the dataset. Changing the ``slice_``
|
| 351 |
+
or resize parameters will change the shape of the output.
|
| 352 |
+
target : numpy array of shape (13233,)
|
| 353 |
+
Labels associated to each face image.
|
| 354 |
+
Those labels range from 0-5748 and correspond to the person IDs.
|
| 355 |
+
target_names : numpy array of shape (5749,)
|
| 356 |
+
Names of all persons in the dataset.
|
| 357 |
+
Position in array corresponds to the person ID in the target array.
|
| 358 |
+
DESCR : str
|
| 359 |
+
Description of the Labeled Faces in the Wild (LFW) dataset.
|
| 360 |
+
|
| 361 |
+
(data, target) : tuple if ``return_X_y`` is True
|
| 362 |
+
A tuple of two ndarray. The first containing a 2D array of
|
| 363 |
+
shape (n_samples, n_features) with each row representing one
|
| 364 |
+
sample and each column representing the features. The second
|
| 365 |
+
ndarray of shape (n_samples,) containing the target samples.
|
| 366 |
+
|
| 367 |
+
.. versionadded:: 0.20
|
| 368 |
+
|
| 369 |
+
Examples
|
| 370 |
+
--------
|
| 371 |
+
>>> from sklearn.datasets import fetch_lfw_people
|
| 372 |
+
>>> lfw_people = fetch_lfw_people()
|
| 373 |
+
>>> lfw_people.data.shape
|
| 374 |
+
(13233, 2914)
|
| 375 |
+
>>> lfw_people.target.shape
|
| 376 |
+
(13233,)
|
| 377 |
+
>>> for name in lfw_people.target_names[:5]:
|
| 378 |
+
... print(name)
|
| 379 |
+
AJ Cook
|
| 380 |
+
AJ Lamas
|
| 381 |
+
Aaron Eckhart
|
| 382 |
+
Aaron Guiel
|
| 383 |
+
Aaron Patterson
|
| 384 |
+
"""
|
| 385 |
+
lfw_home, data_folder_path = _check_fetch_lfw(
|
| 386 |
+
data_home=data_home,
|
| 387 |
+
funneled=funneled,
|
| 388 |
+
download_if_missing=download_if_missing,
|
| 389 |
+
n_retries=n_retries,
|
| 390 |
+
delay=delay,
|
| 391 |
+
)
|
| 392 |
+
logger.debug("Loading LFW people faces from %s", lfw_home)
|
| 393 |
+
|
| 394 |
+
# wrap the loader in a memoizing function that will return memmaped data
|
| 395 |
+
# arrays for optimal memory usage
|
| 396 |
+
m = Memory(location=lfw_home, compress=6, verbose=0)
|
| 397 |
+
load_func = m.cache(_fetch_lfw_people)
|
| 398 |
+
|
| 399 |
+
# load and memoize the pairs as np arrays
|
| 400 |
+
faces, target, target_names = load_func(
|
| 401 |
+
data_folder_path,
|
| 402 |
+
resize=resize,
|
| 403 |
+
min_faces_per_person=min_faces_per_person,
|
| 404 |
+
color=color,
|
| 405 |
+
slice_=slice_,
|
| 406 |
+
)
|
| 407 |
+
|
| 408 |
+
X = faces.reshape(len(faces), -1)
|
| 409 |
+
|
| 410 |
+
fdescr = load_descr("lfw.rst")
|
| 411 |
+
|
| 412 |
+
if return_X_y:
|
| 413 |
+
return X, target
|
| 414 |
+
|
| 415 |
+
# pack the results as a Bunch instance
|
| 416 |
+
return Bunch(
|
| 417 |
+
data=X, images=faces, target=target, target_names=target_names, DESCR=fdescr
|
| 418 |
+
)
|
| 419 |
+
|
| 420 |
+
|
| 421 |
+
#
|
| 422 |
+
# Task #2: Face Verification on pairs of face pictures
|
| 423 |
+
#
|
| 424 |
+
|
| 425 |
+
|
| 426 |
+
def _fetch_lfw_pairs(
|
| 427 |
+
index_file_path, data_folder_path, slice_=None, color=False, resize=None
|
| 428 |
+
):
|
| 429 |
+
"""Perform the actual data loading for the LFW pairs dataset
|
| 430 |
+
|
| 431 |
+
This operation is meant to be cached by a joblib wrapper.
|
| 432 |
+
"""
|
| 433 |
+
# parse the index file to find the number of pairs to be able to allocate
|
| 434 |
+
# the right amount of memory before starting to decode the jpeg files
|
| 435 |
+
with open(index_file_path, "rb") as index_file:
|
| 436 |
+
split_lines = [ln.decode().strip().split("\t") for ln in index_file]
|
| 437 |
+
pair_specs = [sl for sl in split_lines if len(sl) > 2]
|
| 438 |
+
n_pairs = len(pair_specs)
|
| 439 |
+
|
| 440 |
+
# iterating over the metadata lines for each pair to find the filename to
|
| 441 |
+
# decode and load in memory
|
| 442 |
+
target = np.zeros(n_pairs, dtype=int)
|
| 443 |
+
file_paths = list()
|
| 444 |
+
for i, components in enumerate(pair_specs):
|
| 445 |
+
if len(components) == 3:
|
| 446 |
+
target[i] = 1
|
| 447 |
+
pair = (
|
| 448 |
+
(components[0], int(components[1]) - 1),
|
| 449 |
+
(components[0], int(components[2]) - 1),
|
| 450 |
+
)
|
| 451 |
+
elif len(components) == 4:
|
| 452 |
+
target[i] = 0
|
| 453 |
+
pair = (
|
| 454 |
+
(components[0], int(components[1]) - 1),
|
| 455 |
+
(components[2], int(components[3]) - 1),
|
| 456 |
+
)
|
| 457 |
+
else:
|
| 458 |
+
raise ValueError("invalid line %d: %r" % (i + 1, components))
|
| 459 |
+
for j, (name, idx) in enumerate(pair):
|
| 460 |
+
try:
|
| 461 |
+
person_folder = join(data_folder_path, name)
|
| 462 |
+
except TypeError:
|
| 463 |
+
person_folder = join(data_folder_path, str(name, "UTF-8"))
|
| 464 |
+
filenames = list(sorted(listdir(person_folder)))
|
| 465 |
+
file_path = join(person_folder, filenames[idx])
|
| 466 |
+
file_paths.append(file_path)
|
| 467 |
+
|
| 468 |
+
pairs = _load_imgs(file_paths, slice_, color, resize)
|
| 469 |
+
shape = list(pairs.shape)
|
| 470 |
+
n_faces = shape.pop(0)
|
| 471 |
+
shape.insert(0, 2)
|
| 472 |
+
shape.insert(0, n_faces // 2)
|
| 473 |
+
pairs.shape = shape
|
| 474 |
+
|
| 475 |
+
return pairs, target, np.array(["Different persons", "Same person"])
|
| 476 |
+
|
| 477 |
+
|
| 478 |
+
@validate_params(
|
| 479 |
+
{
|
| 480 |
+
"subset": [StrOptions({"train", "test", "10_folds"})],
|
| 481 |
+
"data_home": [str, PathLike, None],
|
| 482 |
+
"funneled": ["boolean"],
|
| 483 |
+
"resize": [Interval(Real, 0, None, closed="neither"), None],
|
| 484 |
+
"color": ["boolean"],
|
| 485 |
+
"slice_": [tuple, Hidden(None)],
|
| 486 |
+
"download_if_missing": ["boolean"],
|
| 487 |
+
"n_retries": [Interval(Integral, 1, None, closed="left")],
|
| 488 |
+
"delay": [Interval(Real, 0.0, None, closed="neither")],
|
| 489 |
+
},
|
| 490 |
+
prefer_skip_nested_validation=True,
|
| 491 |
+
)
|
| 492 |
+
def fetch_lfw_pairs(
|
| 493 |
+
*,
|
| 494 |
+
subset="train",
|
| 495 |
+
data_home=None,
|
| 496 |
+
funneled=True,
|
| 497 |
+
resize=0.5,
|
| 498 |
+
color=False,
|
| 499 |
+
slice_=(slice(70, 195), slice(78, 172)),
|
| 500 |
+
download_if_missing=True,
|
| 501 |
+
n_retries=3,
|
| 502 |
+
delay=1.0,
|
| 503 |
+
):
|
| 504 |
+
"""Load the Labeled Faces in the Wild (LFW) pairs dataset (classification).
|
| 505 |
+
|
| 506 |
+
Download it if necessary.
|
| 507 |
+
|
| 508 |
+
================= =======================
|
| 509 |
+
Classes 2
|
| 510 |
+
Samples total 13233
|
| 511 |
+
Dimensionality 5828
|
| 512 |
+
Features real, between 0 and 255
|
| 513 |
+
================= =======================
|
| 514 |
+
|
| 515 |
+
In the `original paper <https://people.cs.umass.edu/~elm/papers/lfw.pdf>`_
|
| 516 |
+
the "pairs" version corresponds to the "restricted task", where
|
| 517 |
+
the experimenter should not use the name of a person to infer
|
| 518 |
+
the equivalence or non-equivalence of two face images that
|
| 519 |
+
are not explicitly given in the training set.
|
| 520 |
+
|
| 521 |
+
The original images are 250 x 250 pixels, but the default slice and resize
|
| 522 |
+
arguments reduce them to 62 x 47.
|
| 523 |
+
|
| 524 |
+
Read more in the :ref:`User Guide <labeled_faces_in_the_wild_dataset>`.
|
| 525 |
+
|
| 526 |
+
Parameters
|
| 527 |
+
----------
|
| 528 |
+
subset : {'train', 'test', '10_folds'}, default='train'
|
| 529 |
+
Select the dataset to load: 'train' for the development training
|
| 530 |
+
set, 'test' for the development test set, and '10_folds' for the
|
| 531 |
+
official evaluation set that is meant to be used with a 10-folds
|
| 532 |
+
cross validation.
|
| 533 |
+
|
| 534 |
+
data_home : str or path-like, default=None
|
| 535 |
+
Specify another download and cache folder for the datasets. By
|
| 536 |
+
default all scikit-learn data is stored in '~/scikit_learn_data'
|
| 537 |
+
subfolders.
|
| 538 |
+
|
| 539 |
+
funneled : bool, default=True
|
| 540 |
+
Download and use the funneled variant of the dataset.
|
| 541 |
+
|
| 542 |
+
resize : float, default=0.5
|
| 543 |
+
Ratio used to resize the each face picture.
|
| 544 |
+
|
| 545 |
+
color : bool, default=False
|
| 546 |
+
Keep the 3 RGB channels instead of averaging them to a single
|
| 547 |
+
gray level channel. If color is True the shape of the data has
|
| 548 |
+
one more dimension than the shape with color = False.
|
| 549 |
+
|
| 550 |
+
slice_ : tuple of slice, default=(slice(70, 195), slice(78, 172))
|
| 551 |
+
Provide a custom 2D slice (height, width) to extract the
|
| 552 |
+
'interesting' part of the jpeg files and avoid use statistical
|
| 553 |
+
correlation from the background.
|
| 554 |
+
|
| 555 |
+
download_if_missing : bool, default=True
|
| 556 |
+
If False, raise an OSError if the data is not locally available
|
| 557 |
+
instead of trying to download the data from the source site.
|
| 558 |
+
|
| 559 |
+
n_retries : int, default=3
|
| 560 |
+
Number of retries when HTTP errors are encountered.
|
| 561 |
+
|
| 562 |
+
.. versionadded:: 1.5
|
| 563 |
+
|
| 564 |
+
delay : float, default=1.0
|
| 565 |
+
Number of seconds between retries.
|
| 566 |
+
|
| 567 |
+
.. versionadded:: 1.5
|
| 568 |
+
|
| 569 |
+
Returns
|
| 570 |
+
-------
|
| 571 |
+
data : :class:`~sklearn.utils.Bunch`
|
| 572 |
+
Dictionary-like object, with the following attributes.
|
| 573 |
+
|
| 574 |
+
data : ndarray of shape (2200, 5828). Shape depends on ``subset``.
|
| 575 |
+
Each row corresponds to 2 ravel'd face images
|
| 576 |
+
of original size 62 x 47 pixels.
|
| 577 |
+
Changing the ``slice_``, ``resize`` or ``subset`` parameters
|
| 578 |
+
will change the shape of the output.
|
| 579 |
+
pairs : ndarray of shape (2200, 2, 62, 47). Shape depends on ``subset``
|
| 580 |
+
Each row has 2 face images corresponding
|
| 581 |
+
to same or different person from the dataset
|
| 582 |
+
containing 5749 people. Changing the ``slice_``,
|
| 583 |
+
``resize`` or ``subset`` parameters will change the shape of the
|
| 584 |
+
output.
|
| 585 |
+
target : numpy array of shape (2200,). Shape depends on ``subset``.
|
| 586 |
+
Labels associated to each pair of images.
|
| 587 |
+
The two label values being different persons or the same person.
|
| 588 |
+
target_names : numpy array of shape (2,)
|
| 589 |
+
Explains the target values of the target array.
|
| 590 |
+
0 corresponds to "Different person", 1 corresponds to "same person".
|
| 591 |
+
DESCR : str
|
| 592 |
+
Description of the Labeled Faces in the Wild (LFW) dataset.
|
| 593 |
+
|
| 594 |
+
Examples
|
| 595 |
+
--------
|
| 596 |
+
>>> from sklearn.datasets import fetch_lfw_pairs
|
| 597 |
+
>>> lfw_pairs_train = fetch_lfw_pairs(subset='train')
|
| 598 |
+
>>> list(lfw_pairs_train.target_names)
|
| 599 |
+
[np.str_('Different persons'), np.str_('Same person')]
|
| 600 |
+
>>> lfw_pairs_train.pairs.shape
|
| 601 |
+
(2200, 2, 62, 47)
|
| 602 |
+
>>> lfw_pairs_train.data.shape
|
| 603 |
+
(2200, 5828)
|
| 604 |
+
>>> lfw_pairs_train.target.shape
|
| 605 |
+
(2200,)
|
| 606 |
+
"""
|
| 607 |
+
lfw_home, data_folder_path = _check_fetch_lfw(
|
| 608 |
+
data_home=data_home,
|
| 609 |
+
funneled=funneled,
|
| 610 |
+
download_if_missing=download_if_missing,
|
| 611 |
+
n_retries=n_retries,
|
| 612 |
+
delay=delay,
|
| 613 |
+
)
|
| 614 |
+
logger.debug("Loading %s LFW pairs from %s", subset, lfw_home)
|
| 615 |
+
|
| 616 |
+
# wrap the loader in a memoizing function that will return memmaped data
|
| 617 |
+
# arrays for optimal memory usage
|
| 618 |
+
m = Memory(location=lfw_home, compress=6, verbose=0)
|
| 619 |
+
load_func = m.cache(_fetch_lfw_pairs)
|
| 620 |
+
|
| 621 |
+
# select the right metadata file according to the requested subset
|
| 622 |
+
label_filenames = {
|
| 623 |
+
"train": "pairsDevTrain.txt",
|
| 624 |
+
"test": "pairsDevTest.txt",
|
| 625 |
+
"10_folds": "pairs.txt",
|
| 626 |
+
}
|
| 627 |
+
if subset not in label_filenames:
|
| 628 |
+
raise ValueError(
|
| 629 |
+
"subset='%s' is invalid: should be one of %r"
|
| 630 |
+
% (subset, list(sorted(label_filenames.keys())))
|
| 631 |
+
)
|
| 632 |
+
index_file_path = join(lfw_home, label_filenames[subset])
|
| 633 |
+
|
| 634 |
+
# load and memoize the pairs as np arrays
|
| 635 |
+
pairs, target, target_names = load_func(
|
| 636 |
+
index_file_path, data_folder_path, resize=resize, color=color, slice_=slice_
|
| 637 |
+
)
|
| 638 |
+
|
| 639 |
+
fdescr = load_descr("lfw.rst")
|
| 640 |
+
|
| 641 |
+
# pack the results as a Bunch instance
|
| 642 |
+
return Bunch(
|
| 643 |
+
data=pairs.reshape(len(pairs), -1),
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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Modified Olivetti faces dataset.
|
| 2 |
+
|
| 3 |
+
The original database was available from (now defunct)
|
| 4 |
+
|
| 5 |
+
https://www.cl.cam.ac.uk/research/dtg/attarchive/facedatabase.html
|
| 6 |
+
|
| 7 |
+
The version retrieved here comes in MATLAB format from the personal
|
| 8 |
+
web page of Sam Roweis:
|
| 9 |
+
|
| 10 |
+
https://cs.nyu.edu/~roweis/
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
# Authors: The scikit-learn developers
|
| 14 |
+
# SPDX-License-Identifier: BSD-3-Clause
|
| 15 |
+
|
| 16 |
+
from numbers import Integral, Real
|
| 17 |
+
from os import PathLike, makedirs, remove
|
| 18 |
+
from os.path import exists
|
| 19 |
+
|
| 20 |
+
import joblib
|
| 21 |
+
import numpy as np
|
| 22 |
+
from scipy.io import loadmat
|
| 23 |
+
|
| 24 |
+
from ..utils import Bunch, check_random_state
|
| 25 |
+
from ..utils._param_validation import Interval, validate_params
|
| 26 |
+
from . import get_data_home
|
| 27 |
+
from ._base import RemoteFileMetadata, _fetch_remote, _pkl_filepath, load_descr
|
| 28 |
+
|
| 29 |
+
# The original data can be found at:
|
| 30 |
+
# https://cs.nyu.edu/~roweis/data/olivettifaces.mat
|
| 31 |
+
FACES = RemoteFileMetadata(
|
| 32 |
+
filename="olivettifaces.mat",
|
| 33 |
+
url="https://ndownloader.figshare.com/files/5976027",
|
| 34 |
+
checksum="b612fb967f2dc77c9c62d3e1266e0c73d5fca46a4b8906c18e454d41af987794",
|
| 35 |
+
)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
@validate_params(
|
| 39 |
+
{
|
| 40 |
+
"data_home": [str, PathLike, None],
|
| 41 |
+
"shuffle": ["boolean"],
|
| 42 |
+
"random_state": ["random_state"],
|
| 43 |
+
"download_if_missing": ["boolean"],
|
| 44 |
+
"return_X_y": ["boolean"],
|
| 45 |
+
"n_retries": [Interval(Integral, 1, None, closed="left")],
|
| 46 |
+
"delay": [Interval(Real, 0.0, None, closed="neither")],
|
| 47 |
+
},
|
| 48 |
+
prefer_skip_nested_validation=True,
|
| 49 |
+
)
|
| 50 |
+
def fetch_olivetti_faces(
|
| 51 |
+
*,
|
| 52 |
+
data_home=None,
|
| 53 |
+
shuffle=False,
|
| 54 |
+
random_state=0,
|
| 55 |
+
download_if_missing=True,
|
| 56 |
+
return_X_y=False,
|
| 57 |
+
n_retries=3,
|
| 58 |
+
delay=1.0,
|
| 59 |
+
):
|
| 60 |
+
"""Load the Olivetti faces data-set from AT&T (classification).
|
| 61 |
+
|
| 62 |
+
Download it if necessary.
|
| 63 |
+
|
| 64 |
+
================= =====================
|
| 65 |
+
Classes 40
|
| 66 |
+
Samples total 400
|
| 67 |
+
Dimensionality 4096
|
| 68 |
+
Features real, between 0 and 1
|
| 69 |
+
================= =====================
|
| 70 |
+
|
| 71 |
+
Read more in the :ref:`User Guide <olivetti_faces_dataset>`.
|
| 72 |
+
|
| 73 |
+
Parameters
|
| 74 |
+
----------
|
| 75 |
+
data_home : str or path-like, default=None
|
| 76 |
+
Specify another download and cache folder for the datasets. By default
|
| 77 |
+
all scikit-learn data is stored in '~/scikit_learn_data' subfolders.
|
| 78 |
+
|
| 79 |
+
shuffle : bool, default=False
|
| 80 |
+
If True the order of the dataset is shuffled to avoid having
|
| 81 |
+
images of the same person grouped.
|
| 82 |
+
|
| 83 |
+
random_state : int, RandomState instance or None, default=0
|
| 84 |
+
Determines random number generation for dataset shuffling. Pass an int
|
| 85 |
+
for reproducible output across multiple function calls.
|
| 86 |
+
See :term:`Glossary <random_state>`.
|
| 87 |
+
|
| 88 |
+
download_if_missing : bool, default=True
|
| 89 |
+
If False, raise an OSError if the data is not locally available
|
| 90 |
+
instead of trying to download the data from the source site.
|
| 91 |
+
|
| 92 |
+
return_X_y : bool, default=False
|
| 93 |
+
If True, returns `(data, target)` instead of a `Bunch` object. See
|
| 94 |
+
below for more information about the `data` and `target` object.
|
| 95 |
+
|
| 96 |
+
.. versionadded:: 0.22
|
| 97 |
+
|
| 98 |
+
n_retries : int, default=3
|
| 99 |
+
Number of retries when HTTP errors are encountered.
|
| 100 |
+
|
| 101 |
+
.. versionadded:: 1.5
|
| 102 |
+
|
| 103 |
+
delay : float, default=1.0
|
| 104 |
+
Number of seconds between retries.
|
| 105 |
+
|
| 106 |
+
.. versionadded:: 1.5
|
| 107 |
+
|
| 108 |
+
Returns
|
| 109 |
+
-------
|
| 110 |
+
data : :class:`~sklearn.utils.Bunch`
|
| 111 |
+
Dictionary-like object, with the following attributes.
|
| 112 |
+
|
| 113 |
+
data: ndarray, shape (400, 4096)
|
| 114 |
+
Each row corresponds to a ravelled
|
| 115 |
+
face image of original size 64 x 64 pixels.
|
| 116 |
+
images : ndarray, shape (400, 64, 64)
|
| 117 |
+
Each row is a face image
|
| 118 |
+
corresponding to one of the 40 subjects of the dataset.
|
| 119 |
+
target : ndarray, shape (400,)
|
| 120 |
+
Labels associated to each face image.
|
| 121 |
+
Those labels are ranging from 0-39 and correspond to the
|
| 122 |
+
Subject IDs.
|
| 123 |
+
DESCR : str
|
| 124 |
+
Description of the modified Olivetti Faces Dataset.
|
| 125 |
+
|
| 126 |
+
(data, target) : tuple if `return_X_y=True`
|
| 127 |
+
Tuple with the `data` and `target` objects described above.
|
| 128 |
+
|
| 129 |
+
.. versionadded:: 0.22
|
| 130 |
+
|
| 131 |
+
Examples
|
| 132 |
+
--------
|
| 133 |
+
>>> from sklearn.datasets import fetch_olivetti_faces
|
| 134 |
+
>>> olivetti_faces = fetch_olivetti_faces()
|
| 135 |
+
>>> olivetti_faces.data.shape
|
| 136 |
+
(400, 4096)
|
| 137 |
+
>>> olivetti_faces.target.shape
|
| 138 |
+
(400,)
|
| 139 |
+
>>> olivetti_faces.images.shape
|
| 140 |
+
(400, 64, 64)
|
| 141 |
+
"""
|
| 142 |
+
data_home = get_data_home(data_home=data_home)
|
| 143 |
+
if not exists(data_home):
|
| 144 |
+
makedirs(data_home)
|
| 145 |
+
filepath = _pkl_filepath(data_home, "olivetti.pkz")
|
| 146 |
+
if not exists(filepath):
|
| 147 |
+
if not download_if_missing:
|
| 148 |
+
raise OSError("Data not found and `download_if_missing` is False")
|
| 149 |
+
|
| 150 |
+
print("downloading Olivetti faces from %s to %s" % (FACES.url, data_home))
|
| 151 |
+
mat_path = _fetch_remote(
|
| 152 |
+
FACES, dirname=data_home, n_retries=n_retries, delay=delay
|
| 153 |
+
)
|
| 154 |
+
mfile = loadmat(file_name=mat_path)
|
| 155 |
+
# delete raw .mat data
|
| 156 |
+
remove(mat_path)
|
| 157 |
+
|
| 158 |
+
faces = mfile["faces"].T.copy()
|
| 159 |
+
joblib.dump(faces, filepath, compress=6)
|
| 160 |
+
del mfile
|
| 161 |
+
else:
|
| 162 |
+
faces = joblib.load(filepath)
|
| 163 |
+
|
| 164 |
+
# We want floating point data, but float32 is enough (there is only
|
| 165 |
+
# one byte of precision in the original uint8s anyway)
|
| 166 |
+
faces = np.float32(faces)
|
| 167 |
+
faces = faces - faces.min()
|
| 168 |
+
faces /= faces.max()
|
| 169 |
+
faces = faces.reshape((400, 64, 64)).transpose(0, 2, 1)
|
| 170 |
+
# 10 images per class, 400 images total, each class is contiguous.
|
| 171 |
+
target = np.array([i // 10 for i in range(400)])
|
| 172 |
+
if shuffle:
|
| 173 |
+
random_state = check_random_state(random_state)
|
| 174 |
+
order = random_state.permutation(len(faces))
|
| 175 |
+
faces = faces[order]
|
| 176 |
+
target = target[order]
|
| 177 |
+
faces_vectorized = faces.reshape(len(faces), -1)
|
| 178 |
+
|
| 179 |
+
fdescr = load_descr("olivetti_faces.rst")
|
| 180 |
+
|
| 181 |
+
if return_X_y:
|
| 182 |
+
return faces_vectorized, target
|
| 183 |
+
|
| 184 |
+
return Bunch(data=faces_vectorized, images=faces, target=target, DESCR=fdescr)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/datasets/_openml.py
ADDED
|
@@ -0,0 +1,1164 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Authors: The scikit-learn developers
|
| 2 |
+
# SPDX-License-Identifier: BSD-3-Clause
|
| 3 |
+
|
| 4 |
+
import gzip
|
| 5 |
+
import hashlib
|
| 6 |
+
import json
|
| 7 |
+
import os
|
| 8 |
+
import shutil
|
| 9 |
+
import time
|
| 10 |
+
from contextlib import closing
|
| 11 |
+
from functools import wraps
|
| 12 |
+
from os.path import join
|
| 13 |
+
from tempfile import TemporaryDirectory
|
| 14 |
+
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
|
| 15 |
+
from urllib.error import HTTPError, URLError
|
| 16 |
+
from urllib.parse import urlparse
|
| 17 |
+
from urllib.request import Request, urlopen
|
| 18 |
+
from warnings import warn
|
| 19 |
+
|
| 20 |
+
import numpy as np
|
| 21 |
+
|
| 22 |
+
from ..utils import Bunch
|
| 23 |
+
from ..utils._optional_dependencies import check_pandas_support
|
| 24 |
+
from ..utils._param_validation import (
|
| 25 |
+
Integral,
|
| 26 |
+
Interval,
|
| 27 |
+
Real,
|
| 28 |
+
StrOptions,
|
| 29 |
+
validate_params,
|
| 30 |
+
)
|
| 31 |
+
from . import get_data_home
|
| 32 |
+
from ._arff_parser import load_arff_from_gzip_file
|
| 33 |
+
|
| 34 |
+
__all__ = ["fetch_openml"]
|
| 35 |
+
|
| 36 |
+
_SEARCH_NAME = "https://api.openml.org/api/v1/json/data/list/data_name/{}/limit/2"
|
| 37 |
+
_DATA_INFO = "https://api.openml.org/api/v1/json/data/{}"
|
| 38 |
+
_DATA_FEATURES = "https://api.openml.org/api/v1/json/data/features/{}"
|
| 39 |
+
_DATA_QUALITIES = "https://api.openml.org/api/v1/json/data/qualities/{}"
|
| 40 |
+
|
| 41 |
+
OpenmlQualitiesType = List[Dict[str, str]]
|
| 42 |
+
OpenmlFeaturesType = List[Dict[str, str]]
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def _get_local_path(openml_path: str, data_home: str) -> str:
|
| 46 |
+
return os.path.join(data_home, "openml.org", openml_path + ".gz")
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def _retry_with_clean_cache(
|
| 50 |
+
openml_path: str,
|
| 51 |
+
data_home: Optional[str],
|
| 52 |
+
no_retry_exception: Optional[Exception] = None,
|
| 53 |
+
) -> Callable:
|
| 54 |
+
"""If the first call to the decorated function fails, the local cached
|
| 55 |
+
file is removed, and the function is called again. If ``data_home`` is
|
| 56 |
+
``None``, then the function is called once. We can provide a specific
|
| 57 |
+
exception to not retry on using `no_retry_exception` parameter.
|
| 58 |
+
"""
|
| 59 |
+
|
| 60 |
+
def decorator(f):
|
| 61 |
+
@wraps(f)
|
| 62 |
+
def wrapper(*args, **kw):
|
| 63 |
+
if data_home is None:
|
| 64 |
+
return f(*args, **kw)
|
| 65 |
+
try:
|
| 66 |
+
return f(*args, **kw)
|
| 67 |
+
except URLError:
|
| 68 |
+
raise
|
| 69 |
+
except Exception as exc:
|
| 70 |
+
if no_retry_exception is not None and isinstance(
|
| 71 |
+
exc, no_retry_exception
|
| 72 |
+
):
|
| 73 |
+
raise
|
| 74 |
+
warn("Invalid cache, redownloading file", RuntimeWarning)
|
| 75 |
+
local_path = _get_local_path(openml_path, data_home)
|
| 76 |
+
if os.path.exists(local_path):
|
| 77 |
+
os.unlink(local_path)
|
| 78 |
+
return f(*args, **kw)
|
| 79 |
+
|
| 80 |
+
return wrapper
|
| 81 |
+
|
| 82 |
+
return decorator
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def _retry_on_network_error(
|
| 86 |
+
n_retries: int = 3, delay: float = 1.0, url: str = ""
|
| 87 |
+
) -> Callable:
|
| 88 |
+
"""If the function call results in a network error, call the function again
|
| 89 |
+
up to ``n_retries`` times with a ``delay`` between each call. If the error
|
| 90 |
+
has a 412 status code, don't call the function again as this is a specific
|
| 91 |
+
OpenML error.
|
| 92 |
+
The url parameter is used to give more information to the user about the
|
| 93 |
+
error.
|
| 94 |
+
"""
|
| 95 |
+
|
| 96 |
+
def decorator(f):
|
| 97 |
+
@wraps(f)
|
| 98 |
+
def wrapper(*args, **kwargs):
|
| 99 |
+
retry_counter = n_retries
|
| 100 |
+
while True:
|
| 101 |
+
try:
|
| 102 |
+
return f(*args, **kwargs)
|
| 103 |
+
except (URLError, TimeoutError) as e:
|
| 104 |
+
# 412 is a specific OpenML error code.
|
| 105 |
+
if isinstance(e, HTTPError) and e.code == 412:
|
| 106 |
+
raise
|
| 107 |
+
if retry_counter == 0:
|
| 108 |
+
raise
|
| 109 |
+
warn(
|
| 110 |
+
f"A network error occurred while downloading {url}. Retrying..."
|
| 111 |
+
)
|
| 112 |
+
# Avoid a ResourceWarning on Python 3.14 and later.
|
| 113 |
+
if isinstance(e, HTTPError):
|
| 114 |
+
e.close()
|
| 115 |
+
|
| 116 |
+
retry_counter -= 1
|
| 117 |
+
time.sleep(delay)
|
| 118 |
+
|
| 119 |
+
return wrapper
|
| 120 |
+
|
| 121 |
+
return decorator
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def _open_openml_url(
|
| 125 |
+
url: str, data_home: Optional[str], n_retries: int = 3, delay: float = 1.0
|
| 126 |
+
):
|
| 127 |
+
"""
|
| 128 |
+
Returns a resource from OpenML.org. Caches it to data_home if required.
|
| 129 |
+
|
| 130 |
+
Parameters
|
| 131 |
+
----------
|
| 132 |
+
url : str
|
| 133 |
+
OpenML URL that will be downloaded and cached locally. The path component
|
| 134 |
+
of the URL is used to replicate the tree structure as sub-folders of the local
|
| 135 |
+
cache folder.
|
| 136 |
+
|
| 137 |
+
data_home : str
|
| 138 |
+
Directory to which the files will be cached. If None, no caching will
|
| 139 |
+
be applied.
|
| 140 |
+
|
| 141 |
+
n_retries : int, default=3
|
| 142 |
+
Number of retries when HTTP errors are encountered. Error with status
|
| 143 |
+
code 412 won't be retried as they represent OpenML generic errors.
|
| 144 |
+
|
| 145 |
+
delay : float, default=1.0
|
| 146 |
+
Number of seconds between retries.
|
| 147 |
+
|
| 148 |
+
Returns
|
| 149 |
+
-------
|
| 150 |
+
result : stream
|
| 151 |
+
A stream to the OpenML resource.
|
| 152 |
+
"""
|
| 153 |
+
|
| 154 |
+
def is_gzip_encoded(_fsrc):
|
| 155 |
+
return _fsrc.info().get("Content-Encoding", "") == "gzip"
|
| 156 |
+
|
| 157 |
+
req = Request(url)
|
| 158 |
+
req.add_header("Accept-encoding", "gzip")
|
| 159 |
+
|
| 160 |
+
if data_home is None:
|
| 161 |
+
fsrc = _retry_on_network_error(n_retries, delay, req.full_url)(urlopen)(req)
|
| 162 |
+
if is_gzip_encoded(fsrc):
|
| 163 |
+
return gzip.GzipFile(fileobj=fsrc, mode="rb")
|
| 164 |
+
return fsrc
|
| 165 |
+
|
| 166 |
+
openml_path = urlparse(url).path.lstrip("/")
|
| 167 |
+
local_path = _get_local_path(openml_path, data_home)
|
| 168 |
+
dir_name, file_name = os.path.split(local_path)
|
| 169 |
+
if not os.path.exists(local_path):
|
| 170 |
+
os.makedirs(dir_name, exist_ok=True)
|
| 171 |
+
try:
|
| 172 |
+
# Create a tmpdir as a subfolder of dir_name where the final file will
|
| 173 |
+
# be moved to if the download is successful. This guarantees that the
|
| 174 |
+
# renaming operation to the final location is atomic to ensure the
|
| 175 |
+
# concurrence safety of the dataset caching mechanism.
|
| 176 |
+
with TemporaryDirectory(dir=dir_name) as tmpdir:
|
| 177 |
+
with closing(
|
| 178 |
+
_retry_on_network_error(n_retries, delay, req.full_url)(urlopen)(
|
| 179 |
+
req
|
| 180 |
+
)
|
| 181 |
+
) as fsrc:
|
| 182 |
+
opener: Callable
|
| 183 |
+
if is_gzip_encoded(fsrc):
|
| 184 |
+
opener = open
|
| 185 |
+
else:
|
| 186 |
+
opener = gzip.GzipFile
|
| 187 |
+
with opener(os.path.join(tmpdir, file_name), "wb") as fdst:
|
| 188 |
+
shutil.copyfileobj(fsrc, fdst)
|
| 189 |
+
shutil.move(fdst.name, local_path)
|
| 190 |
+
except Exception:
|
| 191 |
+
if os.path.exists(local_path):
|
| 192 |
+
os.unlink(local_path)
|
| 193 |
+
raise
|
| 194 |
+
|
| 195 |
+
# XXX: First time, decompression will not be necessary (by using fsrc), but
|
| 196 |
+
# it will happen nonetheless
|
| 197 |
+
return gzip.GzipFile(local_path, "rb")
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
class OpenMLError(ValueError):
|
| 201 |
+
"""HTTP 412 is a specific OpenML error code, indicating a generic error"""
|
| 202 |
+
|
| 203 |
+
pass
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
def _get_json_content_from_openml_api(
|
| 207 |
+
url: str,
|
| 208 |
+
error_message: Optional[str],
|
| 209 |
+
data_home: Optional[str],
|
| 210 |
+
n_retries: int = 3,
|
| 211 |
+
delay: float = 1.0,
|
| 212 |
+
) -> Dict:
|
| 213 |
+
"""
|
| 214 |
+
Loads json data from the openml api.
|
| 215 |
+
|
| 216 |
+
Parameters
|
| 217 |
+
----------
|
| 218 |
+
url : str
|
| 219 |
+
The URL to load from. Should be an official OpenML endpoint.
|
| 220 |
+
|
| 221 |
+
error_message : str or None
|
| 222 |
+
The error message to raise if an acceptable OpenML error is thrown
|
| 223 |
+
(acceptable error is, e.g., data id not found. Other errors, like 404's
|
| 224 |
+
will throw the native error message).
|
| 225 |
+
|
| 226 |
+
data_home : str or None
|
| 227 |
+
Location to cache the response. None if no cache is required.
|
| 228 |
+
|
| 229 |
+
n_retries : int, default=3
|
| 230 |
+
Number of retries when HTTP errors are encountered. Error with status
|
| 231 |
+
code 412 won't be retried as they represent OpenML generic errors.
|
| 232 |
+
|
| 233 |
+
delay : float, default=1.0
|
| 234 |
+
Number of seconds between retries.
|
| 235 |
+
|
| 236 |
+
Returns
|
| 237 |
+
-------
|
| 238 |
+
json_data : json
|
| 239 |
+
the json result from the OpenML server if the call was successful.
|
| 240 |
+
An exception otherwise.
|
| 241 |
+
"""
|
| 242 |
+
|
| 243 |
+
@_retry_with_clean_cache(url, data_home=data_home)
|
| 244 |
+
def _load_json():
|
| 245 |
+
with closing(
|
| 246 |
+
_open_openml_url(url, data_home, n_retries=n_retries, delay=delay)
|
| 247 |
+
) as response:
|
| 248 |
+
return json.loads(response.read().decode("utf-8"))
|
| 249 |
+
|
| 250 |
+
try:
|
| 251 |
+
return _load_json()
|
| 252 |
+
except HTTPError as error:
|
| 253 |
+
# 412 is an OpenML specific error code, indicating a generic error
|
| 254 |
+
# (e.g., data not found)
|
| 255 |
+
if error.code != 412:
|
| 256 |
+
raise error
|
| 257 |
+
|
| 258 |
+
# 412 error, not in except for nicer traceback
|
| 259 |
+
raise OpenMLError(error_message)
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
def _get_data_info_by_name(
|
| 263 |
+
name: str,
|
| 264 |
+
version: Union[int, str],
|
| 265 |
+
data_home: Optional[str],
|
| 266 |
+
n_retries: int = 3,
|
| 267 |
+
delay: float = 1.0,
|
| 268 |
+
):
|
| 269 |
+
"""
|
| 270 |
+
Utilizes the openml dataset listing api to find a dataset by
|
| 271 |
+
name/version
|
| 272 |
+
OpenML api function:
|
| 273 |
+
https://www.openml.org/api_docs#!/data/get_data_list_data_name_data_name
|
| 274 |
+
|
| 275 |
+
Parameters
|
| 276 |
+
----------
|
| 277 |
+
name : str
|
| 278 |
+
name of the dataset
|
| 279 |
+
|
| 280 |
+
version : int or str
|
| 281 |
+
If version is an integer, the exact name/version will be obtained from
|
| 282 |
+
OpenML. If version is a string (value: "active") it will take the first
|
| 283 |
+
version from OpenML that is annotated as active. Any other string
|
| 284 |
+
values except "active" are treated as integer.
|
| 285 |
+
|
| 286 |
+
data_home : str or None
|
| 287 |
+
Location to cache the response. None if no cache is required.
|
| 288 |
+
|
| 289 |
+
n_retries : int, default=3
|
| 290 |
+
Number of retries when HTTP errors are encountered. Error with status
|
| 291 |
+
code 412 won't be retried as they represent OpenML generic errors.
|
| 292 |
+
|
| 293 |
+
delay : float, default=1.0
|
| 294 |
+
Number of seconds between retries.
|
| 295 |
+
|
| 296 |
+
Returns
|
| 297 |
+
-------
|
| 298 |
+
first_dataset : json
|
| 299 |
+
json representation of the first dataset object that adhired to the
|
| 300 |
+
search criteria
|
| 301 |
+
|
| 302 |
+
"""
|
| 303 |
+
if version == "active":
|
| 304 |
+
# situation in which we return the oldest active version
|
| 305 |
+
url = _SEARCH_NAME.format(name) + "/status/active/"
|
| 306 |
+
error_msg = "No active dataset {} found.".format(name)
|
| 307 |
+
json_data = _get_json_content_from_openml_api(
|
| 308 |
+
url,
|
| 309 |
+
error_msg,
|
| 310 |
+
data_home=data_home,
|
| 311 |
+
n_retries=n_retries,
|
| 312 |
+
delay=delay,
|
| 313 |
+
)
|
| 314 |
+
res = json_data["data"]["dataset"]
|
| 315 |
+
if len(res) > 1:
|
| 316 |
+
first_version = version = res[0]["version"]
|
| 317 |
+
warning_msg = (
|
| 318 |
+
"Multiple active versions of the dataset matching the name"
|
| 319 |
+
f" {name} exist. Versions may be fundamentally different, "
|
| 320 |
+
f"returning version {first_version}. "
|
| 321 |
+
"Available versions:\n"
|
| 322 |
+
)
|
| 323 |
+
for r in res:
|
| 324 |
+
warning_msg += f"- version {r['version']}, status: {r['status']}\n"
|
| 325 |
+
warning_msg += (
|
| 326 |
+
f" url: https://www.openml.org/search?type=data&id={r['did']}\n"
|
| 327 |
+
)
|
| 328 |
+
warn(warning_msg)
|
| 329 |
+
return res[0]
|
| 330 |
+
|
| 331 |
+
# an integer version has been provided
|
| 332 |
+
url = (_SEARCH_NAME + "/data_version/{}").format(name, version)
|
| 333 |
+
try:
|
| 334 |
+
json_data = _get_json_content_from_openml_api(
|
| 335 |
+
url,
|
| 336 |
+
error_message=None,
|
| 337 |
+
data_home=data_home,
|
| 338 |
+
n_retries=n_retries,
|
| 339 |
+
delay=delay,
|
| 340 |
+
)
|
| 341 |
+
except OpenMLError:
|
| 342 |
+
# we can do this in 1 function call if OpenML does not require the
|
| 343 |
+
# specification of the dataset status (i.e., return datasets with a
|
| 344 |
+
# given name / version regardless of active, deactivated, etc. )
|
| 345 |
+
# TODO: feature request OpenML.
|
| 346 |
+
url += "/status/deactivated"
|
| 347 |
+
error_msg = "Dataset {} with version {} not found.".format(name, version)
|
| 348 |
+
json_data = _get_json_content_from_openml_api(
|
| 349 |
+
url,
|
| 350 |
+
error_msg,
|
| 351 |
+
data_home=data_home,
|
| 352 |
+
n_retries=n_retries,
|
| 353 |
+
delay=delay,
|
| 354 |
+
)
|
| 355 |
+
|
| 356 |
+
return json_data["data"]["dataset"][0]
|
| 357 |
+
|
| 358 |
+
|
| 359 |
+
def _get_data_description_by_id(
|
| 360 |
+
data_id: int,
|
| 361 |
+
data_home: Optional[str],
|
| 362 |
+
n_retries: int = 3,
|
| 363 |
+
delay: float = 1.0,
|
| 364 |
+
) -> Dict[str, Any]:
|
| 365 |
+
# OpenML API function: https://www.openml.org/api_docs#!/data/get_data_id
|
| 366 |
+
url = _DATA_INFO.format(data_id)
|
| 367 |
+
error_message = "Dataset with data_id {} not found.".format(data_id)
|
| 368 |
+
json_data = _get_json_content_from_openml_api(
|
| 369 |
+
url,
|
| 370 |
+
error_message,
|
| 371 |
+
data_home=data_home,
|
| 372 |
+
n_retries=n_retries,
|
| 373 |
+
delay=delay,
|
| 374 |
+
)
|
| 375 |
+
return json_data["data_set_description"]
|
| 376 |
+
|
| 377 |
+
|
| 378 |
+
def _get_data_features(
|
| 379 |
+
data_id: int,
|
| 380 |
+
data_home: Optional[str],
|
| 381 |
+
n_retries: int = 3,
|
| 382 |
+
delay: float = 1.0,
|
| 383 |
+
) -> OpenmlFeaturesType:
|
| 384 |
+
# OpenML function:
|
| 385 |
+
# https://www.openml.org/api_docs#!/data/get_data_features_id
|
| 386 |
+
url = _DATA_FEATURES.format(data_id)
|
| 387 |
+
error_message = "Dataset with data_id {} not found.".format(data_id)
|
| 388 |
+
json_data = _get_json_content_from_openml_api(
|
| 389 |
+
url,
|
| 390 |
+
error_message,
|
| 391 |
+
data_home=data_home,
|
| 392 |
+
n_retries=n_retries,
|
| 393 |
+
delay=delay,
|
| 394 |
+
)
|
| 395 |
+
return json_data["data_features"]["feature"]
|
| 396 |
+
|
| 397 |
+
|
| 398 |
+
def _get_data_qualities(
|
| 399 |
+
data_id: int,
|
| 400 |
+
data_home: Optional[str],
|
| 401 |
+
n_retries: int = 3,
|
| 402 |
+
delay: float = 1.0,
|
| 403 |
+
) -> OpenmlQualitiesType:
|
| 404 |
+
# OpenML API function:
|
| 405 |
+
# https://www.openml.org/api_docs#!/data/get_data_qualities_id
|
| 406 |
+
url = _DATA_QUALITIES.format(data_id)
|
| 407 |
+
error_message = "Dataset with data_id {} not found.".format(data_id)
|
| 408 |
+
json_data = _get_json_content_from_openml_api(
|
| 409 |
+
url,
|
| 410 |
+
error_message,
|
| 411 |
+
data_home=data_home,
|
| 412 |
+
n_retries=n_retries,
|
| 413 |
+
delay=delay,
|
| 414 |
+
)
|
| 415 |
+
# the qualities might not be available, but we still try to process
|
| 416 |
+
# the data
|
| 417 |
+
return json_data.get("data_qualities", {}).get("quality", [])
|
| 418 |
+
|
| 419 |
+
|
| 420 |
+
def _get_num_samples(data_qualities: OpenmlQualitiesType) -> int:
|
| 421 |
+
"""Get the number of samples from data qualities.
|
| 422 |
+
|
| 423 |
+
Parameters
|
| 424 |
+
----------
|
| 425 |
+
data_qualities : list of dict
|
| 426 |
+
Used to retrieve the number of instances (samples) in the dataset.
|
| 427 |
+
|
| 428 |
+
Returns
|
| 429 |
+
-------
|
| 430 |
+
n_samples : int
|
| 431 |
+
The number of samples in the dataset or -1 if data qualities are
|
| 432 |
+
unavailable.
|
| 433 |
+
"""
|
| 434 |
+
# If the data qualities are unavailable, we return -1
|
| 435 |
+
default_n_samples = -1
|
| 436 |
+
|
| 437 |
+
qualities = {d["name"]: d["value"] for d in data_qualities}
|
| 438 |
+
return int(float(qualities.get("NumberOfInstances", default_n_samples)))
|
| 439 |
+
|
| 440 |
+
|
| 441 |
+
def _load_arff_response(
|
| 442 |
+
url: str,
|
| 443 |
+
data_home: Optional[str],
|
| 444 |
+
parser: str,
|
| 445 |
+
output_type: str,
|
| 446 |
+
openml_columns_info: dict,
|
| 447 |
+
feature_names_to_select: List[str],
|
| 448 |
+
target_names_to_select: List[str],
|
| 449 |
+
shape: Optional[Tuple[int, int]],
|
| 450 |
+
md5_checksum: str,
|
| 451 |
+
n_retries: int = 3,
|
| 452 |
+
delay: float = 1.0,
|
| 453 |
+
read_csv_kwargs: Optional[Dict] = None,
|
| 454 |
+
):
|
| 455 |
+
"""Load the ARFF data associated with the OpenML URL.
|
| 456 |
+
|
| 457 |
+
In addition of loading the data, this function will also check the
|
| 458 |
+
integrity of the downloaded file from OpenML using MD5 checksum.
|
| 459 |
+
|
| 460 |
+
Parameters
|
| 461 |
+
----------
|
| 462 |
+
url : str
|
| 463 |
+
The URL of the ARFF file on OpenML.
|
| 464 |
+
|
| 465 |
+
data_home : str
|
| 466 |
+
The location where to cache the data.
|
| 467 |
+
|
| 468 |
+
parser : {"liac-arff", "pandas"}
|
| 469 |
+
The parser used to parse the ARFF file.
|
| 470 |
+
|
| 471 |
+
output_type : {"numpy", "pandas", "sparse"}
|
| 472 |
+
The type of the arrays that will be returned. The possibilities are:
|
| 473 |
+
|
| 474 |
+
- `"numpy"`: both `X` and `y` will be NumPy arrays;
|
| 475 |
+
- `"sparse"`: `X` will be sparse matrix and `y` will be a NumPy array;
|
| 476 |
+
- `"pandas"`: `X` will be a pandas DataFrame and `y` will be either a
|
| 477 |
+
pandas Series or DataFrame.
|
| 478 |
+
|
| 479 |
+
openml_columns_info : dict
|
| 480 |
+
The information provided by OpenML regarding the columns of the ARFF
|
| 481 |
+
file.
|
| 482 |
+
|
| 483 |
+
feature_names_to_select : list of str
|
| 484 |
+
The list of the features to be selected.
|
| 485 |
+
|
| 486 |
+
target_names_to_select : list of str
|
| 487 |
+
The list of the target variables to be selected.
|
| 488 |
+
|
| 489 |
+
shape : tuple or None
|
| 490 |
+
With `parser="liac-arff"`, when using a generator to load the data,
|
| 491 |
+
one needs to provide the shape of the data beforehand.
|
| 492 |
+
|
| 493 |
+
md5_checksum : str
|
| 494 |
+
The MD5 checksum provided by OpenML to check the data integrity.
|
| 495 |
+
|
| 496 |
+
n_retries : int, default=3
|
| 497 |
+
The number of times to retry downloading the data if it fails.
|
| 498 |
+
|
| 499 |
+
delay : float, default=1.0
|
| 500 |
+
The delay between two consecutive downloads in seconds.
|
| 501 |
+
|
| 502 |
+
read_csv_kwargs : dict, default=None
|
| 503 |
+
Keyword arguments to pass to `pandas.read_csv` when using the pandas parser.
|
| 504 |
+
It allows to overwrite the default options.
|
| 505 |
+
|
| 506 |
+
.. versionadded:: 1.3
|
| 507 |
+
|
| 508 |
+
Returns
|
| 509 |
+
-------
|
| 510 |
+
X : {ndarray, sparse matrix, dataframe}
|
| 511 |
+
The data matrix.
|
| 512 |
+
|
| 513 |
+
y : {ndarray, dataframe, series}
|
| 514 |
+
The target.
|
| 515 |
+
|
| 516 |
+
frame : dataframe or None
|
| 517 |
+
A dataframe containing both `X` and `y`. `None` if
|
| 518 |
+
`output_array_type != "pandas"`.
|
| 519 |
+
|
| 520 |
+
categories : list of str or None
|
| 521 |
+
The names of the features that are categorical. `None` if
|
| 522 |
+
`output_array_type == "pandas"`.
|
| 523 |
+
"""
|
| 524 |
+
gzip_file = _open_openml_url(url, data_home, n_retries=n_retries, delay=delay)
|
| 525 |
+
with closing(gzip_file):
|
| 526 |
+
md5 = hashlib.md5()
|
| 527 |
+
for chunk in iter(lambda: gzip_file.read(4096), b""):
|
| 528 |
+
md5.update(chunk)
|
| 529 |
+
actual_md5_checksum = md5.hexdigest()
|
| 530 |
+
|
| 531 |
+
if actual_md5_checksum != md5_checksum:
|
| 532 |
+
raise ValueError(
|
| 533 |
+
f"md5 checksum of local file for {url} does not match description: "
|
| 534 |
+
f"expected: {md5_checksum} but got {actual_md5_checksum}. "
|
| 535 |
+
"Downloaded file could have been modified / corrupted, clean cache "
|
| 536 |
+
"and retry..."
|
| 537 |
+
)
|
| 538 |
+
|
| 539 |
+
def _open_url_and_load_gzip_file(url, data_home, n_retries, delay, arff_params):
|
| 540 |
+
gzip_file = _open_openml_url(url, data_home, n_retries=n_retries, delay=delay)
|
| 541 |
+
with closing(gzip_file):
|
| 542 |
+
return load_arff_from_gzip_file(gzip_file, **arff_params)
|
| 543 |
+
|
| 544 |
+
arff_params: Dict = dict(
|
| 545 |
+
parser=parser,
|
| 546 |
+
output_type=output_type,
|
| 547 |
+
openml_columns_info=openml_columns_info,
|
| 548 |
+
feature_names_to_select=feature_names_to_select,
|
| 549 |
+
target_names_to_select=target_names_to_select,
|
| 550 |
+
shape=shape,
|
| 551 |
+
read_csv_kwargs=read_csv_kwargs or {},
|
| 552 |
+
)
|
| 553 |
+
try:
|
| 554 |
+
X, y, frame, categories = _open_url_and_load_gzip_file(
|
| 555 |
+
url, data_home, n_retries, delay, arff_params
|
| 556 |
+
)
|
| 557 |
+
except Exception as exc:
|
| 558 |
+
if parser != "pandas":
|
| 559 |
+
raise
|
| 560 |
+
|
| 561 |
+
from pandas.errors import ParserError
|
| 562 |
+
|
| 563 |
+
if not isinstance(exc, ParserError):
|
| 564 |
+
raise
|
| 565 |
+
|
| 566 |
+
# A parsing error could come from providing the wrong quotechar
|
| 567 |
+
# to pandas. By default, we use a double quote. Thus, we retry
|
| 568 |
+
# with a single quote before to raise the error.
|
| 569 |
+
arff_params["read_csv_kwargs"].update(quotechar="'")
|
| 570 |
+
X, y, frame, categories = _open_url_and_load_gzip_file(
|
| 571 |
+
url, data_home, n_retries, delay, arff_params
|
| 572 |
+
)
|
| 573 |
+
|
| 574 |
+
return X, y, frame, categories
|
| 575 |
+
|
| 576 |
+
|
| 577 |
+
def _download_data_to_bunch(
|
| 578 |
+
url: str,
|
| 579 |
+
sparse: bool,
|
| 580 |
+
data_home: Optional[str],
|
| 581 |
+
*,
|
| 582 |
+
as_frame: bool,
|
| 583 |
+
openml_columns_info: List[dict],
|
| 584 |
+
data_columns: List[str],
|
| 585 |
+
target_columns: List[str],
|
| 586 |
+
shape: Optional[Tuple[int, int]],
|
| 587 |
+
md5_checksum: str,
|
| 588 |
+
n_retries: int = 3,
|
| 589 |
+
delay: float = 1.0,
|
| 590 |
+
parser: str,
|
| 591 |
+
read_csv_kwargs: Optional[Dict] = None,
|
| 592 |
+
):
|
| 593 |
+
"""Download ARFF data, load it to a specific container and create to Bunch.
|
| 594 |
+
|
| 595 |
+
This function has a mechanism to retry/cache/clean the data.
|
| 596 |
+
|
| 597 |
+
Parameters
|
| 598 |
+
----------
|
| 599 |
+
url : str
|
| 600 |
+
The URL of the ARFF file on OpenML.
|
| 601 |
+
|
| 602 |
+
sparse : bool
|
| 603 |
+
Whether the dataset is expected to use the sparse ARFF format.
|
| 604 |
+
|
| 605 |
+
data_home : str
|
| 606 |
+
The location where to cache the data.
|
| 607 |
+
|
| 608 |
+
as_frame : bool
|
| 609 |
+
Whether or not to return the data into a pandas DataFrame.
|
| 610 |
+
|
| 611 |
+
openml_columns_info : list of dict
|
| 612 |
+
The information regarding the columns provided by OpenML for the
|
| 613 |
+
ARFF dataset. The information is stored as a list of dictionaries.
|
| 614 |
+
|
| 615 |
+
data_columns : list of str
|
| 616 |
+
The list of the features to be selected.
|
| 617 |
+
|
| 618 |
+
target_columns : list of str
|
| 619 |
+
The list of the target variables to be selected.
|
| 620 |
+
|
| 621 |
+
shape : tuple or None
|
| 622 |
+
With `parser="liac-arff"`, when using a generator to load the data,
|
| 623 |
+
one needs to provide the shape of the data beforehand.
|
| 624 |
+
|
| 625 |
+
md5_checksum : str
|
| 626 |
+
The MD5 checksum provided by OpenML to check the data integrity.
|
| 627 |
+
|
| 628 |
+
n_retries : int, default=3
|
| 629 |
+
Number of retries when HTTP errors are encountered. Error with status
|
| 630 |
+
code 412 won't be retried as they represent OpenML generic errors.
|
| 631 |
+
|
| 632 |
+
delay : float, default=1.0
|
| 633 |
+
Number of seconds between retries.
|
| 634 |
+
|
| 635 |
+
parser : {"liac-arff", "pandas"}
|
| 636 |
+
The parser used to parse the ARFF file.
|
| 637 |
+
|
| 638 |
+
read_csv_kwargs : dict, default=None
|
| 639 |
+
Keyword arguments to pass to `pandas.read_csv` when using the pandas parser.
|
| 640 |
+
It allows to overwrite the default options.
|
| 641 |
+
|
| 642 |
+
.. versionadded:: 1.3
|
| 643 |
+
|
| 644 |
+
Returns
|
| 645 |
+
-------
|
| 646 |
+
data : :class:`~sklearn.utils.Bunch`
|
| 647 |
+
Dictionary-like object, with the following attributes.
|
| 648 |
+
|
| 649 |
+
X : {ndarray, sparse matrix, dataframe}
|
| 650 |
+
The data matrix.
|
| 651 |
+
y : {ndarray, dataframe, series}
|
| 652 |
+
The target.
|
| 653 |
+
frame : dataframe or None
|
| 654 |
+
A dataframe containing both `X` and `y`. `None` if
|
| 655 |
+
`output_array_type != "pandas"`.
|
| 656 |
+
categories : list of str or None
|
| 657 |
+
The names of the features that are categorical. `None` if
|
| 658 |
+
`output_array_type == "pandas"`.
|
| 659 |
+
"""
|
| 660 |
+
# Prepare which columns and data types should be returned for the X and y
|
| 661 |
+
features_dict = {feature["name"]: feature for feature in openml_columns_info}
|
| 662 |
+
|
| 663 |
+
if sparse:
|
| 664 |
+
output_type = "sparse"
|
| 665 |
+
elif as_frame:
|
| 666 |
+
output_type = "pandas"
|
| 667 |
+
else:
|
| 668 |
+
output_type = "numpy"
|
| 669 |
+
|
| 670 |
+
# XXX: target columns should all be categorical or all numeric
|
| 671 |
+
_verify_target_data_type(features_dict, target_columns)
|
| 672 |
+
for name in target_columns:
|
| 673 |
+
column_info = features_dict[name]
|
| 674 |
+
n_missing_values = int(column_info["number_of_missing_values"])
|
| 675 |
+
if n_missing_values > 0:
|
| 676 |
+
raise ValueError(
|
| 677 |
+
f"Target column '{column_info['name']}' has {n_missing_values} missing "
|
| 678 |
+
"values. Missing values are not supported for target columns."
|
| 679 |
+
)
|
| 680 |
+
|
| 681 |
+
no_retry_exception = None
|
| 682 |
+
if parser == "pandas":
|
| 683 |
+
# If we get a ParserError with pandas, then we don't want to retry and we raise
|
| 684 |
+
# early.
|
| 685 |
+
from pandas.errors import ParserError
|
| 686 |
+
|
| 687 |
+
no_retry_exception = ParserError
|
| 688 |
+
|
| 689 |
+
X, y, frame, categories = _retry_with_clean_cache(
|
| 690 |
+
url, data_home, no_retry_exception
|
| 691 |
+
)(_load_arff_response)(
|
| 692 |
+
url,
|
| 693 |
+
data_home,
|
| 694 |
+
parser=parser,
|
| 695 |
+
output_type=output_type,
|
| 696 |
+
openml_columns_info=features_dict,
|
| 697 |
+
feature_names_to_select=data_columns,
|
| 698 |
+
target_names_to_select=target_columns,
|
| 699 |
+
shape=shape,
|
| 700 |
+
md5_checksum=md5_checksum,
|
| 701 |
+
n_retries=n_retries,
|
| 702 |
+
delay=delay,
|
| 703 |
+
read_csv_kwargs=read_csv_kwargs,
|
| 704 |
+
)
|
| 705 |
+
|
| 706 |
+
return Bunch(
|
| 707 |
+
data=X,
|
| 708 |
+
target=y,
|
| 709 |
+
frame=frame,
|
| 710 |
+
categories=categories,
|
| 711 |
+
feature_names=data_columns,
|
| 712 |
+
target_names=target_columns,
|
| 713 |
+
)
|
| 714 |
+
|
| 715 |
+
|
| 716 |
+
def _verify_target_data_type(features_dict, target_columns):
|
| 717 |
+
# verifies the data type of the y array in case there are multiple targets
|
| 718 |
+
# (throws an error if these targets do not comply with sklearn support)
|
| 719 |
+
if not isinstance(target_columns, list):
|
| 720 |
+
raise ValueError("target_column should be list, got: %s" % type(target_columns))
|
| 721 |
+
found_types = set()
|
| 722 |
+
for target_column in target_columns:
|
| 723 |
+
if target_column not in features_dict:
|
| 724 |
+
raise KeyError(f"Could not find target_column='{target_column}'")
|
| 725 |
+
if features_dict[target_column]["data_type"] == "numeric":
|
| 726 |
+
found_types.add(np.float64)
|
| 727 |
+
else:
|
| 728 |
+
found_types.add(object)
|
| 729 |
+
|
| 730 |
+
# note: we compare to a string, not boolean
|
| 731 |
+
if features_dict[target_column]["is_ignore"] == "true":
|
| 732 |
+
warn(f"target_column='{target_column}' has flag is_ignore.")
|
| 733 |
+
if features_dict[target_column]["is_row_identifier"] == "true":
|
| 734 |
+
warn(f"target_column='{target_column}' has flag is_row_identifier.")
|
| 735 |
+
if len(found_types) > 1:
|
| 736 |
+
raise ValueError(
|
| 737 |
+
"Can only handle homogeneous multi-target datasets, "
|
| 738 |
+
"i.e., all targets are either numeric or "
|
| 739 |
+
"categorical."
|
| 740 |
+
)
|
| 741 |
+
|
| 742 |
+
|
| 743 |
+
def _valid_data_column_names(features_list, target_columns):
|
| 744 |
+
# logic for determining on which columns can be learned. Note that from the
|
| 745 |
+
# OpenML guide follows that columns that have the `is_row_identifier` or
|
| 746 |
+
# `is_ignore` flag, these can not be learned on. Also target columns are
|
| 747 |
+
# excluded.
|
| 748 |
+
valid_data_column_names = []
|
| 749 |
+
for feature in features_list:
|
| 750 |
+
if (
|
| 751 |
+
feature["name"] not in target_columns
|
| 752 |
+
and feature["is_ignore"] != "true"
|
| 753 |
+
and feature["is_row_identifier"] != "true"
|
| 754 |
+
):
|
| 755 |
+
valid_data_column_names.append(feature["name"])
|
| 756 |
+
return valid_data_column_names
|
| 757 |
+
|
| 758 |
+
|
| 759 |
+
@validate_params(
|
| 760 |
+
{
|
| 761 |
+
"name": [str, None],
|
| 762 |
+
"version": [Interval(Integral, 1, None, closed="left"), StrOptions({"active"})],
|
| 763 |
+
"data_id": [Interval(Integral, 1, None, closed="left"), None],
|
| 764 |
+
"data_home": [str, os.PathLike, None],
|
| 765 |
+
"target_column": [str, list, None],
|
| 766 |
+
"cache": [bool],
|
| 767 |
+
"return_X_y": [bool],
|
| 768 |
+
"as_frame": [bool, StrOptions({"auto"})],
|
| 769 |
+
"n_retries": [Interval(Integral, 1, None, closed="left")],
|
| 770 |
+
"delay": [Interval(Real, 0.0, None, closed="neither")],
|
| 771 |
+
"parser": [
|
| 772 |
+
StrOptions({"auto", "pandas", "liac-arff"}),
|
| 773 |
+
],
|
| 774 |
+
"read_csv_kwargs": [dict, None],
|
| 775 |
+
},
|
| 776 |
+
prefer_skip_nested_validation=True,
|
| 777 |
+
)
|
| 778 |
+
def fetch_openml(
|
| 779 |
+
name: Optional[str] = None,
|
| 780 |
+
*,
|
| 781 |
+
version: Union[str, int] = "active",
|
| 782 |
+
data_id: Optional[int] = None,
|
| 783 |
+
data_home: Optional[Union[str, os.PathLike]] = None,
|
| 784 |
+
target_column: Optional[Union[str, List]] = "default-target",
|
| 785 |
+
cache: bool = True,
|
| 786 |
+
return_X_y: bool = False,
|
| 787 |
+
as_frame: Union[str, bool] = "auto",
|
| 788 |
+
n_retries: int = 3,
|
| 789 |
+
delay: float = 1.0,
|
| 790 |
+
parser: str = "auto",
|
| 791 |
+
read_csv_kwargs: Optional[Dict] = None,
|
| 792 |
+
):
|
| 793 |
+
"""Fetch dataset from openml by name or dataset id.
|
| 794 |
+
|
| 795 |
+
Datasets are uniquely identified by either an integer ID or by a
|
| 796 |
+
combination of name and version (i.e. there might be multiple
|
| 797 |
+
versions of the 'iris' dataset). Please give either name or data_id
|
| 798 |
+
(not both). In case a name is given, a version can also be
|
| 799 |
+
provided.
|
| 800 |
+
|
| 801 |
+
Read more in the :ref:`User Guide <openml>`.
|
| 802 |
+
|
| 803 |
+
.. versionadded:: 0.20
|
| 804 |
+
|
| 805 |
+
.. note:: EXPERIMENTAL
|
| 806 |
+
|
| 807 |
+
The API is experimental (particularly the return value structure),
|
| 808 |
+
and might have small backward-incompatible changes without notice
|
| 809 |
+
or warning in future releases.
|
| 810 |
+
|
| 811 |
+
Parameters
|
| 812 |
+
----------
|
| 813 |
+
name : str, default=None
|
| 814 |
+
String identifier of the dataset. Note that OpenML can have multiple
|
| 815 |
+
datasets with the same name.
|
| 816 |
+
|
| 817 |
+
version : int or 'active', default='active'
|
| 818 |
+
Version of the dataset. Can only be provided if also ``name`` is given.
|
| 819 |
+
If 'active' the oldest version that's still active is used. Since
|
| 820 |
+
there may be more than one active version of a dataset, and those
|
| 821 |
+
versions may fundamentally be different from one another, setting an
|
| 822 |
+
exact version is highly recommended.
|
| 823 |
+
|
| 824 |
+
data_id : int, default=None
|
| 825 |
+
OpenML ID of the dataset. The most specific way of retrieving a
|
| 826 |
+
dataset. If data_id is not given, name (and potential version) are
|
| 827 |
+
used to obtain a dataset.
|
| 828 |
+
|
| 829 |
+
data_home : str or path-like, default=None
|
| 830 |
+
Specify another download and cache folder for the data sets. By default
|
| 831 |
+
all scikit-learn data is stored in '~/scikit_learn_data' subfolders.
|
| 832 |
+
|
| 833 |
+
target_column : str, list or None, default='default-target'
|
| 834 |
+
Specify the column name in the data to use as target. If
|
| 835 |
+
'default-target', the standard target column a stored on the server
|
| 836 |
+
is used. If ``None``, all columns are returned as data and the
|
| 837 |
+
target is ``None``. If list (of strings), all columns with these names
|
| 838 |
+
are returned as multi-target (Note: not all scikit-learn classifiers
|
| 839 |
+
can handle all types of multi-output combinations).
|
| 840 |
+
|
| 841 |
+
cache : bool, default=True
|
| 842 |
+
Whether to cache the downloaded datasets into `data_home`.
|
| 843 |
+
|
| 844 |
+
return_X_y : bool, default=False
|
| 845 |
+
If True, returns ``(data, target)`` instead of a Bunch object. See
|
| 846 |
+
below for more information about the `data` and `target` objects.
|
| 847 |
+
|
| 848 |
+
as_frame : bool or 'auto', default='auto'
|
| 849 |
+
If True, the data is a pandas DataFrame including columns with
|
| 850 |
+
appropriate dtypes (numeric, string or categorical). The target is
|
| 851 |
+
a pandas DataFrame or Series depending on the number of target_columns.
|
| 852 |
+
The Bunch will contain a ``frame`` attribute with the target and the
|
| 853 |
+
data. If ``return_X_y`` is True, then ``(data, target)`` will be pandas
|
| 854 |
+
DataFrames or Series as describe above.
|
| 855 |
+
|
| 856 |
+
If `as_frame` is 'auto', the data and target will be converted to
|
| 857 |
+
DataFrame or Series as if `as_frame` is set to True, unless the dataset
|
| 858 |
+
is stored in sparse format.
|
| 859 |
+
|
| 860 |
+
If `as_frame` is False, the data and target will be NumPy arrays and
|
| 861 |
+
the `data` will only contain numerical values when `parser="liac-arff"`
|
| 862 |
+
where the categories are provided in the attribute `categories` of the
|
| 863 |
+
`Bunch` instance. When `parser="pandas"`, no ordinal encoding is made.
|
| 864 |
+
|
| 865 |
+
.. versionchanged:: 0.24
|
| 866 |
+
The default value of `as_frame` changed from `False` to `'auto'`
|
| 867 |
+
in 0.24.
|
| 868 |
+
|
| 869 |
+
n_retries : int, default=3
|
| 870 |
+
Number of retries when HTTP errors or network timeouts are encountered.
|
| 871 |
+
Error with status code 412 won't be retried as they represent OpenML
|
| 872 |
+
generic errors.
|
| 873 |
+
|
| 874 |
+
delay : float, default=1.0
|
| 875 |
+
Number of seconds between retries.
|
| 876 |
+
|
| 877 |
+
parser : {"auto", "pandas", "liac-arff"}, default="auto"
|
| 878 |
+
Parser used to load the ARFF file. Two parsers are implemented:
|
| 879 |
+
|
| 880 |
+
- `"pandas"`: this is the most efficient parser. However, it requires
|
| 881 |
+
pandas to be installed and can only open dense datasets.
|
| 882 |
+
- `"liac-arff"`: this is a pure Python ARFF parser that is much less
|
| 883 |
+
memory- and CPU-efficient. It deals with sparse ARFF datasets.
|
| 884 |
+
|
| 885 |
+
If `"auto"`, the parser is chosen automatically such that `"liac-arff"`
|
| 886 |
+
is selected for sparse ARFF datasets, otherwise `"pandas"` is selected.
|
| 887 |
+
|
| 888 |
+
.. versionadded:: 1.2
|
| 889 |
+
.. versionchanged:: 1.4
|
| 890 |
+
The default value of `parser` changes from `"liac-arff"` to
|
| 891 |
+
`"auto"`.
|
| 892 |
+
|
| 893 |
+
read_csv_kwargs : dict, default=None
|
| 894 |
+
Keyword arguments passed to :func:`pandas.read_csv` when loading the data
|
| 895 |
+
from a ARFF file and using the pandas parser. It can allow to
|
| 896 |
+
overwrite some default parameters.
|
| 897 |
+
|
| 898 |
+
.. versionadded:: 1.3
|
| 899 |
+
|
| 900 |
+
Returns
|
| 901 |
+
-------
|
| 902 |
+
data : :class:`~sklearn.utils.Bunch`
|
| 903 |
+
Dictionary-like object, with the following attributes.
|
| 904 |
+
|
| 905 |
+
data : np.array, scipy.sparse.csr_matrix of floats, or pandas DataFrame
|
| 906 |
+
The feature matrix. Categorical features are encoded as ordinals.
|
| 907 |
+
target : np.array, pandas Series or DataFrame
|
| 908 |
+
The regression target or classification labels, if applicable.
|
| 909 |
+
Dtype is float if numeric, and object if categorical. If
|
| 910 |
+
``as_frame`` is True, ``target`` is a pandas object.
|
| 911 |
+
DESCR : str
|
| 912 |
+
The full description of the dataset.
|
| 913 |
+
feature_names : list
|
| 914 |
+
The names of the dataset columns.
|
| 915 |
+
target_names: list
|
| 916 |
+
The names of the target columns.
|
| 917 |
+
|
| 918 |
+
.. versionadded:: 0.22
|
| 919 |
+
|
| 920 |
+
categories : dict or None
|
| 921 |
+
Maps each categorical feature name to a list of values, such
|
| 922 |
+
that the value encoded as i is ith in the list. If ``as_frame``
|
| 923 |
+
is True, this is None.
|
| 924 |
+
details : dict
|
| 925 |
+
More metadata from OpenML.
|
| 926 |
+
frame : pandas DataFrame
|
| 927 |
+
Only present when `as_frame=True`. DataFrame with ``data`` and
|
| 928 |
+
``target``.
|
| 929 |
+
|
| 930 |
+
(data, target) : tuple if ``return_X_y`` is True
|
| 931 |
+
|
| 932 |
+
.. note:: EXPERIMENTAL
|
| 933 |
+
|
| 934 |
+
This interface is **experimental** and subsequent releases may
|
| 935 |
+
change attributes without notice (although there should only be
|
| 936 |
+
minor changes to ``data`` and ``target``).
|
| 937 |
+
|
| 938 |
+
Missing values in the 'data' are represented as NaN's. Missing values
|
| 939 |
+
in 'target' are represented as NaN's (numerical target) or None
|
| 940 |
+
(categorical target).
|
| 941 |
+
|
| 942 |
+
Notes
|
| 943 |
+
-----
|
| 944 |
+
The `"pandas"` and `"liac-arff"` parsers can lead to different data types
|
| 945 |
+
in the output. The notable differences are the following:
|
| 946 |
+
|
| 947 |
+
- The `"liac-arff"` parser always encodes categorical features as `str` objects.
|
| 948 |
+
To the contrary, the `"pandas"` parser instead infers the type while
|
| 949 |
+
reading and numerical categories will be casted into integers whenever
|
| 950 |
+
possible.
|
| 951 |
+
- The `"liac-arff"` parser uses float64 to encode numerical features
|
| 952 |
+
tagged as 'REAL' and 'NUMERICAL' in the metadata. The `"pandas"`
|
| 953 |
+
parser instead infers if these numerical features corresponds
|
| 954 |
+
to integers and uses panda's Integer extension dtype.
|
| 955 |
+
- In particular, classification datasets with integer categories are
|
| 956 |
+
typically loaded as such `(0, 1, ...)` with the `"pandas"` parser while
|
| 957 |
+
`"liac-arff"` will force the use of string encoded class labels such as
|
| 958 |
+
`"0"`, `"1"` and so on.
|
| 959 |
+
- The `"pandas"` parser will not strip single quotes - i.e. `'` - from
|
| 960 |
+
string columns. For instance, a string `'my string'` will be kept as is
|
| 961 |
+
while the `"liac-arff"` parser will strip the single quotes. For
|
| 962 |
+
categorical columns, the single quotes are stripped from the values.
|
| 963 |
+
|
| 964 |
+
In addition, when `as_frame=False` is used, the `"liac-arff"` parser
|
| 965 |
+
returns ordinally encoded data where the categories are provided in the
|
| 966 |
+
attribute `categories` of the `Bunch` instance. Instead, `"pandas"` returns
|
| 967 |
+
a NumPy array were the categories are not encoded.
|
| 968 |
+
|
| 969 |
+
Examples
|
| 970 |
+
--------
|
| 971 |
+
>>> from sklearn.datasets import fetch_openml
|
| 972 |
+
>>> adult = fetch_openml("adult", version=2) # doctest: +SKIP
|
| 973 |
+
>>> adult.frame.info() # doctest: +SKIP
|
| 974 |
+
<class 'pandas.core.frame.DataFrame'>
|
| 975 |
+
RangeIndex: 48842 entries, 0 to 48841
|
| 976 |
+
Data columns (total 15 columns):
|
| 977 |
+
# Column Non-Null Count Dtype
|
| 978 |
+
--- ------ -------------- -----
|
| 979 |
+
0 age 48842 non-null int64
|
| 980 |
+
1 workclass 46043 non-null category
|
| 981 |
+
2 fnlwgt 48842 non-null int64
|
| 982 |
+
3 education 48842 non-null category
|
| 983 |
+
4 education-num 48842 non-null int64
|
| 984 |
+
5 marital-status 48842 non-null category
|
| 985 |
+
6 occupation 46033 non-null category
|
| 986 |
+
7 relationship 48842 non-null category
|
| 987 |
+
8 race 48842 non-null category
|
| 988 |
+
9 sex 48842 non-null category
|
| 989 |
+
10 capital-gain 48842 non-null int64
|
| 990 |
+
11 capital-loss 48842 non-null int64
|
| 991 |
+
12 hours-per-week 48842 non-null int64
|
| 992 |
+
13 native-country 47985 non-null category
|
| 993 |
+
14 class 48842 non-null category
|
| 994 |
+
dtypes: category(9), int64(6)
|
| 995 |
+
memory usage: 2.7 MB
|
| 996 |
+
"""
|
| 997 |
+
if cache is False:
|
| 998 |
+
# no caching will be applied
|
| 999 |
+
data_home = None
|
| 1000 |
+
else:
|
| 1001 |
+
data_home = get_data_home(data_home=data_home)
|
| 1002 |
+
data_home = join(str(data_home), "openml")
|
| 1003 |
+
|
| 1004 |
+
# check valid function arguments. data_id XOR (name, version) should be
|
| 1005 |
+
# provided
|
| 1006 |
+
if name is not None:
|
| 1007 |
+
# OpenML is case-insensitive, but the caching mechanism is not
|
| 1008 |
+
# convert all data names (str) to lower case
|
| 1009 |
+
name = name.lower()
|
| 1010 |
+
if data_id is not None:
|
| 1011 |
+
raise ValueError(
|
| 1012 |
+
"Dataset data_id={} and name={} passed, but you can only "
|
| 1013 |
+
"specify a numeric data_id or a name, not "
|
| 1014 |
+
"both.".format(data_id, name)
|
| 1015 |
+
)
|
| 1016 |
+
data_info = _get_data_info_by_name(
|
| 1017 |
+
name, version, data_home, n_retries=n_retries, delay=delay
|
| 1018 |
+
)
|
| 1019 |
+
data_id = data_info["did"]
|
| 1020 |
+
elif data_id is not None:
|
| 1021 |
+
# from the previous if statement, it is given that name is None
|
| 1022 |
+
if version != "active":
|
| 1023 |
+
raise ValueError(
|
| 1024 |
+
"Dataset data_id={} and version={} passed, but you can only "
|
| 1025 |
+
"specify a numeric data_id or a version, not "
|
| 1026 |
+
"both.".format(data_id, version)
|
| 1027 |
+
)
|
| 1028 |
+
else:
|
| 1029 |
+
raise ValueError(
|
| 1030 |
+
"Neither name nor data_id are provided. Please provide name or data_id."
|
| 1031 |
+
)
|
| 1032 |
+
|
| 1033 |
+
data_description = _get_data_description_by_id(data_id, data_home)
|
| 1034 |
+
if data_description["status"] != "active":
|
| 1035 |
+
warn(
|
| 1036 |
+
"Version {} of dataset {} is inactive, meaning that issues have "
|
| 1037 |
+
"been found in the dataset. Try using a newer version from "
|
| 1038 |
+
"this URL: {}".format(
|
| 1039 |
+
data_description["version"],
|
| 1040 |
+
data_description["name"],
|
| 1041 |
+
data_description["url"],
|
| 1042 |
+
)
|
| 1043 |
+
)
|
| 1044 |
+
if "error" in data_description:
|
| 1045 |
+
warn(
|
| 1046 |
+
"OpenML registered a problem with the dataset. It might be "
|
| 1047 |
+
"unusable. Error: {}".format(data_description["error"])
|
| 1048 |
+
)
|
| 1049 |
+
if "warning" in data_description:
|
| 1050 |
+
warn(
|
| 1051 |
+
"OpenML raised a warning on the dataset. It might be "
|
| 1052 |
+
"unusable. Warning: {}".format(data_description["warning"])
|
| 1053 |
+
)
|
| 1054 |
+
|
| 1055 |
+
return_sparse = data_description["format"].lower() == "sparse_arff"
|
| 1056 |
+
as_frame = not return_sparse if as_frame == "auto" else as_frame
|
| 1057 |
+
if parser == "auto":
|
| 1058 |
+
parser_ = "liac-arff" if return_sparse else "pandas"
|
| 1059 |
+
else:
|
| 1060 |
+
parser_ = parser
|
| 1061 |
+
|
| 1062 |
+
if parser_ == "pandas":
|
| 1063 |
+
try:
|
| 1064 |
+
check_pandas_support("`fetch_openml`")
|
| 1065 |
+
except ImportError as exc:
|
| 1066 |
+
if as_frame:
|
| 1067 |
+
err_msg = (
|
| 1068 |
+
"Returning pandas objects requires pandas to be installed. "
|
| 1069 |
+
"Alternatively, explicitly set `as_frame=False` and "
|
| 1070 |
+
"`parser='liac-arff'`."
|
| 1071 |
+
)
|
| 1072 |
+
else:
|
| 1073 |
+
err_msg = (
|
| 1074 |
+
f"Using `parser={parser!r}` with dense data requires pandas to be "
|
| 1075 |
+
"installed. Alternatively, explicitly set `parser='liac-arff'`."
|
| 1076 |
+
)
|
| 1077 |
+
raise ImportError(err_msg) from exc
|
| 1078 |
+
|
| 1079 |
+
if return_sparse:
|
| 1080 |
+
if as_frame:
|
| 1081 |
+
raise ValueError(
|
| 1082 |
+
"Sparse ARFF datasets cannot be loaded with as_frame=True. "
|
| 1083 |
+
"Use as_frame=False or as_frame='auto' instead."
|
| 1084 |
+
)
|
| 1085 |
+
if parser_ == "pandas":
|
| 1086 |
+
raise ValueError(
|
| 1087 |
+
f"Sparse ARFF datasets cannot be loaded with parser={parser!r}. "
|
| 1088 |
+
"Use parser='liac-arff' or parser='auto' instead."
|
| 1089 |
+
)
|
| 1090 |
+
|
| 1091 |
+
# download data features, meta-info about column types
|
| 1092 |
+
features_list = _get_data_features(data_id, data_home)
|
| 1093 |
+
|
| 1094 |
+
if not as_frame:
|
| 1095 |
+
for feature in features_list:
|
| 1096 |
+
if "true" in (feature["is_ignore"], feature["is_row_identifier"]):
|
| 1097 |
+
continue
|
| 1098 |
+
if feature["data_type"] == "string":
|
| 1099 |
+
raise ValueError(
|
| 1100 |
+
"STRING attributes are not supported for "
|
| 1101 |
+
"array representation. Try as_frame=True"
|
| 1102 |
+
)
|
| 1103 |
+
|
| 1104 |
+
if target_column == "default-target":
|
| 1105 |
+
# determines the default target based on the data feature results
|
| 1106 |
+
# (which is currently more reliable than the data description;
|
| 1107 |
+
# see issue: https://github.com/openml/OpenML/issues/768)
|
| 1108 |
+
target_columns = [
|
| 1109 |
+
feature["name"]
|
| 1110 |
+
for feature in features_list
|
| 1111 |
+
if feature["is_target"] == "true"
|
| 1112 |
+
]
|
| 1113 |
+
elif isinstance(target_column, str):
|
| 1114 |
+
# for code-simplicity, make target_column by default a list
|
| 1115 |
+
target_columns = [target_column]
|
| 1116 |
+
elif target_column is None:
|
| 1117 |
+
target_columns = []
|
| 1118 |
+
else:
|
| 1119 |
+
# target_column already is of type list
|
| 1120 |
+
target_columns = target_column
|
| 1121 |
+
data_columns = _valid_data_column_names(features_list, target_columns)
|
| 1122 |
+
|
| 1123 |
+
shape: Optional[Tuple[int, int]]
|
| 1124 |
+
# determine arff encoding to return
|
| 1125 |
+
if not return_sparse:
|
| 1126 |
+
# The shape must include the ignored features to keep the right indexes
|
| 1127 |
+
# during the arff data conversion.
|
| 1128 |
+
data_qualities = _get_data_qualities(data_id, data_home)
|
| 1129 |
+
shape = _get_num_samples(data_qualities), len(features_list)
|
| 1130 |
+
else:
|
| 1131 |
+
shape = None
|
| 1132 |
+
|
| 1133 |
+
# obtain the data
|
| 1134 |
+
url = data_description["url"]
|
| 1135 |
+
bunch = _download_data_to_bunch(
|
| 1136 |
+
url,
|
| 1137 |
+
return_sparse,
|
| 1138 |
+
data_home,
|
| 1139 |
+
as_frame=bool(as_frame),
|
| 1140 |
+
openml_columns_info=features_list,
|
| 1141 |
+
shape=shape,
|
| 1142 |
+
target_columns=target_columns,
|
| 1143 |
+
data_columns=data_columns,
|
| 1144 |
+
md5_checksum=data_description["md5_checksum"],
|
| 1145 |
+
n_retries=n_retries,
|
| 1146 |
+
delay=delay,
|
| 1147 |
+
parser=parser_,
|
| 1148 |
+
read_csv_kwargs=read_csv_kwargs,
|
| 1149 |
+
)
|
| 1150 |
+
|
| 1151 |
+
if return_X_y:
|
| 1152 |
+
return bunch.data, bunch.target
|
| 1153 |
+
|
| 1154 |
+
description = "{}\n\nDownloaded from openml.org.".format(
|
| 1155 |
+
data_description.pop("description")
|
| 1156 |
+
)
|
| 1157 |
+
|
| 1158 |
+
bunch.update(
|
| 1159 |
+
DESCR=description,
|
| 1160 |
+
details=data_description,
|
| 1161 |
+
url="https://www.openml.org/d/{}".format(data_id),
|
| 1162 |
+
)
|
| 1163 |
+
|
| 1164 |
+
return bunch
|
miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/datasets/_rcv1.py
ADDED
|
@@ -0,0 +1,334 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
| 10 |
+
|
| 11 |
+
import logging
|
| 12 |
+
from gzip import GzipFile
|
| 13 |
+
from numbers import Integral, Real
|
| 14 |
+
from os import PathLike, makedirs, remove
|
| 15 |
+
from os.path import exists, join
|
| 16 |
+
|
| 17 |
+
import joblib
|
| 18 |
+
import numpy as np
|
| 19 |
+
import scipy.sparse as sp
|
| 20 |
+
|
| 21 |
+
from ..utils import Bunch
|
| 22 |
+
from ..utils import shuffle as shuffle_
|
| 23 |
+
from ..utils._param_validation import Interval, StrOptions, validate_params
|
| 24 |
+
from . import get_data_home
|
| 25 |
+
from ._base import RemoteFileMetadata, _fetch_remote, _pkl_filepath, load_descr
|
| 26 |
+
from ._svmlight_format_io import load_svmlight_files
|
| 27 |
+
|
| 28 |
+
# The original vectorized data can be found at:
|
| 29 |
+
# http://www.ai.mit.edu/projects/jmlr/papers/volume5/lewis04a/a13-vector-files/lyrl2004_vectors_test_pt0.dat.gz
|
| 30 |
+
# http://www.ai.mit.edu/projects/jmlr/papers/volume5/lewis04a/a13-vector-files/lyrl2004_vectors_test_pt1.dat.gz
|
| 31 |
+
# http://www.ai.mit.edu/projects/jmlr/papers/volume5/lewis04a/a13-vector-files/lyrl2004_vectors_test_pt2.dat.gz
|
| 32 |
+
# http://www.ai.mit.edu/projects/jmlr/papers/volume5/lewis04a/a13-vector-files/lyrl2004_vectors_test_pt3.dat.gz
|
| 33 |
+
# http://www.ai.mit.edu/projects/jmlr/papers/volume5/lewis04a/a13-vector-files/lyrl2004_vectors_train.dat.gz
|
| 34 |
+
# while the original stemmed token files can be found
|
| 35 |
+
# in the README, section B.12.i.:
|
| 36 |
+
# http://www.ai.mit.edu/projects/jmlr/papers/volume5/lewis04a/lyrl2004_rcv1v2_README.htm
|
| 37 |
+
XY_METADATA = (
|
| 38 |
+
RemoteFileMetadata(
|
| 39 |
+
url="https://ndownloader.figshare.com/files/5976069",
|
| 40 |
+
checksum="ed40f7e418d10484091b059703eeb95ae3199fe042891dcec4be6696b9968374",
|
| 41 |
+
filename="lyrl2004_vectors_test_pt0.dat.gz",
|
| 42 |
+
),
|
| 43 |
+
RemoteFileMetadata(
|
| 44 |
+
url="https://ndownloader.figshare.com/files/5976066",
|
| 45 |
+
checksum="87700668ae45d45d5ca1ef6ae9bd81ab0f5ec88cc95dcef9ae7838f727a13aa6",
|
| 46 |
+
filename="lyrl2004_vectors_test_pt1.dat.gz",
|
| 47 |
+
),
|
| 48 |
+
RemoteFileMetadata(
|
| 49 |
+
url="https://ndownloader.figshare.com/files/5976063",
|
| 50 |
+
checksum="48143ac703cbe33299f7ae9f4995db49a258690f60e5debbff8995c34841c7f5",
|
| 51 |
+
filename="lyrl2004_vectors_test_pt2.dat.gz",
|
| 52 |
+
),
|
| 53 |
+
RemoteFileMetadata(
|
| 54 |
+
url="https://ndownloader.figshare.com/files/5976060",
|
| 55 |
+
checksum="dfcb0d658311481523c6e6ca0c3f5a3e1d3d12cde5d7a8ce629a9006ec7dbb39",
|
| 56 |
+
filename="lyrl2004_vectors_test_pt3.dat.gz",
|
| 57 |
+
),
|
| 58 |
+
RemoteFileMetadata(
|
| 59 |
+
url="https://ndownloader.figshare.com/files/5976057",
|
| 60 |
+
checksum="5468f656d0ba7a83afc7ad44841cf9a53048a5c083eedc005dcdb5cc768924ae",
|
| 61 |
+
filename="lyrl2004_vectors_train.dat.gz",
|
| 62 |
+
),
|
| 63 |
+
)
|
| 64 |
+
|
| 65 |
+
# The original data can be found at:
|
| 66 |
+
# http://jmlr.csail.mit.edu/papers/volume5/lewis04a/a08-topic-qrels/rcv1-v2.topics.qrels.gz
|
| 67 |
+
TOPICS_METADATA = RemoteFileMetadata(
|
| 68 |
+
url="https://ndownloader.figshare.com/files/5976048",
|
| 69 |
+
checksum="2a98e5e5d8b770bded93afc8930d88299474317fe14181aee1466cc754d0d1c1",
|
| 70 |
+
filename="rcv1v2.topics.qrels.gz",
|
| 71 |
+
)
|
| 72 |
+
|
| 73 |
+
logger = logging.getLogger(__name__)
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
@validate_params(
|
| 77 |
+
{
|
| 78 |
+
"data_home": [str, PathLike, None],
|
| 79 |
+
"subset": [StrOptions({"train", "test", "all"})],
|
| 80 |
+
"download_if_missing": ["boolean"],
|
| 81 |
+
"random_state": ["random_state"],
|
| 82 |
+
"shuffle": ["boolean"],
|
| 83 |
+
"return_X_y": ["boolean"],
|
| 84 |
+
"n_retries": [Interval(Integral, 1, None, closed="left")],
|
| 85 |
+
"delay": [Interval(Real, 0.0, None, closed="neither")],
|
| 86 |
+
},
|
| 87 |
+
prefer_skip_nested_validation=True,
|
| 88 |
+
)
|
| 89 |
+
def fetch_rcv1(
|
| 90 |
+
*,
|
| 91 |
+
data_home=None,
|
| 92 |
+
subset="all",
|
| 93 |
+
download_if_missing=True,
|
| 94 |
+
random_state=None,
|
| 95 |
+
shuffle=False,
|
| 96 |
+
return_X_y=False,
|
| 97 |
+
n_retries=3,
|
| 98 |
+
delay=1.0,
|
| 99 |
+
):
|
| 100 |
+
"""Load the RCV1 multilabel dataset (classification).
|
| 101 |
+
|
| 102 |
+
Download it if necessary.
|
| 103 |
+
|
| 104 |
+
Version: RCV1-v2, vectors, full sets, topics multilabels.
|
| 105 |
+
|
| 106 |
+
================= =====================
|
| 107 |
+
Classes 103
|
| 108 |
+
Samples total 804414
|
| 109 |
+
Dimensionality 47236
|
| 110 |
+
Features real, between 0 and 1
|
| 111 |
+
================= =====================
|
| 112 |
+
|
| 113 |
+
Read more in the :ref:`User Guide <rcv1_dataset>`.
|
| 114 |
+
|
| 115 |
+
.. versionadded:: 0.17
|
| 116 |
+
|
| 117 |
+
Parameters
|
| 118 |
+
----------
|
| 119 |
+
data_home : str or path-like, default=None
|
| 120 |
+
Specify another download and cache folder for the datasets. By default
|
| 121 |
+
all scikit-learn data is stored in '~/scikit_learn_data' subfolders.
|
| 122 |
+
|
| 123 |
+
subset : {'train', 'test', 'all'}, default='all'
|
| 124 |
+
Select the dataset to load: 'train' for the training set
|
| 125 |
+
(23149 samples), 'test' for the test set (781265 samples),
|
| 126 |
+
'all' for both, with the training samples first if shuffle is False.
|
| 127 |
+
This follows the official LYRL2004 chronological split.
|
| 128 |
+
|
| 129 |
+
download_if_missing : bool, default=True
|
| 130 |
+
If False, raise an OSError if the data is not locally available
|
| 131 |
+
instead of trying to download the data from the source site.
|
| 132 |
+
|
| 133 |
+
random_state : int, RandomState instance or None, default=None
|
| 134 |
+
Determines random number generation for dataset shuffling. Pass an int
|
| 135 |
+
for reproducible output across multiple function calls.
|
| 136 |
+
See :term:`Glossary <random_state>`.
|
| 137 |
+
|
| 138 |
+
shuffle : bool, default=False
|
| 139 |
+
Whether to shuffle dataset.
|
| 140 |
+
|
| 141 |
+
return_X_y : bool, default=False
|
| 142 |
+
If True, returns ``(dataset.data, dataset.target)`` instead of a Bunch
|
| 143 |
+
object. See below for more information about the `dataset.data` and
|
| 144 |
+
`dataset.target` object.
|
| 145 |
+
|
| 146 |
+
.. versionadded:: 0.20
|
| 147 |
+
|
| 148 |
+
n_retries : int, default=3
|
| 149 |
+
Number of retries when HTTP errors are encountered.
|
| 150 |
+
|
| 151 |
+
.. versionadded:: 1.5
|
| 152 |
+
|
| 153 |
+
delay : float, default=1.0
|
| 154 |
+
Number of seconds between retries.
|
| 155 |
+
|
| 156 |
+
.. versionadded:: 1.5
|
| 157 |
+
|
| 158 |
+
Returns
|
| 159 |
+
-------
|
| 160 |
+
dataset : :class:`~sklearn.utils.Bunch`
|
| 161 |
+
Dictionary-like object. Returned only if `return_X_y` is False.
|
| 162 |
+
`dataset` has the following attributes:
|
| 163 |
+
|
| 164 |
+
- data : sparse matrix of shape (804414, 47236), dtype=np.float64
|
| 165 |
+
The array has 0.16% of non zero values. Will be of CSR format.
|
| 166 |
+
- target : sparse matrix of shape (804414, 103), dtype=np.uint8
|
| 167 |
+
Each sample has a value of 1 in its categories, and 0 in others.
|
| 168 |
+
The array has 3.15% of non zero values. Will be of CSR format.
|
| 169 |
+
- sample_id : ndarray of shape (804414,), dtype=np.uint32,
|
| 170 |
+
Identification number of each sample, as ordered in dataset.data.
|
| 171 |
+
- target_names : ndarray of shape (103,), dtype=object
|
| 172 |
+
Names of each target (RCV1 topics), as ordered in dataset.target.
|
| 173 |
+
- DESCR : str
|
| 174 |
+
Description of the RCV1 dataset.
|
| 175 |
+
|
| 176 |
+
(data, target) : tuple
|
| 177 |
+
A tuple consisting of `dataset.data` and `dataset.target`, as
|
| 178 |
+
described above. Returned only if `return_X_y` is True.
|
| 179 |
+
|
| 180 |
+
.. versionadded:: 0.20
|
| 181 |
+
|
| 182 |
+
Examples
|
| 183 |
+
--------
|
| 184 |
+
>>> from sklearn.datasets import fetch_rcv1
|
| 185 |
+
>>> rcv1 = fetch_rcv1()
|
| 186 |
+
>>> rcv1.data.shape
|
| 187 |
+
(804414, 47236)
|
| 188 |
+
>>> rcv1.target.shape
|
| 189 |
+
(804414, 103)
|
| 190 |
+
"""
|
| 191 |
+
N_SAMPLES = 804414
|
| 192 |
+
N_FEATURES = 47236
|
| 193 |
+
N_CATEGORIES = 103
|
| 194 |
+
N_TRAIN = 23149
|
| 195 |
+
|
| 196 |
+
data_home = get_data_home(data_home=data_home)
|
| 197 |
+
rcv1_dir = join(data_home, "RCV1")
|
| 198 |
+
if download_if_missing:
|
| 199 |
+
if not exists(rcv1_dir):
|
| 200 |
+
makedirs(rcv1_dir)
|
| 201 |
+
|
| 202 |
+
samples_path = _pkl_filepath(rcv1_dir, "samples.pkl")
|
| 203 |
+
sample_id_path = _pkl_filepath(rcv1_dir, "sample_id.pkl")
|
| 204 |
+
sample_topics_path = _pkl_filepath(rcv1_dir, "sample_topics.pkl")
|
| 205 |
+
topics_path = _pkl_filepath(rcv1_dir, "topics_names.pkl")
|
| 206 |
+
|
| 207 |
+
# load data (X) and sample_id
|
| 208 |
+
if download_if_missing and (not exists(samples_path) or not exists(sample_id_path)):
|
| 209 |
+
files = []
|
| 210 |
+
for each in XY_METADATA:
|
| 211 |
+
logger.info("Downloading %s" % each.url)
|
| 212 |
+
file_path = _fetch_remote(
|
| 213 |
+
each, dirname=rcv1_dir, n_retries=n_retries, delay=delay
|
| 214 |
+
)
|
| 215 |
+
files.append(GzipFile(filename=file_path))
|
| 216 |
+
|
| 217 |
+
Xy = load_svmlight_files(files, n_features=N_FEATURES)
|
| 218 |
+
|
| 219 |
+
# Training data is before testing data
|
| 220 |
+
X = sp.vstack([Xy[8], Xy[0], Xy[2], Xy[4], Xy[6]]).tocsr()
|
| 221 |
+
sample_id = np.hstack((Xy[9], Xy[1], Xy[3], Xy[5], Xy[7]))
|
| 222 |
+
sample_id = sample_id.astype(np.uint32, copy=False)
|
| 223 |
+
|
| 224 |
+
joblib.dump(X, samples_path, compress=9)
|
| 225 |
+
joblib.dump(sample_id, sample_id_path, compress=9)
|
| 226 |
+
|
| 227 |
+
# delete archives
|
| 228 |
+
for f in files:
|
| 229 |
+
f.close()
|
| 230 |
+
remove(f.name)
|
| 231 |
+
else:
|
| 232 |
+
X = joblib.load(samples_path)
|
| 233 |
+
sample_id = joblib.load(sample_id_path)
|
| 234 |
+
|
| 235 |
+
# load target (y), categories, and sample_id_bis
|
| 236 |
+
if download_if_missing and (
|
| 237 |
+
not exists(sample_topics_path) or not exists(topics_path)
|
| 238 |
+
):
|
| 239 |
+
logger.info("Downloading %s" % TOPICS_METADATA.url)
|
| 240 |
+
topics_archive_path = _fetch_remote(
|
| 241 |
+
TOPICS_METADATA, dirname=rcv1_dir, n_retries=n_retries, delay=delay
|
| 242 |
+
)
|
| 243 |
+
|
| 244 |
+
# parse the target file
|
| 245 |
+
n_cat = -1
|
| 246 |
+
n_doc = -1
|
| 247 |
+
doc_previous = -1
|
| 248 |
+
y = np.zeros((N_SAMPLES, N_CATEGORIES), dtype=np.uint8)
|
| 249 |
+
sample_id_bis = np.zeros(N_SAMPLES, dtype=np.int32)
|
| 250 |
+
category_names = {}
|
| 251 |
+
with GzipFile(filename=topics_archive_path, mode="rb") as f:
|
| 252 |
+
for line in f:
|
| 253 |
+
line_components = line.decode("ascii").split(" ")
|
| 254 |
+
if len(line_components) == 3:
|
| 255 |
+
cat, doc, _ = line_components
|
| 256 |
+
if cat not in category_names:
|
| 257 |
+
n_cat += 1
|
| 258 |
+
category_names[cat] = n_cat
|
| 259 |
+
|
| 260 |
+
doc = int(doc)
|
| 261 |
+
if doc != doc_previous:
|
| 262 |
+
doc_previous = doc
|
| 263 |
+
n_doc += 1
|
| 264 |
+
sample_id_bis[n_doc] = doc
|
| 265 |
+
y[n_doc, category_names[cat]] = 1
|
| 266 |
+
|
| 267 |
+
# delete archive
|
| 268 |
+
remove(topics_archive_path)
|
| 269 |
+
|
| 270 |
+
# Samples in X are ordered with sample_id,
|
| 271 |
+
# whereas in y, they are ordered with sample_id_bis.
|
| 272 |
+
permutation = _find_permutation(sample_id_bis, sample_id)
|
| 273 |
+
y = y[permutation, :]
|
| 274 |
+
|
| 275 |
+
# save category names in a list, with same order than y
|
| 276 |
+
categories = np.empty(N_CATEGORIES, dtype=object)
|
| 277 |
+
for k in category_names.keys():
|
| 278 |
+
categories[category_names[k]] = k
|
| 279 |
+
|
| 280 |
+
# reorder categories in lexicographic order
|
| 281 |
+
order = np.argsort(categories)
|
| 282 |
+
categories = categories[order]
|
| 283 |
+
y = sp.csr_matrix(y[:, order])
|
| 284 |
+
|
| 285 |
+
joblib.dump(y, sample_topics_path, compress=9)
|
| 286 |
+
joblib.dump(categories, topics_path, compress=9)
|
| 287 |
+
else:
|
| 288 |
+
y = joblib.load(sample_topics_path)
|
| 289 |
+
categories = joblib.load(topics_path)
|
| 290 |
+
|
| 291 |
+
if subset == "all":
|
| 292 |
+
pass
|
| 293 |
+
elif subset == "train":
|
| 294 |
+
X = X[:N_TRAIN, :]
|
| 295 |
+
y = y[:N_TRAIN, :]
|
| 296 |
+
sample_id = sample_id[:N_TRAIN]
|
| 297 |
+
elif subset == "test":
|
| 298 |
+
X = X[N_TRAIN:, :]
|
| 299 |
+
y = y[N_TRAIN:, :]
|
| 300 |
+
sample_id = sample_id[N_TRAIN:]
|
| 301 |
+
else:
|
| 302 |
+
raise ValueError(
|
| 303 |
+
"Unknown subset parameter. Got '%s' instead of one"
|
| 304 |
+
" of ('all', 'train', test')" % subset
|
| 305 |
+
)
|
| 306 |
+
|
| 307 |
+
if shuffle:
|
| 308 |
+
X, y, sample_id = shuffle_(X, y, sample_id, random_state=random_state)
|
| 309 |
+
|
| 310 |
+
fdescr = load_descr("rcv1.rst")
|
| 311 |
+
|
| 312 |
+
if return_X_y:
|
| 313 |
+
return X, y
|
| 314 |
+
|
| 315 |
+
return Bunch(
|
| 316 |
+
data=X, target=y, sample_id=sample_id, target_names=categories, DESCR=fdescr
|
| 317 |
+
)
|
| 318 |
+
|
| 319 |
+
|
| 320 |
+
def _inverse_permutation(p):
|
| 321 |
+
"""Inverse permutation p."""
|
| 322 |
+
n = p.size
|
| 323 |
+
s = np.zeros(n, dtype=np.int32)
|
| 324 |
+
i = np.arange(n, dtype=np.int32)
|
| 325 |
+
np.put(s, p, i) # s[p] = i
|
| 326 |
+
return s
|
| 327 |
+
|
| 328 |
+
|
| 329 |
+
def _find_permutation(a, b):
|
| 330 |
+
"""Find the permutation from a to b."""
|
| 331 |
+
t = np.argsort(a)
|
| 332 |
+
u = np.argsort(b)
|
| 333 |
+
u_ = _inverse_permutation(u)
|
| 334 |
+
return t[u_]
|
miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/datasets/_samples_generator.py
ADDED
|
@@ -0,0 +1,2383 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Generate samples of synthetic data sets.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
# Authors: The scikit-learn developers
|
| 6 |
+
# SPDX-License-Identifier: BSD-3-Clause
|
| 7 |
+
|
| 8 |
+
import array
|
| 9 |
+
import numbers
|
| 10 |
+
from collections.abc import Iterable
|
| 11 |
+
from numbers import Integral, Real
|
| 12 |
+
|
| 13 |
+
import numpy as np
|
| 14 |
+
import scipy.sparse as sp
|
| 15 |
+
from scipy import linalg
|
| 16 |
+
|
| 17 |
+
from sklearn.utils import Bunch
|
| 18 |
+
|
| 19 |
+
from ..preprocessing import MultiLabelBinarizer
|
| 20 |
+
from ..utils import check_array, check_random_state
|
| 21 |
+
from ..utils import shuffle as util_shuffle
|
| 22 |
+
from ..utils._param_validation import Interval, StrOptions, validate_params
|
| 23 |
+
from ..utils.random import sample_without_replacement
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def _generate_hypercube(samples, dimensions, rng):
|
| 27 |
+
"""Returns distinct binary samples of length dimensions."""
|
| 28 |
+
if dimensions > 30:
|
| 29 |
+
return np.hstack(
|
| 30 |
+
[
|
| 31 |
+
rng.randint(2, size=(samples, dimensions - 30)),
|
| 32 |
+
_generate_hypercube(samples, 30, rng),
|
| 33 |
+
]
|
| 34 |
+
)
|
| 35 |
+
out = sample_without_replacement(2**dimensions, samples, random_state=rng).astype(
|
| 36 |
+
dtype=">u4", copy=False
|
| 37 |
+
)
|
| 38 |
+
out = np.unpackbits(out.view(">u1")).reshape((-1, 32))[:, -dimensions:]
|
| 39 |
+
return out
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
@validate_params(
|
| 43 |
+
{
|
| 44 |
+
"n_samples": [Interval(Integral, 1, None, closed="left")],
|
| 45 |
+
"n_features": [Interval(Integral, 1, None, closed="left")],
|
| 46 |
+
"n_informative": [Interval(Integral, 1, None, closed="left")],
|
| 47 |
+
"n_redundant": [Interval(Integral, 0, None, closed="left")],
|
| 48 |
+
"n_repeated": [Interval(Integral, 0, None, closed="left")],
|
| 49 |
+
"n_classes": [Interval(Integral, 1, None, closed="left")],
|
| 50 |
+
"n_clusters_per_class": [Interval(Integral, 1, None, closed="left")],
|
| 51 |
+
"weights": ["array-like", None],
|
| 52 |
+
"flip_y": [Interval(Real, 0, 1, closed="both")],
|
| 53 |
+
"class_sep": [Interval(Real, 0, None, closed="neither")],
|
| 54 |
+
"hypercube": ["boolean"],
|
| 55 |
+
"shift": [Interval(Real, None, None, closed="neither"), "array-like", None],
|
| 56 |
+
"scale": [Interval(Real, 0, None, closed="neither"), "array-like", None],
|
| 57 |
+
"shuffle": ["boolean"],
|
| 58 |
+
"random_state": ["random_state"],
|
| 59 |
+
"return_X_y": ["boolean"],
|
| 60 |
+
},
|
| 61 |
+
prefer_skip_nested_validation=True,
|
| 62 |
+
)
|
| 63 |
+
def make_classification(
|
| 64 |
+
n_samples=100,
|
| 65 |
+
n_features=20,
|
| 66 |
+
*,
|
| 67 |
+
n_informative=2,
|
| 68 |
+
n_redundant=2,
|
| 69 |
+
n_repeated=0,
|
| 70 |
+
n_classes=2,
|
| 71 |
+
n_clusters_per_class=2,
|
| 72 |
+
weights=None,
|
| 73 |
+
flip_y=0.01,
|
| 74 |
+
class_sep=1.0,
|
| 75 |
+
hypercube=True,
|
| 76 |
+
shift=0.0,
|
| 77 |
+
scale=1.0,
|
| 78 |
+
shuffle=True,
|
| 79 |
+
random_state=None,
|
| 80 |
+
return_X_y=True,
|
| 81 |
+
):
|
| 82 |
+
"""Generate a random n-class classification problem.
|
| 83 |
+
|
| 84 |
+
This initially creates clusters of points normally distributed (std=1)
|
| 85 |
+
about vertices of an ``n_informative``-dimensional hypercube with sides of
|
| 86 |
+
length ``2*class_sep`` and assigns an equal number of clusters to each
|
| 87 |
+
class. It introduces interdependence between these features and adds
|
| 88 |
+
various types of further noise to the data.
|
| 89 |
+
|
| 90 |
+
Without shuffling, ``X`` horizontally stacks features in the following
|
| 91 |
+
order: the primary ``n_informative`` features, followed by ``n_redundant``
|
| 92 |
+
linear combinations of the informative features, followed by ``n_repeated``
|
| 93 |
+
duplicates, drawn randomly with replacement from the informative and
|
| 94 |
+
redundant features. The remaining features are filled with random noise.
|
| 95 |
+
Thus, without shuffling, all useful features are contained in the columns
|
| 96 |
+
``X[:, :n_informative + n_redundant + n_repeated]``.
|
| 97 |
+
|
| 98 |
+
Read more in the :ref:`User Guide <sample_generators>`.
|
| 99 |
+
|
| 100 |
+
Parameters
|
| 101 |
+
----------
|
| 102 |
+
n_samples : int, default=100
|
| 103 |
+
The number of samples.
|
| 104 |
+
|
| 105 |
+
n_features : int, default=20
|
| 106 |
+
The total number of features. These comprise ``n_informative``
|
| 107 |
+
informative features, ``n_redundant`` redundant features,
|
| 108 |
+
``n_repeated`` duplicated features and
|
| 109 |
+
``n_features-n_informative-n_redundant-n_repeated`` useless features
|
| 110 |
+
drawn at random.
|
| 111 |
+
|
| 112 |
+
n_informative : int, default=2
|
| 113 |
+
The number of informative features. Each class is composed of a number
|
| 114 |
+
of gaussian clusters each located around the vertices of a hypercube
|
| 115 |
+
in a subspace of dimension ``n_informative``. For each cluster,
|
| 116 |
+
informative features are drawn independently from N(0, 1) and then
|
| 117 |
+
randomly linearly combined within each cluster in order to add
|
| 118 |
+
covariance. The clusters are then placed on the vertices of the
|
| 119 |
+
hypercube.
|
| 120 |
+
|
| 121 |
+
n_redundant : int, default=2
|
| 122 |
+
The number of redundant features. These features are generated as
|
| 123 |
+
random linear combinations of the informative features.
|
| 124 |
+
|
| 125 |
+
n_repeated : int, default=0
|
| 126 |
+
The number of duplicated features, drawn randomly from the informative
|
| 127 |
+
and the redundant features.
|
| 128 |
+
|
| 129 |
+
n_classes : int, default=2
|
| 130 |
+
The number of classes (or labels) of the classification problem.
|
| 131 |
+
|
| 132 |
+
n_clusters_per_class : int, default=2
|
| 133 |
+
The number of clusters per class.
|
| 134 |
+
|
| 135 |
+
weights : array-like of shape (n_classes,) or (n_classes - 1,),\
|
| 136 |
+
default=None
|
| 137 |
+
The proportions of samples assigned to each class. If None, then
|
| 138 |
+
classes are balanced. Note that if ``len(weights) == n_classes - 1``,
|
| 139 |
+
then the last class weight is automatically inferred.
|
| 140 |
+
More than ``n_samples`` samples may be returned if the sum of
|
| 141 |
+
``weights`` exceeds 1. Note that the actual class proportions will
|
| 142 |
+
not exactly match ``weights`` when ``flip_y`` isn't 0.
|
| 143 |
+
|
| 144 |
+
flip_y : float, default=0.01
|
| 145 |
+
The fraction of samples whose class is assigned randomly. Larger
|
| 146 |
+
values introduce noise in the labels and make the classification
|
| 147 |
+
task harder. Note that the default setting flip_y > 0 might lead
|
| 148 |
+
to less than ``n_classes`` in y in some cases.
|
| 149 |
+
|
| 150 |
+
class_sep : float, default=1.0
|
| 151 |
+
The factor multiplying the hypercube size. Larger values spread
|
| 152 |
+
out the clusters/classes and make the classification task easier.
|
| 153 |
+
|
| 154 |
+
hypercube : bool, default=True
|
| 155 |
+
If True, the clusters are put on the vertices of a hypercube. If
|
| 156 |
+
False, the clusters are put on the vertices of a random polytope.
|
| 157 |
+
|
| 158 |
+
shift : float, ndarray of shape (n_features,) or None, default=0.0
|
| 159 |
+
Shift features by the specified value. If None, then features
|
| 160 |
+
are shifted by a random value drawn in [-class_sep, class_sep].
|
| 161 |
+
|
| 162 |
+
scale : float, ndarray of shape (n_features,) or None, default=1.0
|
| 163 |
+
Multiply features by the specified value. If None, then features
|
| 164 |
+
are scaled by a random value drawn in [1, 100]. Note that scaling
|
| 165 |
+
happens after shifting.
|
| 166 |
+
|
| 167 |
+
shuffle : bool, default=True
|
| 168 |
+
Shuffle the samples and the features.
|
| 169 |
+
|
| 170 |
+
random_state : int, RandomState instance or None, default=None
|
| 171 |
+
Determines random number generation for dataset creation. Pass an int
|
| 172 |
+
for reproducible output across multiple function calls.
|
| 173 |
+
See :term:`Glossary <random_state>`.
|
| 174 |
+
|
| 175 |
+
return_X_y : bool, default=True
|
| 176 |
+
If True, a tuple ``(X, y)`` instead of a Bunch object is returned.
|
| 177 |
+
|
| 178 |
+
.. versionadded:: 1.7
|
| 179 |
+
|
| 180 |
+
Returns
|
| 181 |
+
-------
|
| 182 |
+
data : :class:`~sklearn.utils.Bunch` if `return_X_y` is `False`.
|
| 183 |
+
Dictionary-like object, with the following attributes.
|
| 184 |
+
|
| 185 |
+
DESCR : str
|
| 186 |
+
A description of the function that generated the dataset.
|
| 187 |
+
parameter : dict
|
| 188 |
+
A dictionary that stores the values of the arguments passed to the
|
| 189 |
+
generator function.
|
| 190 |
+
feature_info : list of len(n_features)
|
| 191 |
+
A description for each generated feature.
|
| 192 |
+
X : ndarray of shape (n_samples, n_features)
|
| 193 |
+
The generated samples.
|
| 194 |
+
y : ndarray of shape (n_samples,)
|
| 195 |
+
An integer label for class membership of each sample.
|
| 196 |
+
|
| 197 |
+
.. versionadded:: 1.7
|
| 198 |
+
|
| 199 |
+
(X, y) : tuple if ``return_X_y`` is True
|
| 200 |
+
A tuple of generated samples and labels.
|
| 201 |
+
|
| 202 |
+
See Also
|
| 203 |
+
--------
|
| 204 |
+
make_blobs : Simplified variant.
|
| 205 |
+
make_multilabel_classification : Unrelated generator for multilabel tasks.
|
| 206 |
+
|
| 207 |
+
Notes
|
| 208 |
+
-----
|
| 209 |
+
The algorithm is adapted from Guyon [1] and was designed to generate
|
| 210 |
+
the "Madelon" dataset.
|
| 211 |
+
|
| 212 |
+
References
|
| 213 |
+
----------
|
| 214 |
+
.. [1] I. Guyon, "Design of experiments for the NIPS 2003 variable
|
| 215 |
+
selection benchmark", 2003.
|
| 216 |
+
|
| 217 |
+
Examples
|
| 218 |
+
--------
|
| 219 |
+
>>> from sklearn.datasets import make_classification
|
| 220 |
+
>>> X, y = make_classification(random_state=42)
|
| 221 |
+
>>> X.shape
|
| 222 |
+
(100, 20)
|
| 223 |
+
>>> y.shape
|
| 224 |
+
(100,)
|
| 225 |
+
>>> list(y[:5])
|
| 226 |
+
[np.int64(0), np.int64(0), np.int64(1), np.int64(1), np.int64(0)]
|
| 227 |
+
"""
|
| 228 |
+
generator = check_random_state(random_state)
|
| 229 |
+
|
| 230 |
+
# Count features, clusters and samples
|
| 231 |
+
if n_informative + n_redundant + n_repeated > n_features:
|
| 232 |
+
raise ValueError(
|
| 233 |
+
"Number of informative, redundant and repeated "
|
| 234 |
+
"features must sum to less than the number of total"
|
| 235 |
+
" features"
|
| 236 |
+
)
|
| 237 |
+
# Use log2 to avoid overflow errors
|
| 238 |
+
if n_informative < np.log2(n_classes * n_clusters_per_class):
|
| 239 |
+
msg = "n_classes({}) * n_clusters_per_class({}) must be"
|
| 240 |
+
msg += " smaller or equal 2**n_informative({})={}"
|
| 241 |
+
raise ValueError(
|
| 242 |
+
msg.format(n_classes, n_clusters_per_class, n_informative, 2**n_informative)
|
| 243 |
+
)
|
| 244 |
+
|
| 245 |
+
if weights is not None:
|
| 246 |
+
# we define new variable, weight_, instead of modifying user defined parameter.
|
| 247 |
+
if len(weights) not in [n_classes, n_classes - 1]:
|
| 248 |
+
raise ValueError(
|
| 249 |
+
"Weights specified but incompatible with number of classes."
|
| 250 |
+
)
|
| 251 |
+
if len(weights) == n_classes - 1:
|
| 252 |
+
if isinstance(weights, list):
|
| 253 |
+
weights_ = weights + [1.0 - sum(weights)]
|
| 254 |
+
else:
|
| 255 |
+
weights_ = np.resize(weights, n_classes)
|
| 256 |
+
weights_[-1] = 1.0 - sum(weights_[:-1])
|
| 257 |
+
else:
|
| 258 |
+
weights_ = weights.copy()
|
| 259 |
+
else:
|
| 260 |
+
weights_ = [1.0 / n_classes] * n_classes
|
| 261 |
+
|
| 262 |
+
n_random = n_features - n_informative - n_redundant - n_repeated
|
| 263 |
+
n_clusters = n_classes * n_clusters_per_class
|
| 264 |
+
|
| 265 |
+
# Distribute samples among clusters by weight
|
| 266 |
+
n_samples_per_cluster = [
|
| 267 |
+
int(n_samples * weights_[k % n_classes] / n_clusters_per_class)
|
| 268 |
+
for k in range(n_clusters)
|
| 269 |
+
]
|
| 270 |
+
|
| 271 |
+
for i in range(n_samples - sum(n_samples_per_cluster)):
|
| 272 |
+
n_samples_per_cluster[i % n_clusters] += 1
|
| 273 |
+
|
| 274 |
+
# Initialize X and y
|
| 275 |
+
X = np.zeros((n_samples, n_features))
|
| 276 |
+
y = np.zeros(n_samples, dtype=int)
|
| 277 |
+
|
| 278 |
+
# Build the polytope whose vertices become cluster centroids
|
| 279 |
+
centroids = _generate_hypercube(n_clusters, n_informative, generator).astype(
|
| 280 |
+
float, copy=False
|
| 281 |
+
)
|
| 282 |
+
centroids *= 2 * class_sep
|
| 283 |
+
centroids -= class_sep
|
| 284 |
+
if not hypercube:
|
| 285 |
+
centroids *= generator.uniform(size=(n_clusters, 1))
|
| 286 |
+
centroids *= generator.uniform(size=(1, n_informative))
|
| 287 |
+
|
| 288 |
+
# Initially draw informative features from the standard normal
|
| 289 |
+
X[:, :n_informative] = generator.standard_normal(size=(n_samples, n_informative))
|
| 290 |
+
|
| 291 |
+
# Create each cluster; a variant of make_blobs
|
| 292 |
+
stop = 0
|
| 293 |
+
for k, centroid in enumerate(centroids):
|
| 294 |
+
start, stop = stop, stop + n_samples_per_cluster[k]
|
| 295 |
+
y[start:stop] = k % n_classes # assign labels
|
| 296 |
+
X_k = X[start:stop, :n_informative] # slice a view of the cluster
|
| 297 |
+
|
| 298 |
+
A = 2 * generator.uniform(size=(n_informative, n_informative)) - 1
|
| 299 |
+
X_k[...] = np.dot(X_k, A) # introduce random covariance
|
| 300 |
+
|
| 301 |
+
X_k += centroid # shift the cluster to a vertex
|
| 302 |
+
|
| 303 |
+
# Create redundant features
|
| 304 |
+
if n_redundant > 0:
|
| 305 |
+
B = 2 * generator.uniform(size=(n_informative, n_redundant)) - 1
|
| 306 |
+
X[:, n_informative : n_informative + n_redundant] = np.dot(
|
| 307 |
+
X[:, :n_informative], B
|
| 308 |
+
)
|
| 309 |
+
|
| 310 |
+
# Repeat some features
|
| 311 |
+
n = n_informative + n_redundant
|
| 312 |
+
if n_repeated > 0:
|
| 313 |
+
indices = ((n - 1) * generator.uniform(size=n_repeated) + 0.5).astype(np.intp)
|
| 314 |
+
X[:, n : n + n_repeated] = X[:, indices]
|
| 315 |
+
|
| 316 |
+
# Fill useless features
|
| 317 |
+
if n_random > 0:
|
| 318 |
+
X[:, -n_random:] = generator.standard_normal(size=(n_samples, n_random))
|
| 319 |
+
|
| 320 |
+
# Randomly replace labels
|
| 321 |
+
if flip_y >= 0.0:
|
| 322 |
+
flip_mask = generator.uniform(size=n_samples) < flip_y
|
| 323 |
+
y[flip_mask] = generator.randint(n_classes, size=flip_mask.sum())
|
| 324 |
+
|
| 325 |
+
# Randomly shift and scale
|
| 326 |
+
if shift is None:
|
| 327 |
+
shift = (2 * generator.uniform(size=n_features) - 1) * class_sep
|
| 328 |
+
X += shift
|
| 329 |
+
|
| 330 |
+
if scale is None:
|
| 331 |
+
scale = 1 + 100 * generator.uniform(size=n_features)
|
| 332 |
+
X *= scale
|
| 333 |
+
|
| 334 |
+
indices = np.arange(n_features)
|
| 335 |
+
if shuffle:
|
| 336 |
+
# Randomly permute samples
|
| 337 |
+
X, y = util_shuffle(X, y, random_state=generator)
|
| 338 |
+
|
| 339 |
+
# Randomly permute features
|
| 340 |
+
generator.shuffle(indices)
|
| 341 |
+
X[:, :] = X[:, indices]
|
| 342 |
+
|
| 343 |
+
if return_X_y:
|
| 344 |
+
return X, y
|
| 345 |
+
|
| 346 |
+
# feat_desc describes features in X
|
| 347 |
+
feat_desc = ["random"] * n_features
|
| 348 |
+
for i, index in enumerate(indices):
|
| 349 |
+
if index < n_informative:
|
| 350 |
+
feat_desc[i] = "informative"
|
| 351 |
+
elif n_informative <= index < n_informative + n_redundant:
|
| 352 |
+
feat_desc[i] = "redundant"
|
| 353 |
+
elif n <= index < n + n_repeated:
|
| 354 |
+
feat_desc[i] = "repeated"
|
| 355 |
+
|
| 356 |
+
parameters = {
|
| 357 |
+
"n_samples": n_samples,
|
| 358 |
+
"n_features": n_features,
|
| 359 |
+
"n_informative": n_informative,
|
| 360 |
+
"n_redundant": n_redundant,
|
| 361 |
+
"n_repeated": n_repeated,
|
| 362 |
+
"n_classes": n_classes,
|
| 363 |
+
"n_clusters_per_class": n_clusters_per_class,
|
| 364 |
+
"weights": weights,
|
| 365 |
+
"flip_y": flip_y,
|
| 366 |
+
"class_sep": class_sep,
|
| 367 |
+
"hypercube": hypercube,
|
| 368 |
+
"shift": shift,
|
| 369 |
+
"scale": scale,
|
| 370 |
+
"shuffle": shuffle,
|
| 371 |
+
"random_state": random_state,
|
| 372 |
+
"return_X_y": return_X_y,
|
| 373 |
+
}
|
| 374 |
+
|
| 375 |
+
bunch = Bunch(
|
| 376 |
+
DESCR=make_classification.__doc__,
|
| 377 |
+
parameters=parameters,
|
| 378 |
+
feature_info=feat_desc,
|
| 379 |
+
X=X,
|
| 380 |
+
y=y,
|
| 381 |
+
)
|
| 382 |
+
|
| 383 |
+
return bunch
|
| 384 |
+
|
| 385 |
+
|
| 386 |
+
@validate_params(
|
| 387 |
+
{
|
| 388 |
+
"n_samples": [Interval(Integral, 1, None, closed="left")],
|
| 389 |
+
"n_features": [Interval(Integral, 1, None, closed="left")],
|
| 390 |
+
"n_classes": [Interval(Integral, 1, None, closed="left")],
|
| 391 |
+
"n_labels": [Interval(Integral, 0, None, closed="left")],
|
| 392 |
+
"length": [Interval(Integral, 1, None, closed="left")],
|
| 393 |
+
"allow_unlabeled": ["boolean"],
|
| 394 |
+
"sparse": ["boolean"],
|
| 395 |
+
"return_indicator": [StrOptions({"dense", "sparse"}), "boolean"],
|
| 396 |
+
"return_distributions": ["boolean"],
|
| 397 |
+
"random_state": ["random_state"],
|
| 398 |
+
},
|
| 399 |
+
prefer_skip_nested_validation=True,
|
| 400 |
+
)
|
| 401 |
+
def make_multilabel_classification(
|
| 402 |
+
n_samples=100,
|
| 403 |
+
n_features=20,
|
| 404 |
+
*,
|
| 405 |
+
n_classes=5,
|
| 406 |
+
n_labels=2,
|
| 407 |
+
length=50,
|
| 408 |
+
allow_unlabeled=True,
|
| 409 |
+
sparse=False,
|
| 410 |
+
return_indicator="dense",
|
| 411 |
+
return_distributions=False,
|
| 412 |
+
random_state=None,
|
| 413 |
+
):
|
| 414 |
+
"""Generate a random multilabel classification problem.
|
| 415 |
+
|
| 416 |
+
For each sample, the generative process is:
|
| 417 |
+
- pick the number of labels: n ~ Poisson(n_labels)
|
| 418 |
+
- n times, choose a class c: c ~ Multinomial(theta)
|
| 419 |
+
- pick the document length: k ~ Poisson(length)
|
| 420 |
+
- k times, choose a word: w ~ Multinomial(theta_c)
|
| 421 |
+
|
| 422 |
+
In the above process, rejection sampling is used to make sure that
|
| 423 |
+
n is never zero or more than `n_classes`, and that the document length
|
| 424 |
+
is never zero. Likewise, we reject classes which have already been chosen.
|
| 425 |
+
|
| 426 |
+
For an example of usage, see
|
| 427 |
+
:ref:`sphx_glr_auto_examples_datasets_plot_random_multilabel_dataset.py`.
|
| 428 |
+
|
| 429 |
+
Read more in the :ref:`User Guide <sample_generators>`.
|
| 430 |
+
|
| 431 |
+
Parameters
|
| 432 |
+
----------
|
| 433 |
+
n_samples : int, default=100
|
| 434 |
+
The number of samples.
|
| 435 |
+
|
| 436 |
+
n_features : int, default=20
|
| 437 |
+
The total number of features.
|
| 438 |
+
|
| 439 |
+
n_classes : int, default=5
|
| 440 |
+
The number of classes of the classification problem.
|
| 441 |
+
|
| 442 |
+
n_labels : int, default=2
|
| 443 |
+
The average number of labels per instance. More precisely, the number
|
| 444 |
+
of labels per sample is drawn from a Poisson distribution with
|
| 445 |
+
``n_labels`` as its expected value, but samples are bounded (using
|
| 446 |
+
rejection sampling) by ``n_classes``, and must be nonzero if
|
| 447 |
+
``allow_unlabeled`` is False.
|
| 448 |
+
|
| 449 |
+
length : int, default=50
|
| 450 |
+
The sum of the features (number of words if documents) is drawn from
|
| 451 |
+
a Poisson distribution with this expected value.
|
| 452 |
+
|
| 453 |
+
allow_unlabeled : bool, default=True
|
| 454 |
+
If ``True``, some instances might not belong to any class.
|
| 455 |
+
|
| 456 |
+
sparse : bool, default=False
|
| 457 |
+
If ``True``, return a sparse feature matrix.
|
| 458 |
+
|
| 459 |
+
.. versionadded:: 0.17
|
| 460 |
+
parameter to allow *sparse* output.
|
| 461 |
+
|
| 462 |
+
return_indicator : {'dense', 'sparse'} or False, default='dense'
|
| 463 |
+
If ``'dense'`` return ``Y`` in the dense binary indicator format. If
|
| 464 |
+
``'sparse'`` return ``Y`` in the sparse binary indicator format.
|
| 465 |
+
``False`` returns a list of lists of labels.
|
| 466 |
+
|
| 467 |
+
return_distributions : bool, default=False
|
| 468 |
+
If ``True``, return the prior class probability and conditional
|
| 469 |
+
probabilities of features given classes, from which the data was
|
| 470 |
+
drawn.
|
| 471 |
+
|
| 472 |
+
random_state : int, RandomState instance or None, default=None
|
| 473 |
+
Determines random number generation for dataset creation. Pass an int
|
| 474 |
+
for reproducible output across multiple function calls.
|
| 475 |
+
See :term:`Glossary <random_state>`.
|
| 476 |
+
|
| 477 |
+
Returns
|
| 478 |
+
-------
|
| 479 |
+
X : ndarray of shape (n_samples, n_features)
|
| 480 |
+
The generated samples.
|
| 481 |
+
|
| 482 |
+
Y : {ndarray, sparse matrix} of shape (n_samples, n_classes)
|
| 483 |
+
The label sets. Sparse matrix should be of CSR format.
|
| 484 |
+
|
| 485 |
+
p_c : ndarray of shape (n_classes,)
|
| 486 |
+
The probability of each class being drawn. Only returned if
|
| 487 |
+
``return_distributions=True``.
|
| 488 |
+
|
| 489 |
+
p_w_c : ndarray of shape (n_features, n_classes)
|
| 490 |
+
The probability of each feature being drawn given each class.
|
| 491 |
+
Only returned if ``return_distributions=True``.
|
| 492 |
+
|
| 493 |
+
Examples
|
| 494 |
+
--------
|
| 495 |
+
>>> from sklearn.datasets import make_multilabel_classification
|
| 496 |
+
>>> X, y = make_multilabel_classification(n_labels=3, random_state=42)
|
| 497 |
+
>>> X.shape
|
| 498 |
+
(100, 20)
|
| 499 |
+
>>> y.shape
|
| 500 |
+
(100, 5)
|
| 501 |
+
>>> list(y[:3])
|
| 502 |
+
[array([1, 1, 0, 1, 0]), array([0, 1, 1, 1, 0]), array([0, 1, 0, 0, 0])]
|
| 503 |
+
"""
|
| 504 |
+
|
| 505 |
+
generator = check_random_state(random_state)
|
| 506 |
+
p_c = generator.uniform(size=n_classes)
|
| 507 |
+
p_c /= p_c.sum()
|
| 508 |
+
cumulative_p_c = np.cumsum(p_c)
|
| 509 |
+
p_w_c = generator.uniform(size=(n_features, n_classes))
|
| 510 |
+
p_w_c /= np.sum(p_w_c, axis=0)
|
| 511 |
+
|
| 512 |
+
def sample_example():
|
| 513 |
+
_, n_classes = p_w_c.shape
|
| 514 |
+
|
| 515 |
+
# pick a nonzero number of labels per document by rejection sampling
|
| 516 |
+
y_size = n_classes + 1
|
| 517 |
+
while (not allow_unlabeled and y_size == 0) or y_size > n_classes:
|
| 518 |
+
y_size = generator.poisson(n_labels)
|
| 519 |
+
|
| 520 |
+
# pick n classes
|
| 521 |
+
y = set()
|
| 522 |
+
while len(y) != y_size:
|
| 523 |
+
# pick a class with probability P(c)
|
| 524 |
+
c = np.searchsorted(cumulative_p_c, generator.uniform(size=y_size - len(y)))
|
| 525 |
+
y.update(c)
|
| 526 |
+
y = list(y)
|
| 527 |
+
|
| 528 |
+
# pick a non-zero document length by rejection sampling
|
| 529 |
+
n_words = 0
|
| 530 |
+
while n_words == 0:
|
| 531 |
+
n_words = generator.poisson(length)
|
| 532 |
+
|
| 533 |
+
# generate a document of length n_words
|
| 534 |
+
if len(y) == 0:
|
| 535 |
+
# if sample does not belong to any class, generate noise word
|
| 536 |
+
words = generator.randint(n_features, size=n_words)
|
| 537 |
+
return words, y
|
| 538 |
+
|
| 539 |
+
# sample words with replacement from selected classes
|
| 540 |
+
cumulative_p_w_sample = p_w_c.take(y, axis=1).sum(axis=1).cumsum()
|
| 541 |
+
cumulative_p_w_sample /= cumulative_p_w_sample[-1]
|
| 542 |
+
words = np.searchsorted(cumulative_p_w_sample, generator.uniform(size=n_words))
|
| 543 |
+
return words, y
|
| 544 |
+
|
| 545 |
+
X_indices = array.array("i")
|
| 546 |
+
X_indptr = array.array("i", [0])
|
| 547 |
+
Y = []
|
| 548 |
+
for i in range(n_samples):
|
| 549 |
+
words, y = sample_example()
|
| 550 |
+
X_indices.extend(words)
|
| 551 |
+
X_indptr.append(len(X_indices))
|
| 552 |
+
Y.append(y)
|
| 553 |
+
X_data = np.ones(len(X_indices), dtype=np.float64)
|
| 554 |
+
X = sp.csr_matrix((X_data, X_indices, X_indptr), shape=(n_samples, n_features))
|
| 555 |
+
X.sum_duplicates()
|
| 556 |
+
if not sparse:
|
| 557 |
+
X = X.toarray()
|
| 558 |
+
|
| 559 |
+
# return_indicator can be True due to backward compatibility
|
| 560 |
+
if return_indicator in (True, "sparse", "dense"):
|
| 561 |
+
lb = MultiLabelBinarizer(sparse_output=(return_indicator == "sparse"))
|
| 562 |
+
Y = lb.fit([range(n_classes)]).transform(Y)
|
| 563 |
+
if return_distributions:
|
| 564 |
+
return X, Y, p_c, p_w_c
|
| 565 |
+
return X, Y
|
| 566 |
+
|
| 567 |
+
|
| 568 |
+
@validate_params(
|
| 569 |
+
{
|
| 570 |
+
"n_samples": [Interval(Integral, 1, None, closed="left")],
|
| 571 |
+
"random_state": ["random_state"],
|
| 572 |
+
},
|
| 573 |
+
prefer_skip_nested_validation=True,
|
| 574 |
+
)
|
| 575 |
+
def make_hastie_10_2(n_samples=12000, *, random_state=None):
|
| 576 |
+
"""Generate data for binary classification used in Hastie et al. 2009, Example 10.2.
|
| 577 |
+
|
| 578 |
+
The ten features are standard independent Gaussian and
|
| 579 |
+
the target ``y`` is defined by::
|
| 580 |
+
|
| 581 |
+
y[i] = 1 if np.sum(X[i] ** 2) > 9.34 else -1
|
| 582 |
+
|
| 583 |
+
Read more in the :ref:`User Guide <sample_generators>`.
|
| 584 |
+
|
| 585 |
+
Parameters
|
| 586 |
+
----------
|
| 587 |
+
n_samples : int, default=12000
|
| 588 |
+
The number of samples.
|
| 589 |
+
|
| 590 |
+
random_state : int, RandomState instance or None, default=None
|
| 591 |
+
Determines random number generation for dataset creation. Pass an int
|
| 592 |
+
for reproducible output across multiple function calls.
|
| 593 |
+
See :term:`Glossary <random_state>`.
|
| 594 |
+
|
| 595 |
+
Returns
|
| 596 |
+
-------
|
| 597 |
+
X : ndarray of shape (n_samples, 10)
|
| 598 |
+
The input samples.
|
| 599 |
+
|
| 600 |
+
y : ndarray of shape (n_samples,)
|
| 601 |
+
The output values.
|
| 602 |
+
|
| 603 |
+
See Also
|
| 604 |
+
--------
|
| 605 |
+
make_gaussian_quantiles : A generalization of this dataset approach.
|
| 606 |
+
|
| 607 |
+
References
|
| 608 |
+
----------
|
| 609 |
+
.. [1] T. Hastie, R. Tibshirani and J. Friedman, "Elements of Statistical
|
| 610 |
+
Learning Ed. 2", Springer, 2009.
|
| 611 |
+
|
| 612 |
+
Examples
|
| 613 |
+
--------
|
| 614 |
+
>>> from sklearn.datasets import make_hastie_10_2
|
| 615 |
+
>>> X, y = make_hastie_10_2(n_samples=24000, random_state=42)
|
| 616 |
+
>>> X.shape
|
| 617 |
+
(24000, 10)
|
| 618 |
+
>>> y.shape
|
| 619 |
+
(24000,)
|
| 620 |
+
>>> list(y[:5])
|
| 621 |
+
[np.float64(-1.0), np.float64(1.0), np.float64(-1.0), np.float64(1.0),
|
| 622 |
+
np.float64(-1.0)]
|
| 623 |
+
"""
|
| 624 |
+
rs = check_random_state(random_state)
|
| 625 |
+
|
| 626 |
+
shape = (n_samples, 10)
|
| 627 |
+
X = rs.normal(size=shape).reshape(shape)
|
| 628 |
+
y = ((X**2.0).sum(axis=1) > 9.34).astype(np.float64, copy=False)
|
| 629 |
+
y[y == 0.0] = -1.0
|
| 630 |
+
|
| 631 |
+
return X, y
|
| 632 |
+
|
| 633 |
+
|
| 634 |
+
@validate_params(
|
| 635 |
+
{
|
| 636 |
+
"n_samples": [Interval(Integral, 1, None, closed="left")],
|
| 637 |
+
"n_features": [Interval(Integral, 1, None, closed="left")],
|
| 638 |
+
"n_informative": [Interval(Integral, 0, None, closed="left")],
|
| 639 |
+
"n_targets": [Interval(Integral, 1, None, closed="left")],
|
| 640 |
+
"bias": [Interval(Real, None, None, closed="neither")],
|
| 641 |
+
"effective_rank": [Interval(Integral, 1, None, closed="left"), None],
|
| 642 |
+
"tail_strength": [Interval(Real, 0, 1, closed="both")],
|
| 643 |
+
"noise": [Interval(Real, 0, None, closed="left")],
|
| 644 |
+
"shuffle": ["boolean"],
|
| 645 |
+
"coef": ["boolean"],
|
| 646 |
+
"random_state": ["random_state"],
|
| 647 |
+
},
|
| 648 |
+
prefer_skip_nested_validation=True,
|
| 649 |
+
)
|
| 650 |
+
def make_regression(
|
| 651 |
+
n_samples=100,
|
| 652 |
+
n_features=100,
|
| 653 |
+
*,
|
| 654 |
+
n_informative=10,
|
| 655 |
+
n_targets=1,
|
| 656 |
+
bias=0.0,
|
| 657 |
+
effective_rank=None,
|
| 658 |
+
tail_strength=0.5,
|
| 659 |
+
noise=0.0,
|
| 660 |
+
shuffle=True,
|
| 661 |
+
coef=False,
|
| 662 |
+
random_state=None,
|
| 663 |
+
):
|
| 664 |
+
"""Generate a random regression problem.
|
| 665 |
+
|
| 666 |
+
The input set can either be well conditioned (by default) or have a low
|
| 667 |
+
rank-fat tail singular profile. See :func:`make_low_rank_matrix` for
|
| 668 |
+
more details.
|
| 669 |
+
|
| 670 |
+
The output is generated by applying a (potentially biased) random linear
|
| 671 |
+
regression model with `n_informative` nonzero regressors to the previously
|
| 672 |
+
generated input and some gaussian centered noise with some adjustable
|
| 673 |
+
scale.
|
| 674 |
+
|
| 675 |
+
Read more in the :ref:`User Guide <sample_generators>`.
|
| 676 |
+
|
| 677 |
+
Parameters
|
| 678 |
+
----------
|
| 679 |
+
n_samples : int, default=100
|
| 680 |
+
The number of samples.
|
| 681 |
+
|
| 682 |
+
n_features : int, default=100
|
| 683 |
+
The number of features.
|
| 684 |
+
|
| 685 |
+
n_informative : int, default=10
|
| 686 |
+
The number of informative features, i.e., the number of features used
|
| 687 |
+
to build the linear model used to generate the output.
|
| 688 |
+
|
| 689 |
+
n_targets : int, default=1
|
| 690 |
+
The number of regression targets, i.e., the dimension of the y output
|
| 691 |
+
vector associated with a sample. By default, the output is a scalar.
|
| 692 |
+
|
| 693 |
+
bias : float, default=0.0
|
| 694 |
+
The bias term in the underlying linear model.
|
| 695 |
+
|
| 696 |
+
effective_rank : int, default=None
|
| 697 |
+
If not None:
|
| 698 |
+
The approximate number of singular vectors required to explain most
|
| 699 |
+
of the input data by linear combinations. Using this kind of
|
| 700 |
+
singular spectrum in the input allows the generator to reproduce
|
| 701 |
+
the correlations often observed in practice.
|
| 702 |
+
If None:
|
| 703 |
+
The input set is well conditioned, centered and gaussian with
|
| 704 |
+
unit variance.
|
| 705 |
+
|
| 706 |
+
tail_strength : float, default=0.5
|
| 707 |
+
The relative importance of the fat noisy tail of the singular values
|
| 708 |
+
profile if `effective_rank` is not None. When a float, it should be
|
| 709 |
+
between 0 and 1.
|
| 710 |
+
|
| 711 |
+
noise : float, default=0.0
|
| 712 |
+
The standard deviation of the gaussian noise applied to the output.
|
| 713 |
+
|
| 714 |
+
shuffle : bool, default=True
|
| 715 |
+
Shuffle the samples and the features.
|
| 716 |
+
|
| 717 |
+
coef : bool, default=False
|
| 718 |
+
If True, the coefficients of the underlying linear model are returned.
|
| 719 |
+
|
| 720 |
+
random_state : int, RandomState instance or None, default=None
|
| 721 |
+
Determines random number generation for dataset creation. Pass an int
|
| 722 |
+
for reproducible output across multiple function calls.
|
| 723 |
+
See :term:`Glossary <random_state>`.
|
| 724 |
+
|
| 725 |
+
Returns
|
| 726 |
+
-------
|
| 727 |
+
X : ndarray of shape (n_samples, n_features)
|
| 728 |
+
The input samples.
|
| 729 |
+
|
| 730 |
+
y : ndarray of shape (n_samples,) or (n_samples, n_targets)
|
| 731 |
+
The output values.
|
| 732 |
+
|
| 733 |
+
coef : ndarray of shape (n_features,) or (n_features, n_targets)
|
| 734 |
+
The coefficient of the underlying linear model. It is returned only if
|
| 735 |
+
coef is True.
|
| 736 |
+
|
| 737 |
+
Examples
|
| 738 |
+
--------
|
| 739 |
+
>>> from sklearn.datasets import make_regression
|
| 740 |
+
>>> X, y = make_regression(n_samples=5, n_features=2, noise=1, random_state=42)
|
| 741 |
+
>>> X
|
| 742 |
+
array([[ 0.4967, -0.1382 ],
|
| 743 |
+
[ 0.6476, 1.523],
|
| 744 |
+
[-0.2341, -0.2341],
|
| 745 |
+
[-0.4694, 0.5425],
|
| 746 |
+
[ 1.579, 0.7674]])
|
| 747 |
+
>>> y
|
| 748 |
+
array([ 6.737, 37.79, -10.27, 0.4017, 42.22])
|
| 749 |
+
"""
|
| 750 |
+
n_informative = min(n_features, n_informative)
|
| 751 |
+
generator = check_random_state(random_state)
|
| 752 |
+
|
| 753 |
+
if effective_rank is None:
|
| 754 |
+
# Randomly generate a well conditioned input set
|
| 755 |
+
X = generator.standard_normal(size=(n_samples, n_features))
|
| 756 |
+
|
| 757 |
+
else:
|
| 758 |
+
# Randomly generate a low rank, fat tail input set
|
| 759 |
+
X = make_low_rank_matrix(
|
| 760 |
+
n_samples=n_samples,
|
| 761 |
+
n_features=n_features,
|
| 762 |
+
effective_rank=effective_rank,
|
| 763 |
+
tail_strength=tail_strength,
|
| 764 |
+
random_state=generator,
|
| 765 |
+
)
|
| 766 |
+
|
| 767 |
+
# Generate a ground truth model with only n_informative features being non
|
| 768 |
+
# zeros (the other features are not correlated to y and should be ignored
|
| 769 |
+
# by a sparsifying regularizers such as L1 or elastic net)
|
| 770 |
+
ground_truth = np.zeros((n_features, n_targets))
|
| 771 |
+
ground_truth[:n_informative, :] = 100 * generator.uniform(
|
| 772 |
+
size=(n_informative, n_targets)
|
| 773 |
+
)
|
| 774 |
+
|
| 775 |
+
y = np.dot(X, ground_truth) + bias
|
| 776 |
+
|
| 777 |
+
# Add noise
|
| 778 |
+
if noise > 0.0:
|
| 779 |
+
y += generator.normal(scale=noise, size=y.shape)
|
| 780 |
+
|
| 781 |
+
# Randomly permute samples and features
|
| 782 |
+
if shuffle:
|
| 783 |
+
X, y = util_shuffle(X, y, random_state=generator)
|
| 784 |
+
|
| 785 |
+
indices = np.arange(n_features)
|
| 786 |
+
generator.shuffle(indices)
|
| 787 |
+
X[:, :] = X[:, indices]
|
| 788 |
+
ground_truth = ground_truth[indices]
|
| 789 |
+
|
| 790 |
+
y = np.squeeze(y)
|
| 791 |
+
|
| 792 |
+
if coef:
|
| 793 |
+
return X, y, np.squeeze(ground_truth)
|
| 794 |
+
|
| 795 |
+
else:
|
| 796 |
+
return X, y
|
| 797 |
+
|
| 798 |
+
|
| 799 |
+
@validate_params(
|
| 800 |
+
{
|
| 801 |
+
"n_samples": [Interval(Integral, 0, None, closed="left"), tuple],
|
| 802 |
+
"shuffle": ["boolean"],
|
| 803 |
+
"noise": [Interval(Real, 0, None, closed="left"), None],
|
| 804 |
+
"random_state": ["random_state"],
|
| 805 |
+
"factor": [Interval(Real, 0, 1, closed="left")],
|
| 806 |
+
},
|
| 807 |
+
prefer_skip_nested_validation=True,
|
| 808 |
+
)
|
| 809 |
+
def make_circles(
|
| 810 |
+
n_samples=100, *, shuffle=True, noise=None, random_state=None, factor=0.8
|
| 811 |
+
):
|
| 812 |
+
"""Make a large circle containing a smaller circle in 2d.
|
| 813 |
+
|
| 814 |
+
A simple toy dataset to visualize clustering and classification
|
| 815 |
+
algorithms.
|
| 816 |
+
|
| 817 |
+
Read more in the :ref:`User Guide <sample_generators>`.
|
| 818 |
+
|
| 819 |
+
Parameters
|
| 820 |
+
----------
|
| 821 |
+
n_samples : int or tuple of shape (2,), dtype=int, default=100
|
| 822 |
+
If int, it is the total number of points generated.
|
| 823 |
+
For odd numbers, the inner circle will have one point more than the
|
| 824 |
+
outer circle.
|
| 825 |
+
If two-element tuple, number of points in outer circle and inner
|
| 826 |
+
circle.
|
| 827 |
+
|
| 828 |
+
.. versionchanged:: 0.23
|
| 829 |
+
Added two-element tuple.
|
| 830 |
+
|
| 831 |
+
shuffle : bool, default=True
|
| 832 |
+
Whether to shuffle the samples.
|
| 833 |
+
|
| 834 |
+
noise : float, default=None
|
| 835 |
+
Standard deviation of Gaussian noise added to the data.
|
| 836 |
+
|
| 837 |
+
random_state : int, RandomState instance or None, default=None
|
| 838 |
+
Determines random number generation for dataset shuffling and noise.
|
| 839 |
+
Pass an int for reproducible output across multiple function calls.
|
| 840 |
+
See :term:`Glossary <random_state>`.
|
| 841 |
+
|
| 842 |
+
factor : float, default=.8
|
| 843 |
+
Scale factor between inner and outer circle in the range `[0, 1)`.
|
| 844 |
+
|
| 845 |
+
Returns
|
| 846 |
+
-------
|
| 847 |
+
X : ndarray of shape (n_samples, 2)
|
| 848 |
+
The generated samples.
|
| 849 |
+
|
| 850 |
+
y : ndarray of shape (n_samples,)
|
| 851 |
+
The integer labels (0 or 1) for class membership of each sample.
|
| 852 |
+
|
| 853 |
+
Examples
|
| 854 |
+
--------
|
| 855 |
+
>>> from sklearn.datasets import make_circles
|
| 856 |
+
>>> X, y = make_circles(random_state=42)
|
| 857 |
+
>>> X.shape
|
| 858 |
+
(100, 2)
|
| 859 |
+
>>> y.shape
|
| 860 |
+
(100,)
|
| 861 |
+
>>> list(y[:5])
|
| 862 |
+
[np.int64(1), np.int64(1), np.int64(1), np.int64(0), np.int64(0)]
|
| 863 |
+
"""
|
| 864 |
+
if isinstance(n_samples, numbers.Integral):
|
| 865 |
+
n_samples_out = n_samples // 2
|
| 866 |
+
n_samples_in = n_samples - n_samples_out
|
| 867 |
+
else: # n_samples is a tuple
|
| 868 |
+
if len(n_samples) != 2:
|
| 869 |
+
raise ValueError("When a tuple, n_samples must have exactly two elements.")
|
| 870 |
+
n_samples_out, n_samples_in = n_samples
|
| 871 |
+
|
| 872 |
+
generator = check_random_state(random_state)
|
| 873 |
+
# so as not to have the first point = last point, we set endpoint=False
|
| 874 |
+
linspace_out = np.linspace(0, 2 * np.pi, n_samples_out, endpoint=False)
|
| 875 |
+
linspace_in = np.linspace(0, 2 * np.pi, n_samples_in, endpoint=False)
|
| 876 |
+
outer_circ_x = np.cos(linspace_out)
|
| 877 |
+
outer_circ_y = np.sin(linspace_out)
|
| 878 |
+
inner_circ_x = np.cos(linspace_in) * factor
|
| 879 |
+
inner_circ_y = np.sin(linspace_in) * factor
|
| 880 |
+
|
| 881 |
+
X = np.vstack(
|
| 882 |
+
[np.append(outer_circ_x, inner_circ_x), np.append(outer_circ_y, inner_circ_y)]
|
| 883 |
+
).T
|
| 884 |
+
y = np.hstack(
|
| 885 |
+
[np.zeros(n_samples_out, dtype=np.intp), np.ones(n_samples_in, dtype=np.intp)]
|
| 886 |
+
)
|
| 887 |
+
if shuffle:
|
| 888 |
+
X, y = util_shuffle(X, y, random_state=generator)
|
| 889 |
+
|
| 890 |
+
if noise is not None:
|
| 891 |
+
X += generator.normal(scale=noise, size=X.shape)
|
| 892 |
+
|
| 893 |
+
return X, y
|
| 894 |
+
|
| 895 |
+
|
| 896 |
+
@validate_params(
|
| 897 |
+
{
|
| 898 |
+
"n_samples": [Interval(Integral, 1, None, closed="left"), tuple],
|
| 899 |
+
"shuffle": ["boolean"],
|
| 900 |
+
"noise": [Interval(Real, 0, None, closed="left"), None],
|
| 901 |
+
"random_state": ["random_state"],
|
| 902 |
+
},
|
| 903 |
+
prefer_skip_nested_validation=True,
|
| 904 |
+
)
|
| 905 |
+
def make_moons(n_samples=100, *, shuffle=True, noise=None, random_state=None):
|
| 906 |
+
"""Make two interleaving half circles.
|
| 907 |
+
|
| 908 |
+
A simple toy dataset to visualize clustering and classification
|
| 909 |
+
algorithms. Read more in the :ref:`User Guide <sample_generators>`.
|
| 910 |
+
|
| 911 |
+
Parameters
|
| 912 |
+
----------
|
| 913 |
+
n_samples : int or tuple of shape (2,), dtype=int, default=100
|
| 914 |
+
If int, the total number of points generated.
|
| 915 |
+
If two-element tuple, number of points in each of two moons.
|
| 916 |
+
|
| 917 |
+
.. versionchanged:: 0.23
|
| 918 |
+
Added two-element tuple.
|
| 919 |
+
|
| 920 |
+
shuffle : bool, default=True
|
| 921 |
+
Whether to shuffle the samples.
|
| 922 |
+
|
| 923 |
+
noise : float, default=None
|
| 924 |
+
Standard deviation of Gaussian noise added to the data.
|
| 925 |
+
|
| 926 |
+
random_state : int, RandomState instance or None, default=None
|
| 927 |
+
Determines random number generation for dataset shuffling and noise.
|
| 928 |
+
Pass an int for reproducible output across multiple function calls.
|
| 929 |
+
See :term:`Glossary <random_state>`.
|
| 930 |
+
|
| 931 |
+
Returns
|
| 932 |
+
-------
|
| 933 |
+
X : ndarray of shape (n_samples, 2)
|
| 934 |
+
The generated samples.
|
| 935 |
+
|
| 936 |
+
y : ndarray of shape (n_samples,)
|
| 937 |
+
The integer labels (0 or 1) for class membership of each sample.
|
| 938 |
+
|
| 939 |
+
Examples
|
| 940 |
+
--------
|
| 941 |
+
>>> from sklearn.datasets import make_moons
|
| 942 |
+
>>> X, y = make_moons(n_samples=200, noise=0.2, random_state=42)
|
| 943 |
+
>>> X.shape
|
| 944 |
+
(200, 2)
|
| 945 |
+
>>> y.shape
|
| 946 |
+
(200,)
|
| 947 |
+
"""
|
| 948 |
+
|
| 949 |
+
if isinstance(n_samples, numbers.Integral):
|
| 950 |
+
n_samples_out = n_samples // 2
|
| 951 |
+
n_samples_in = n_samples - n_samples_out
|
| 952 |
+
else:
|
| 953 |
+
try:
|
| 954 |
+
n_samples_out, n_samples_in = n_samples
|
| 955 |
+
except ValueError as e:
|
| 956 |
+
raise ValueError(
|
| 957 |
+
"`n_samples` can be either an int or a two-element tuple."
|
| 958 |
+
) from e
|
| 959 |
+
|
| 960 |
+
generator = check_random_state(random_state)
|
| 961 |
+
|
| 962 |
+
outer_circ_x = np.cos(np.linspace(0, np.pi, n_samples_out))
|
| 963 |
+
outer_circ_y = np.sin(np.linspace(0, np.pi, n_samples_out))
|
| 964 |
+
inner_circ_x = 1 - np.cos(np.linspace(0, np.pi, n_samples_in))
|
| 965 |
+
inner_circ_y = 1 - np.sin(np.linspace(0, np.pi, n_samples_in)) - 0.5
|
| 966 |
+
|
| 967 |
+
X = np.vstack(
|
| 968 |
+
[np.append(outer_circ_x, inner_circ_x), np.append(outer_circ_y, inner_circ_y)]
|
| 969 |
+
).T
|
| 970 |
+
y = np.hstack(
|
| 971 |
+
[np.zeros(n_samples_out, dtype=np.intp), np.ones(n_samples_in, dtype=np.intp)]
|
| 972 |
+
)
|
| 973 |
+
|
| 974 |
+
if shuffle:
|
| 975 |
+
X, y = util_shuffle(X, y, random_state=generator)
|
| 976 |
+
|
| 977 |
+
if noise is not None:
|
| 978 |
+
X += generator.normal(scale=noise, size=X.shape)
|
| 979 |
+
|
| 980 |
+
return X, y
|
| 981 |
+
|
| 982 |
+
|
| 983 |
+
@validate_params(
|
| 984 |
+
{
|
| 985 |
+
"n_samples": [Interval(Integral, 1, None, closed="left"), "array-like"],
|
| 986 |
+
"n_features": [Interval(Integral, 1, None, closed="left")],
|
| 987 |
+
"centers": [Interval(Integral, 1, None, closed="left"), "array-like", None],
|
| 988 |
+
"cluster_std": [Interval(Real, 0, None, closed="left"), "array-like"],
|
| 989 |
+
"center_box": [tuple],
|
| 990 |
+
"shuffle": ["boolean"],
|
| 991 |
+
"random_state": ["random_state"],
|
| 992 |
+
"return_centers": ["boolean"],
|
| 993 |
+
},
|
| 994 |
+
prefer_skip_nested_validation=True,
|
| 995 |
+
)
|
| 996 |
+
def make_blobs(
|
| 997 |
+
n_samples=100,
|
| 998 |
+
n_features=2,
|
| 999 |
+
*,
|
| 1000 |
+
centers=None,
|
| 1001 |
+
cluster_std=1.0,
|
| 1002 |
+
center_box=(-10.0, 10.0),
|
| 1003 |
+
shuffle=True,
|
| 1004 |
+
random_state=None,
|
| 1005 |
+
return_centers=False,
|
| 1006 |
+
):
|
| 1007 |
+
"""Generate isotropic Gaussian blobs for clustering.
|
| 1008 |
+
|
| 1009 |
+
Read more in the :ref:`User Guide <sample_generators>`.
|
| 1010 |
+
|
| 1011 |
+
Parameters
|
| 1012 |
+
----------
|
| 1013 |
+
n_samples : int or array-like, default=100
|
| 1014 |
+
If int, it is the total number of points equally divided among
|
| 1015 |
+
clusters.
|
| 1016 |
+
If array-like, each element of the sequence indicates
|
| 1017 |
+
the number of samples per cluster.
|
| 1018 |
+
|
| 1019 |
+
.. versionchanged:: v0.20
|
| 1020 |
+
one can now pass an array-like to the ``n_samples`` parameter
|
| 1021 |
+
|
| 1022 |
+
n_features : int, default=2
|
| 1023 |
+
The number of features for each sample.
|
| 1024 |
+
|
| 1025 |
+
centers : int or array-like of shape (n_centers, n_features), default=None
|
| 1026 |
+
The number of centers to generate, or the fixed center locations.
|
| 1027 |
+
If n_samples is an int and centers is None, 3 centers are generated.
|
| 1028 |
+
If n_samples is array-like, centers must be
|
| 1029 |
+
either None or an array of length equal to the length of n_samples.
|
| 1030 |
+
|
| 1031 |
+
cluster_std : float or array-like of float, default=1.0
|
| 1032 |
+
The standard deviation of the clusters.
|
| 1033 |
+
|
| 1034 |
+
center_box : tuple of float (min, max), default=(-10.0, 10.0)
|
| 1035 |
+
The bounding box for each cluster center when centers are
|
| 1036 |
+
generated at random.
|
| 1037 |
+
|
| 1038 |
+
shuffle : bool, default=True
|
| 1039 |
+
Shuffle the samples.
|
| 1040 |
+
|
| 1041 |
+
random_state : int, RandomState instance or None, default=None
|
| 1042 |
+
Determines random number generation for dataset creation. Pass an int
|
| 1043 |
+
for reproducible output across multiple function calls.
|
| 1044 |
+
See :term:`Glossary <random_state>`.
|
| 1045 |
+
|
| 1046 |
+
return_centers : bool, default=False
|
| 1047 |
+
If True, then return the centers of each cluster.
|
| 1048 |
+
|
| 1049 |
+
.. versionadded:: 0.23
|
| 1050 |
+
|
| 1051 |
+
Returns
|
| 1052 |
+
-------
|
| 1053 |
+
X : ndarray of shape (n_samples, n_features)
|
| 1054 |
+
The generated samples.
|
| 1055 |
+
|
| 1056 |
+
y : ndarray of shape (n_samples,)
|
| 1057 |
+
The integer labels for cluster membership of each sample.
|
| 1058 |
+
|
| 1059 |
+
centers : ndarray of shape (n_centers, n_features)
|
| 1060 |
+
The centers of each cluster. Only returned if
|
| 1061 |
+
``return_centers=True``.
|
| 1062 |
+
|
| 1063 |
+
See Also
|
| 1064 |
+
--------
|
| 1065 |
+
make_classification : A more intricate variant.
|
| 1066 |
+
|
| 1067 |
+
Examples
|
| 1068 |
+
--------
|
| 1069 |
+
>>> from sklearn.datasets import make_blobs
|
| 1070 |
+
>>> X, y = make_blobs(n_samples=10, centers=3, n_features=2,
|
| 1071 |
+
... random_state=0)
|
| 1072 |
+
>>> print(X.shape)
|
| 1073 |
+
(10, 2)
|
| 1074 |
+
>>> y
|
| 1075 |
+
array([0, 0, 1, 0, 2, 2, 2, 1, 1, 0])
|
| 1076 |
+
>>> X, y = make_blobs(n_samples=[3, 3, 4], centers=None, n_features=2,
|
| 1077 |
+
... random_state=0)
|
| 1078 |
+
>>> print(X.shape)
|
| 1079 |
+
(10, 2)
|
| 1080 |
+
>>> y
|
| 1081 |
+
array([0, 1, 2, 0, 2, 2, 2, 1, 1, 0])
|
| 1082 |
+
"""
|
| 1083 |
+
generator = check_random_state(random_state)
|
| 1084 |
+
|
| 1085 |
+
if isinstance(n_samples, numbers.Integral):
|
| 1086 |
+
# Set n_centers by looking at centers arg
|
| 1087 |
+
if centers is None:
|
| 1088 |
+
centers = 3
|
| 1089 |
+
|
| 1090 |
+
if isinstance(centers, numbers.Integral):
|
| 1091 |
+
n_centers = centers
|
| 1092 |
+
centers = generator.uniform(
|
| 1093 |
+
center_box[0], center_box[1], size=(n_centers, n_features)
|
| 1094 |
+
)
|
| 1095 |
+
|
| 1096 |
+
else:
|
| 1097 |
+
centers = check_array(centers)
|
| 1098 |
+
n_features = centers.shape[1]
|
| 1099 |
+
n_centers = centers.shape[0]
|
| 1100 |
+
|
| 1101 |
+
else:
|
| 1102 |
+
# Set n_centers by looking at [n_samples] arg
|
| 1103 |
+
n_centers = len(n_samples)
|
| 1104 |
+
if centers is None:
|
| 1105 |
+
centers = generator.uniform(
|
| 1106 |
+
center_box[0], center_box[1], size=(n_centers, n_features)
|
| 1107 |
+
)
|
| 1108 |
+
if not isinstance(centers, Iterable):
|
| 1109 |
+
raise ValueError(
|
| 1110 |
+
"Parameter `centers` must be array-like. Got {!r} instead".format(
|
| 1111 |
+
centers
|
| 1112 |
+
)
|
| 1113 |
+
)
|
| 1114 |
+
if len(centers) != n_centers:
|
| 1115 |
+
raise ValueError(
|
| 1116 |
+
"Length of `n_samples` not consistent with number of "
|
| 1117 |
+
f"centers. Got n_samples = {n_samples} and centers = {centers}"
|
| 1118 |
+
)
|
| 1119 |
+
centers = check_array(centers)
|
| 1120 |
+
n_features = centers.shape[1]
|
| 1121 |
+
|
| 1122 |
+
# stds: if cluster_std is given as list, it must be consistent
|
| 1123 |
+
# with the n_centers
|
| 1124 |
+
if hasattr(cluster_std, "__len__") and len(cluster_std) != n_centers:
|
| 1125 |
+
raise ValueError(
|
| 1126 |
+
"Length of `clusters_std` not consistent with "
|
| 1127 |
+
"number of centers. Got centers = {} "
|
| 1128 |
+
"and cluster_std = {}".format(centers, cluster_std)
|
| 1129 |
+
)
|
| 1130 |
+
|
| 1131 |
+
if isinstance(cluster_std, numbers.Real):
|
| 1132 |
+
cluster_std = np.full(len(centers), cluster_std)
|
| 1133 |
+
|
| 1134 |
+
if isinstance(n_samples, Iterable):
|
| 1135 |
+
n_samples_per_center = n_samples
|
| 1136 |
+
else:
|
| 1137 |
+
n_samples_per_center = [int(n_samples // n_centers)] * n_centers
|
| 1138 |
+
|
| 1139 |
+
for i in range(n_samples % n_centers):
|
| 1140 |
+
n_samples_per_center[i] += 1
|
| 1141 |
+
|
| 1142 |
+
cum_sum_n_samples = np.cumsum(n_samples_per_center)
|
| 1143 |
+
X = np.empty(shape=(sum(n_samples_per_center), n_features), dtype=np.float64)
|
| 1144 |
+
y = np.empty(shape=(sum(n_samples_per_center),), dtype=int)
|
| 1145 |
+
|
| 1146 |
+
for i, (n, std) in enumerate(zip(n_samples_per_center, cluster_std)):
|
| 1147 |
+
start_idx = cum_sum_n_samples[i - 1] if i > 0 else 0
|
| 1148 |
+
end_idx = cum_sum_n_samples[i]
|
| 1149 |
+
X[start_idx:end_idx] = generator.normal(
|
| 1150 |
+
loc=centers[i], scale=std, size=(n, n_features)
|
| 1151 |
+
)
|
| 1152 |
+
y[start_idx:end_idx] = i
|
| 1153 |
+
|
| 1154 |
+
if shuffle:
|
| 1155 |
+
X, y = util_shuffle(X, y, random_state=generator)
|
| 1156 |
+
|
| 1157 |
+
if return_centers:
|
| 1158 |
+
return X, y, centers
|
| 1159 |
+
else:
|
| 1160 |
+
return X, y
|
| 1161 |
+
|
| 1162 |
+
|
| 1163 |
+
@validate_params(
|
| 1164 |
+
{
|
| 1165 |
+
"n_samples": [Interval(Integral, 1, None, closed="left")],
|
| 1166 |
+
"n_features": [Interval(Integral, 5, None, closed="left")],
|
| 1167 |
+
"noise": [Interval(Real, 0.0, None, closed="left")],
|
| 1168 |
+
"random_state": ["random_state"],
|
| 1169 |
+
},
|
| 1170 |
+
prefer_skip_nested_validation=True,
|
| 1171 |
+
)
|
| 1172 |
+
def make_friedman1(n_samples=100, n_features=10, *, noise=0.0, random_state=None):
|
| 1173 |
+
"""Generate the "Friedman #1" regression problem.
|
| 1174 |
+
|
| 1175 |
+
This dataset is described in Friedman [1] and Breiman [2].
|
| 1176 |
+
|
| 1177 |
+
Inputs `X` are independent features uniformly distributed on the interval
|
| 1178 |
+
[0, 1]. The output `y` is created according to the formula::
|
| 1179 |
+
|
| 1180 |
+
y(X) = 10 * sin(pi * X[:, 0] * X[:, 1]) + 20 * (X[:, 2] - 0.5) ** 2 \
|
| 1181 |
+
+ 10 * X[:, 3] + 5 * X[:, 4] + noise * N(0, 1).
|
| 1182 |
+
|
| 1183 |
+
Out of the `n_features` features, only 5 are actually used to compute
|
| 1184 |
+
`y`. The remaining features are independent of `y`.
|
| 1185 |
+
|
| 1186 |
+
The number of features has to be >= 5.
|
| 1187 |
+
|
| 1188 |
+
Read more in the :ref:`User Guide <sample_generators>`.
|
| 1189 |
+
|
| 1190 |
+
Parameters
|
| 1191 |
+
----------
|
| 1192 |
+
n_samples : int, default=100
|
| 1193 |
+
The number of samples.
|
| 1194 |
+
|
| 1195 |
+
n_features : int, default=10
|
| 1196 |
+
The number of features. Should be at least 5.
|
| 1197 |
+
|
| 1198 |
+
noise : float, default=0.0
|
| 1199 |
+
The standard deviation of the gaussian noise applied to the output.
|
| 1200 |
+
|
| 1201 |
+
random_state : int, RandomState instance or None, default=None
|
| 1202 |
+
Determines random number generation for dataset noise. Pass an int
|
| 1203 |
+
for reproducible output across multiple function calls.
|
| 1204 |
+
See :term:`Glossary <random_state>`.
|
| 1205 |
+
|
| 1206 |
+
Returns
|
| 1207 |
+
-------
|
| 1208 |
+
X : ndarray of shape (n_samples, n_features)
|
| 1209 |
+
The input samples.
|
| 1210 |
+
|
| 1211 |
+
y : ndarray of shape (n_samples,)
|
| 1212 |
+
The output values.
|
| 1213 |
+
|
| 1214 |
+
References
|
| 1215 |
+
----------
|
| 1216 |
+
.. [1] J. Friedman, "Multivariate adaptive regression splines", The Annals
|
| 1217 |
+
of Statistics 19 (1), pages 1-67, 1991.
|
| 1218 |
+
|
| 1219 |
+
.. [2] L. Breiman, "Bagging predictors", Machine Learning 24,
|
| 1220 |
+
pages 123-140, 1996.
|
| 1221 |
+
|
| 1222 |
+
Examples
|
| 1223 |
+
--------
|
| 1224 |
+
>>> from sklearn.datasets import make_friedman1
|
| 1225 |
+
>>> X, y = make_friedman1(random_state=42)
|
| 1226 |
+
>>> X.shape
|
| 1227 |
+
(100, 10)
|
| 1228 |
+
>>> y.shape
|
| 1229 |
+
(100,)
|
| 1230 |
+
>>> list(y[:3])
|
| 1231 |
+
[np.float64(16.8), np.float64(5.87), np.float64(9.46)]
|
| 1232 |
+
"""
|
| 1233 |
+
generator = check_random_state(random_state)
|
| 1234 |
+
|
| 1235 |
+
X = generator.uniform(size=(n_samples, n_features))
|
| 1236 |
+
y = (
|
| 1237 |
+
10 * np.sin(np.pi * X[:, 0] * X[:, 1])
|
| 1238 |
+
+ 20 * (X[:, 2] - 0.5) ** 2
|
| 1239 |
+
+ 10 * X[:, 3]
|
| 1240 |
+
+ 5 * X[:, 4]
|
| 1241 |
+
+ noise * generator.standard_normal(size=(n_samples))
|
| 1242 |
+
)
|
| 1243 |
+
|
| 1244 |
+
return X, y
|
| 1245 |
+
|
| 1246 |
+
|
| 1247 |
+
@validate_params(
|
| 1248 |
+
{
|
| 1249 |
+
"n_samples": [Interval(Integral, 1, None, closed="left")],
|
| 1250 |
+
"noise": [Interval(Real, 0, None, closed="left")],
|
| 1251 |
+
"random_state": ["random_state"],
|
| 1252 |
+
},
|
| 1253 |
+
prefer_skip_nested_validation=True,
|
| 1254 |
+
)
|
| 1255 |
+
def make_friedman2(n_samples=100, *, noise=0.0, random_state=None):
|
| 1256 |
+
"""Generate the "Friedman #2" regression problem.
|
| 1257 |
+
|
| 1258 |
+
This dataset is described in Friedman [1] and Breiman [2].
|
| 1259 |
+
|
| 1260 |
+
Inputs `X` are 4 independent features uniformly distributed on the
|
| 1261 |
+
intervals::
|
| 1262 |
+
|
| 1263 |
+
0 <= X[:, 0] <= 100,
|
| 1264 |
+
40 * pi <= X[:, 1] <= 560 * pi,
|
| 1265 |
+
0 <= X[:, 2] <= 1,
|
| 1266 |
+
1 <= X[:, 3] <= 11.
|
| 1267 |
+
|
| 1268 |
+
The output `y` is created according to the formula::
|
| 1269 |
+
|
| 1270 |
+
y(X) = (X[:, 0] ** 2 + (X[:, 1] * X[:, 2] \
|
| 1271 |
+
- 1 / (X[:, 1] * X[:, 3])) ** 2) ** 0.5 + noise * N(0, 1).
|
| 1272 |
+
|
| 1273 |
+
Read more in the :ref:`User Guide <sample_generators>`.
|
| 1274 |
+
|
| 1275 |
+
Parameters
|
| 1276 |
+
----------
|
| 1277 |
+
n_samples : int, default=100
|
| 1278 |
+
The number of samples.
|
| 1279 |
+
|
| 1280 |
+
noise : float, default=0.0
|
| 1281 |
+
The standard deviation of the gaussian noise applied to the output.
|
| 1282 |
+
|
| 1283 |
+
random_state : int, RandomState instance or None, default=None
|
| 1284 |
+
Determines random number generation for dataset noise. Pass an int
|
| 1285 |
+
for reproducible output across multiple function calls.
|
| 1286 |
+
See :term:`Glossary <random_state>`.
|
| 1287 |
+
|
| 1288 |
+
Returns
|
| 1289 |
+
-------
|
| 1290 |
+
X : ndarray of shape (n_samples, 4)
|
| 1291 |
+
The input samples.
|
| 1292 |
+
|
| 1293 |
+
y : ndarray of shape (n_samples,)
|
| 1294 |
+
The output values.
|
| 1295 |
+
|
| 1296 |
+
References
|
| 1297 |
+
----------
|
| 1298 |
+
.. [1] J. Friedman, "Multivariate adaptive regression splines", The Annals
|
| 1299 |
+
of Statistics 19 (1), pages 1-67, 1991.
|
| 1300 |
+
|
| 1301 |
+
.. [2] L. Breiman, "Bagging predictors", Machine Learning 24,
|
| 1302 |
+
pages 123-140, 1996.
|
| 1303 |
+
|
| 1304 |
+
Examples
|
| 1305 |
+
--------
|
| 1306 |
+
>>> from sklearn.datasets import make_friedman2
|
| 1307 |
+
>>> X, y = make_friedman2(random_state=42)
|
| 1308 |
+
>>> X.shape
|
| 1309 |
+
(100, 4)
|
| 1310 |
+
>>> y.shape
|
| 1311 |
+
(100,)
|
| 1312 |
+
>>> list(y[:3])
|
| 1313 |
+
[np.float64(1229.4), np.float64(27.0), np.float64(65.6)]
|
| 1314 |
+
"""
|
| 1315 |
+
generator = check_random_state(random_state)
|
| 1316 |
+
|
| 1317 |
+
X = generator.uniform(size=(n_samples, 4))
|
| 1318 |
+
X[:, 0] *= 100
|
| 1319 |
+
X[:, 1] *= 520 * np.pi
|
| 1320 |
+
X[:, 1] += 40 * np.pi
|
| 1321 |
+
X[:, 3] *= 10
|
| 1322 |
+
X[:, 3] += 1
|
| 1323 |
+
|
| 1324 |
+
y = (
|
| 1325 |
+
X[:, 0] ** 2 + (X[:, 1] * X[:, 2] - 1 / (X[:, 1] * X[:, 3])) ** 2
|
| 1326 |
+
) ** 0.5 + noise * generator.standard_normal(size=(n_samples))
|
| 1327 |
+
|
| 1328 |
+
return X, y
|
| 1329 |
+
|
| 1330 |
+
|
| 1331 |
+
@validate_params(
|
| 1332 |
+
{
|
| 1333 |
+
"n_samples": [Interval(Integral, 1, None, closed="left")],
|
| 1334 |
+
"noise": [Interval(Real, 0, None, closed="left")],
|
| 1335 |
+
"random_state": ["random_state"],
|
| 1336 |
+
},
|
| 1337 |
+
prefer_skip_nested_validation=True,
|
| 1338 |
+
)
|
| 1339 |
+
def make_friedman3(n_samples=100, *, noise=0.0, random_state=None):
|
| 1340 |
+
"""Generate the "Friedman #3" regression problem.
|
| 1341 |
+
|
| 1342 |
+
This dataset is described in Friedman [1] and Breiman [2].
|
| 1343 |
+
|
| 1344 |
+
Inputs `X` are 4 independent features uniformly distributed on the
|
| 1345 |
+
intervals::
|
| 1346 |
+
|
| 1347 |
+
0 <= X[:, 0] <= 100,
|
| 1348 |
+
40 * pi <= X[:, 1] <= 560 * pi,
|
| 1349 |
+
0 <= X[:, 2] <= 1,
|
| 1350 |
+
1 <= X[:, 3] <= 11.
|
| 1351 |
+
|
| 1352 |
+
The output `y` is created according to the formula::
|
| 1353 |
+
|
| 1354 |
+
y(X) = arctan((X[:, 1] * X[:, 2] - 1 / (X[:, 1] * X[:, 3])) \
|
| 1355 |
+
/ X[:, 0]) + noise * N(0, 1).
|
| 1356 |
+
|
| 1357 |
+
Read more in the :ref:`User Guide <sample_generators>`.
|
| 1358 |
+
|
| 1359 |
+
Parameters
|
| 1360 |
+
----------
|
| 1361 |
+
n_samples : int, default=100
|
| 1362 |
+
The number of samples.
|
| 1363 |
+
|
| 1364 |
+
noise : float, default=0.0
|
| 1365 |
+
The standard deviation of the gaussian noise applied to the output.
|
| 1366 |
+
|
| 1367 |
+
random_state : int, RandomState instance or None, default=None
|
| 1368 |
+
Determines random number generation for dataset noise. Pass an int
|
| 1369 |
+
for reproducible output across multiple function calls.
|
| 1370 |
+
See :term:`Glossary <random_state>`.
|
| 1371 |
+
|
| 1372 |
+
Returns
|
| 1373 |
+
-------
|
| 1374 |
+
X : ndarray of shape (n_samples, 4)
|
| 1375 |
+
The input samples.
|
| 1376 |
+
|
| 1377 |
+
y : ndarray of shape (n_samples,)
|
| 1378 |
+
The output values.
|
| 1379 |
+
|
| 1380 |
+
References
|
| 1381 |
+
----------
|
| 1382 |
+
.. [1] J. Friedman, "Multivariate adaptive regression splines", The Annals
|
| 1383 |
+
of Statistics 19 (1), pages 1-67, 1991.
|
| 1384 |
+
|
| 1385 |
+
.. [2] L. Breiman, "Bagging predictors", Machine Learning 24,
|
| 1386 |
+
pages 123-140, 1996.
|
| 1387 |
+
|
| 1388 |
+
Examples
|
| 1389 |
+
--------
|
| 1390 |
+
>>> from sklearn.datasets import make_friedman3
|
| 1391 |
+
>>> X, y = make_friedman3(random_state=42)
|
| 1392 |
+
>>> X.shape
|
| 1393 |
+
(100, 4)
|
| 1394 |
+
>>> y.shape
|
| 1395 |
+
(100,)
|
| 1396 |
+
>>> list(y[:3])
|
| 1397 |
+
[np.float64(1.54), np.float64(0.956), np.float64(0.414)]
|
| 1398 |
+
"""
|
| 1399 |
+
generator = check_random_state(random_state)
|
| 1400 |
+
|
| 1401 |
+
X = generator.uniform(size=(n_samples, 4))
|
| 1402 |
+
X[:, 0] *= 100
|
| 1403 |
+
X[:, 1] *= 520 * np.pi
|
| 1404 |
+
X[:, 1] += 40 * np.pi
|
| 1405 |
+
X[:, 3] *= 10
|
| 1406 |
+
X[:, 3] += 1
|
| 1407 |
+
|
| 1408 |
+
y = np.arctan(
|
| 1409 |
+
(X[:, 1] * X[:, 2] - 1 / (X[:, 1] * X[:, 3])) / X[:, 0]
|
| 1410 |
+
) + noise * generator.standard_normal(size=(n_samples))
|
| 1411 |
+
|
| 1412 |
+
return X, y
|
| 1413 |
+
|
| 1414 |
+
|
| 1415 |
+
@validate_params(
|
| 1416 |
+
{
|
| 1417 |
+
"n_samples": [Interval(Integral, 1, None, closed="left")],
|
| 1418 |
+
"n_features": [Interval(Integral, 1, None, closed="left")],
|
| 1419 |
+
"effective_rank": [Interval(Integral, 1, None, closed="left")],
|
| 1420 |
+
"tail_strength": [Interval(Real, 0, 1, closed="both")],
|
| 1421 |
+
"random_state": ["random_state"],
|
| 1422 |
+
},
|
| 1423 |
+
prefer_skip_nested_validation=True,
|
| 1424 |
+
)
|
| 1425 |
+
def make_low_rank_matrix(
|
| 1426 |
+
n_samples=100,
|
| 1427 |
+
n_features=100,
|
| 1428 |
+
*,
|
| 1429 |
+
effective_rank=10,
|
| 1430 |
+
tail_strength=0.5,
|
| 1431 |
+
random_state=None,
|
| 1432 |
+
):
|
| 1433 |
+
"""Generate a mostly low rank matrix with bell-shaped singular values.
|
| 1434 |
+
|
| 1435 |
+
Most of the variance can be explained by a bell-shaped curve of width
|
| 1436 |
+
effective_rank: the low rank part of the singular values profile is::
|
| 1437 |
+
|
| 1438 |
+
(1 - tail_strength) * exp(-1.0 * (i / effective_rank) ** 2)
|
| 1439 |
+
|
| 1440 |
+
The remaining singular values' tail is fat, decreasing as::
|
| 1441 |
+
|
| 1442 |
+
tail_strength * exp(-0.1 * i / effective_rank).
|
| 1443 |
+
|
| 1444 |
+
The low rank part of the profile can be considered the structured
|
| 1445 |
+
signal part of the data while the tail can be considered the noisy
|
| 1446 |
+
part of the data that cannot be summarized by a low number of linear
|
| 1447 |
+
components (singular vectors).
|
| 1448 |
+
|
| 1449 |
+
This kind of singular profiles is often seen in practice, for instance:
|
| 1450 |
+
- gray level pictures of faces
|
| 1451 |
+
- TF-IDF vectors of text documents crawled from the web
|
| 1452 |
+
|
| 1453 |
+
Read more in the :ref:`User Guide <sample_generators>`.
|
| 1454 |
+
|
| 1455 |
+
Parameters
|
| 1456 |
+
----------
|
| 1457 |
+
n_samples : int, default=100
|
| 1458 |
+
The number of samples.
|
| 1459 |
+
|
| 1460 |
+
n_features : int, default=100
|
| 1461 |
+
The number of features.
|
| 1462 |
+
|
| 1463 |
+
effective_rank : int, default=10
|
| 1464 |
+
The approximate number of singular vectors required to explain most of
|
| 1465 |
+
the data by linear combinations.
|
| 1466 |
+
|
| 1467 |
+
tail_strength : float, default=0.5
|
| 1468 |
+
The relative importance of the fat noisy tail of the singular values
|
| 1469 |
+
profile. The value should be between 0 and 1.
|
| 1470 |
+
|
| 1471 |
+
random_state : int, RandomState instance or None, default=None
|
| 1472 |
+
Determines random number generation for dataset creation. Pass an int
|
| 1473 |
+
for reproducible output across multiple function calls.
|
| 1474 |
+
See :term:`Glossary <random_state>`.
|
| 1475 |
+
|
| 1476 |
+
Returns
|
| 1477 |
+
-------
|
| 1478 |
+
X : ndarray of shape (n_samples, n_features)
|
| 1479 |
+
The matrix.
|
| 1480 |
+
|
| 1481 |
+
Examples
|
| 1482 |
+
--------
|
| 1483 |
+
>>> from numpy.linalg import svd
|
| 1484 |
+
>>> from sklearn.datasets import make_low_rank_matrix
|
| 1485 |
+
>>> X = make_low_rank_matrix(
|
| 1486 |
+
... n_samples=50,
|
| 1487 |
+
... n_features=25,
|
| 1488 |
+
... effective_rank=5,
|
| 1489 |
+
... tail_strength=0.01,
|
| 1490 |
+
... random_state=0,
|
| 1491 |
+
... )
|
| 1492 |
+
>>> X.shape
|
| 1493 |
+
(50, 25)
|
| 1494 |
+
"""
|
| 1495 |
+
generator = check_random_state(random_state)
|
| 1496 |
+
n = min(n_samples, n_features)
|
| 1497 |
+
|
| 1498 |
+
# Random (ortho normal) vectors
|
| 1499 |
+
u, _ = linalg.qr(
|
| 1500 |
+
generator.standard_normal(size=(n_samples, n)),
|
| 1501 |
+
mode="economic",
|
| 1502 |
+
check_finite=False,
|
| 1503 |
+
)
|
| 1504 |
+
v, _ = linalg.qr(
|
| 1505 |
+
generator.standard_normal(size=(n_features, n)),
|
| 1506 |
+
mode="economic",
|
| 1507 |
+
check_finite=False,
|
| 1508 |
+
)
|
| 1509 |
+
|
| 1510 |
+
# Index of the singular values
|
| 1511 |
+
singular_ind = np.arange(n, dtype=np.float64)
|
| 1512 |
+
|
| 1513 |
+
# Build the singular profile by assembling signal and noise components
|
| 1514 |
+
low_rank = (1 - tail_strength) * np.exp(-1.0 * (singular_ind / effective_rank) ** 2)
|
| 1515 |
+
tail = tail_strength * np.exp(-0.1 * singular_ind / effective_rank)
|
| 1516 |
+
s = np.identity(n) * (low_rank + tail)
|
| 1517 |
+
|
| 1518 |
+
return np.dot(np.dot(u, s), v.T)
|
| 1519 |
+
|
| 1520 |
+
|
| 1521 |
+
@validate_params(
|
| 1522 |
+
{
|
| 1523 |
+
"n_samples": [Interval(Integral, 1, None, closed="left")],
|
| 1524 |
+
"n_components": [Interval(Integral, 1, None, closed="left")],
|
| 1525 |
+
"n_features": [Interval(Integral, 1, None, closed="left")],
|
| 1526 |
+
"n_nonzero_coefs": [Interval(Integral, 1, None, closed="left")],
|
| 1527 |
+
"random_state": ["random_state"],
|
| 1528 |
+
},
|
| 1529 |
+
prefer_skip_nested_validation=True,
|
| 1530 |
+
)
|
| 1531 |
+
def make_sparse_coded_signal(
|
| 1532 |
+
n_samples,
|
| 1533 |
+
*,
|
| 1534 |
+
n_components,
|
| 1535 |
+
n_features,
|
| 1536 |
+
n_nonzero_coefs,
|
| 1537 |
+
random_state=None,
|
| 1538 |
+
):
|
| 1539 |
+
"""Generate a signal as a sparse combination of dictionary elements.
|
| 1540 |
+
|
| 1541 |
+
Returns matrices `Y`, `D` and `X` such that `Y = XD` where `X` is of shape
|
| 1542 |
+
`(n_samples, n_components)`, `D` is of shape `(n_components, n_features)`, and
|
| 1543 |
+
each row of `X` has exactly `n_nonzero_coefs` non-zero elements.
|
| 1544 |
+
|
| 1545 |
+
Read more in the :ref:`User Guide <sample_generators>`.
|
| 1546 |
+
|
| 1547 |
+
Parameters
|
| 1548 |
+
----------
|
| 1549 |
+
n_samples : int
|
| 1550 |
+
Number of samples to generate.
|
| 1551 |
+
|
| 1552 |
+
n_components : int
|
| 1553 |
+
Number of components in the dictionary.
|
| 1554 |
+
|
| 1555 |
+
n_features : int
|
| 1556 |
+
Number of features of the dataset to generate.
|
| 1557 |
+
|
| 1558 |
+
n_nonzero_coefs : int
|
| 1559 |
+
Number of active (non-zero) coefficients in each sample.
|
| 1560 |
+
|
| 1561 |
+
random_state : int, RandomState instance or None, default=None
|
| 1562 |
+
Determines random number generation for dataset creation. Pass an int
|
| 1563 |
+
for reproducible output across multiple function calls.
|
| 1564 |
+
See :term:`Glossary <random_state>`.
|
| 1565 |
+
|
| 1566 |
+
Returns
|
| 1567 |
+
-------
|
| 1568 |
+
data : ndarray of shape (n_samples, n_features)
|
| 1569 |
+
The encoded signal (Y).
|
| 1570 |
+
|
| 1571 |
+
dictionary : ndarray of shape (n_components, n_features)
|
| 1572 |
+
The dictionary with normalized components (D).
|
| 1573 |
+
|
| 1574 |
+
code : ndarray of shape (n_samples, n_components)
|
| 1575 |
+
The sparse code such that each column of this matrix has exactly
|
| 1576 |
+
n_nonzero_coefs non-zero items (X).
|
| 1577 |
+
|
| 1578 |
+
Examples
|
| 1579 |
+
--------
|
| 1580 |
+
>>> from sklearn.datasets import make_sparse_coded_signal
|
| 1581 |
+
>>> data, dictionary, code = make_sparse_coded_signal(
|
| 1582 |
+
... n_samples=50,
|
| 1583 |
+
... n_components=100,
|
| 1584 |
+
... n_features=10,
|
| 1585 |
+
... n_nonzero_coefs=4,
|
| 1586 |
+
... random_state=0
|
| 1587 |
+
... )
|
| 1588 |
+
>>> data.shape
|
| 1589 |
+
(50, 10)
|
| 1590 |
+
>>> dictionary.shape
|
| 1591 |
+
(100, 10)
|
| 1592 |
+
>>> code.shape
|
| 1593 |
+
(50, 100)
|
| 1594 |
+
"""
|
| 1595 |
+
generator = check_random_state(random_state)
|
| 1596 |
+
|
| 1597 |
+
# generate dictionary
|
| 1598 |
+
D = generator.standard_normal(size=(n_features, n_components))
|
| 1599 |
+
D /= np.sqrt(np.sum((D**2), axis=0))
|
| 1600 |
+
|
| 1601 |
+
# generate code
|
| 1602 |
+
X = np.zeros((n_components, n_samples))
|
| 1603 |
+
for i in range(n_samples):
|
| 1604 |
+
idx = np.arange(n_components)
|
| 1605 |
+
generator.shuffle(idx)
|
| 1606 |
+
idx = idx[:n_nonzero_coefs]
|
| 1607 |
+
X[idx, i] = generator.standard_normal(size=n_nonzero_coefs)
|
| 1608 |
+
|
| 1609 |
+
# encode signal
|
| 1610 |
+
Y = np.dot(D, X)
|
| 1611 |
+
|
| 1612 |
+
# Transpose to have shapes consistent with the rest of the API
|
| 1613 |
+
Y, D, X = Y.T, D.T, X.T
|
| 1614 |
+
|
| 1615 |
+
return map(np.squeeze, (Y, D, X))
|
| 1616 |
+
|
| 1617 |
+
|
| 1618 |
+
@validate_params(
|
| 1619 |
+
{
|
| 1620 |
+
"n_samples": [Interval(Integral, 1, None, closed="left")],
|
| 1621 |
+
"n_features": [Interval(Integral, 1, None, closed="left")],
|
| 1622 |
+
"random_state": ["random_state"],
|
| 1623 |
+
},
|
| 1624 |
+
prefer_skip_nested_validation=True,
|
| 1625 |
+
)
|
| 1626 |
+
def make_sparse_uncorrelated(n_samples=100, n_features=10, *, random_state=None):
|
| 1627 |
+
"""Generate a random regression problem with sparse uncorrelated design.
|
| 1628 |
+
|
| 1629 |
+
This dataset is described in Celeux et al [1]. as::
|
| 1630 |
+
|
| 1631 |
+
X ~ N(0, 1)
|
| 1632 |
+
y(X) = X[:, 0] + 2 * X[:, 1] - 2 * X[:, 2] - 1.5 * X[:, 3]
|
| 1633 |
+
|
| 1634 |
+
Only the first 4 features are informative. The remaining features are
|
| 1635 |
+
useless.
|
| 1636 |
+
|
| 1637 |
+
Read more in the :ref:`User Guide <sample_generators>`.
|
| 1638 |
+
|
| 1639 |
+
Parameters
|
| 1640 |
+
----------
|
| 1641 |
+
n_samples : int, default=100
|
| 1642 |
+
The number of samples.
|
| 1643 |
+
|
| 1644 |
+
n_features : int, default=10
|
| 1645 |
+
The number of features.
|
| 1646 |
+
|
| 1647 |
+
random_state : int, RandomState instance or None, default=None
|
| 1648 |
+
Determines random number generation for dataset creation. Pass an int
|
| 1649 |
+
for reproducible output across multiple function calls.
|
| 1650 |
+
See :term:`Glossary <random_state>`.
|
| 1651 |
+
|
| 1652 |
+
Returns
|
| 1653 |
+
-------
|
| 1654 |
+
X : ndarray of shape (n_samples, n_features)
|
| 1655 |
+
The input samples.
|
| 1656 |
+
|
| 1657 |
+
y : ndarray of shape (n_samples,)
|
| 1658 |
+
The output values.
|
| 1659 |
+
|
| 1660 |
+
References
|
| 1661 |
+
----------
|
| 1662 |
+
.. [1] G. Celeux, M. El Anbari, J.-M. Marin, C. P. Robert,
|
| 1663 |
+
"Regularization in regression: comparing Bayesian and frequentist
|
| 1664 |
+
methods in a poorly informative situation", 2009.
|
| 1665 |
+
|
| 1666 |
+
Examples
|
| 1667 |
+
--------
|
| 1668 |
+
>>> from sklearn.datasets import make_sparse_uncorrelated
|
| 1669 |
+
>>> X, y = make_sparse_uncorrelated(random_state=0)
|
| 1670 |
+
>>> X.shape
|
| 1671 |
+
(100, 10)
|
| 1672 |
+
>>> y.shape
|
| 1673 |
+
(100,)
|
| 1674 |
+
"""
|
| 1675 |
+
generator = check_random_state(random_state)
|
| 1676 |
+
|
| 1677 |
+
X = generator.normal(loc=0, scale=1, size=(n_samples, n_features))
|
| 1678 |
+
y = generator.normal(
|
| 1679 |
+
loc=(X[:, 0] + 2 * X[:, 1] - 2 * X[:, 2] - 1.5 * X[:, 3]),
|
| 1680 |
+
scale=np.ones(n_samples),
|
| 1681 |
+
)
|
| 1682 |
+
|
| 1683 |
+
return X, y
|
| 1684 |
+
|
| 1685 |
+
|
| 1686 |
+
@validate_params(
|
| 1687 |
+
{
|
| 1688 |
+
"n_dim": [Interval(Integral, 1, None, closed="left")],
|
| 1689 |
+
"random_state": ["random_state"],
|
| 1690 |
+
},
|
| 1691 |
+
prefer_skip_nested_validation=True,
|
| 1692 |
+
)
|
| 1693 |
+
def make_spd_matrix(n_dim, *, random_state=None):
|
| 1694 |
+
"""Generate a random symmetric, positive-definite matrix.
|
| 1695 |
+
|
| 1696 |
+
Read more in the :ref:`User Guide <sample_generators>`.
|
| 1697 |
+
|
| 1698 |
+
Parameters
|
| 1699 |
+
----------
|
| 1700 |
+
n_dim : int
|
| 1701 |
+
The matrix dimension.
|
| 1702 |
+
|
| 1703 |
+
random_state : int, RandomState instance or None, default=None
|
| 1704 |
+
Determines random number generation for dataset creation. Pass an int
|
| 1705 |
+
for reproducible output across multiple function calls.
|
| 1706 |
+
See :term:`Glossary <random_state>`.
|
| 1707 |
+
|
| 1708 |
+
Returns
|
| 1709 |
+
-------
|
| 1710 |
+
X : ndarray of shape (n_dim, n_dim)
|
| 1711 |
+
The random symmetric, positive-definite matrix.
|
| 1712 |
+
|
| 1713 |
+
See Also
|
| 1714 |
+
--------
|
| 1715 |
+
make_sparse_spd_matrix: Generate a sparse symmetric definite positive matrix.
|
| 1716 |
+
|
| 1717 |
+
Examples
|
| 1718 |
+
--------
|
| 1719 |
+
>>> from sklearn.datasets import make_spd_matrix
|
| 1720 |
+
>>> make_spd_matrix(n_dim=2, random_state=42)
|
| 1721 |
+
array([[2.093, 0.346],
|
| 1722 |
+
[0.346, 0.218]])
|
| 1723 |
+
"""
|
| 1724 |
+
generator = check_random_state(random_state)
|
| 1725 |
+
|
| 1726 |
+
A = generator.uniform(size=(n_dim, n_dim))
|
| 1727 |
+
U, _, Vt = linalg.svd(np.dot(A.T, A), check_finite=False)
|
| 1728 |
+
X = np.dot(np.dot(U, 1.0 + np.diag(generator.uniform(size=n_dim))), Vt)
|
| 1729 |
+
|
| 1730 |
+
return X
|
| 1731 |
+
|
| 1732 |
+
|
| 1733 |
+
@validate_params(
|
| 1734 |
+
{
|
| 1735 |
+
"n_dim": [Interval(Integral, 1, None, closed="left")],
|
| 1736 |
+
"alpha": [Interval(Real, 0, 1, closed="both")],
|
| 1737 |
+
"norm_diag": ["boolean"],
|
| 1738 |
+
"smallest_coef": [Interval(Real, 0, 1, closed="both")],
|
| 1739 |
+
"largest_coef": [Interval(Real, 0, 1, closed="both")],
|
| 1740 |
+
"sparse_format": [
|
| 1741 |
+
StrOptions({"bsr", "coo", "csc", "csr", "dia", "dok", "lil"}),
|
| 1742 |
+
None,
|
| 1743 |
+
],
|
| 1744 |
+
"random_state": ["random_state"],
|
| 1745 |
+
},
|
| 1746 |
+
prefer_skip_nested_validation=True,
|
| 1747 |
+
)
|
| 1748 |
+
def make_sparse_spd_matrix(
|
| 1749 |
+
n_dim=1,
|
| 1750 |
+
*,
|
| 1751 |
+
alpha=0.95,
|
| 1752 |
+
norm_diag=False,
|
| 1753 |
+
smallest_coef=0.1,
|
| 1754 |
+
largest_coef=0.9,
|
| 1755 |
+
sparse_format=None,
|
| 1756 |
+
random_state=None,
|
| 1757 |
+
):
|
| 1758 |
+
"""Generate a sparse symmetric definite positive matrix.
|
| 1759 |
+
|
| 1760 |
+
Read more in the :ref:`User Guide <sample_generators>`.
|
| 1761 |
+
|
| 1762 |
+
Parameters
|
| 1763 |
+
----------
|
| 1764 |
+
n_dim : int, default=1
|
| 1765 |
+
The size of the random matrix to generate.
|
| 1766 |
+
|
| 1767 |
+
.. versionchanged:: 1.4
|
| 1768 |
+
Renamed from ``dim`` to ``n_dim``.
|
| 1769 |
+
|
| 1770 |
+
alpha : float, default=0.95
|
| 1771 |
+
The probability that a coefficient is zero (see notes). Larger values
|
| 1772 |
+
enforce more sparsity. The value should be in the range 0 and 1.
|
| 1773 |
+
|
| 1774 |
+
norm_diag : bool, default=False
|
| 1775 |
+
Whether to normalize the output matrix to make the leading diagonal
|
| 1776 |
+
elements all 1.
|
| 1777 |
+
|
| 1778 |
+
smallest_coef : float, default=0.1
|
| 1779 |
+
The value of the smallest coefficient between 0 and 1.
|
| 1780 |
+
|
| 1781 |
+
largest_coef : float, default=0.9
|
| 1782 |
+
The value of the largest coefficient between 0 and 1.
|
| 1783 |
+
|
| 1784 |
+
sparse_format : str, default=None
|
| 1785 |
+
String representing the output sparse format, such as 'csc', 'csr', etc.
|
| 1786 |
+
If ``None``, return a dense numpy ndarray.
|
| 1787 |
+
|
| 1788 |
+
.. versionadded:: 1.4
|
| 1789 |
+
|
| 1790 |
+
random_state : int, RandomState instance or None, default=None
|
| 1791 |
+
Determines random number generation for dataset creation. Pass an int
|
| 1792 |
+
for reproducible output across multiple function calls.
|
| 1793 |
+
See :term:`Glossary <random_state>`.
|
| 1794 |
+
|
| 1795 |
+
Returns
|
| 1796 |
+
-------
|
| 1797 |
+
prec : ndarray or sparse matrix of shape (dim, dim)
|
| 1798 |
+
The generated matrix. If ``sparse_format=None``, this would be an ndarray.
|
| 1799 |
+
Otherwise, this will be a sparse matrix of the specified format.
|
| 1800 |
+
|
| 1801 |
+
See Also
|
| 1802 |
+
--------
|
| 1803 |
+
make_spd_matrix : Generate a random symmetric, positive-definite matrix.
|
| 1804 |
+
|
| 1805 |
+
Notes
|
| 1806 |
+
-----
|
| 1807 |
+
The sparsity is actually imposed on the cholesky factor of the matrix.
|
| 1808 |
+
Thus alpha does not translate directly into the filling fraction of
|
| 1809 |
+
the matrix itself.
|
| 1810 |
+
|
| 1811 |
+
Examples
|
| 1812 |
+
--------
|
| 1813 |
+
>>> from sklearn.datasets import make_sparse_spd_matrix
|
| 1814 |
+
>>> make_sparse_spd_matrix(n_dim=4, norm_diag=False, random_state=42)
|
| 1815 |
+
array([[1., 0., 0., 0.],
|
| 1816 |
+
[0., 1., 0., 0.],
|
| 1817 |
+
[0., 0., 1., 0.],
|
| 1818 |
+
[0., 0., 0., 1.]])
|
| 1819 |
+
"""
|
| 1820 |
+
random_state = check_random_state(random_state)
|
| 1821 |
+
|
| 1822 |
+
chol = -sp.eye(n_dim)
|
| 1823 |
+
aux = sp.random(
|
| 1824 |
+
m=n_dim,
|
| 1825 |
+
n=n_dim,
|
| 1826 |
+
density=1 - alpha,
|
| 1827 |
+
data_rvs=lambda x: random_state.uniform(
|
| 1828 |
+
low=smallest_coef, high=largest_coef, size=x
|
| 1829 |
+
),
|
| 1830 |
+
random_state=random_state,
|
| 1831 |
+
)
|
| 1832 |
+
# We need to avoid "coo" format because it does not support slicing
|
| 1833 |
+
aux = sp.tril(aux, k=-1, format="csc")
|
| 1834 |
+
|
| 1835 |
+
# Permute the lines: we don't want to have asymmetries in the final
|
| 1836 |
+
# SPD matrix
|
| 1837 |
+
permutation = random_state.permutation(n_dim)
|
| 1838 |
+
aux = aux[permutation].T[permutation]
|
| 1839 |
+
chol += aux
|
| 1840 |
+
prec = chol.T @ chol
|
| 1841 |
+
|
| 1842 |
+
if norm_diag:
|
| 1843 |
+
# Form the diagonal vector into a row matrix
|
| 1844 |
+
d = sp.diags(1.0 / np.sqrt(prec.diagonal()))
|
| 1845 |
+
prec = d @ prec @ d
|
| 1846 |
+
|
| 1847 |
+
if sparse_format is None:
|
| 1848 |
+
return prec.toarray()
|
| 1849 |
+
else:
|
| 1850 |
+
return prec.asformat(sparse_format)
|
| 1851 |
+
|
| 1852 |
+
|
| 1853 |
+
@validate_params(
|
| 1854 |
+
{
|
| 1855 |
+
"n_samples": [Interval(Integral, 1, None, closed="left")],
|
| 1856 |
+
"noise": [Interval(Real, 0, None, closed="left")],
|
| 1857 |
+
"random_state": ["random_state"],
|
| 1858 |
+
"hole": ["boolean"],
|
| 1859 |
+
},
|
| 1860 |
+
prefer_skip_nested_validation=True,
|
| 1861 |
+
)
|
| 1862 |
+
def make_swiss_roll(n_samples=100, *, noise=0.0, random_state=None, hole=False):
|
| 1863 |
+
"""Generate a swiss roll dataset.
|
| 1864 |
+
|
| 1865 |
+
Read more in the :ref:`User Guide <sample_generators>`.
|
| 1866 |
+
|
| 1867 |
+
Adapted with permission from Stephen Marsland's code [1].
|
| 1868 |
+
|
| 1869 |
+
Parameters
|
| 1870 |
+
----------
|
| 1871 |
+
n_samples : int, default=100
|
| 1872 |
+
The number of sample points on the Swiss Roll.
|
| 1873 |
+
|
| 1874 |
+
noise : float, default=0.0
|
| 1875 |
+
The standard deviation of the gaussian noise.
|
| 1876 |
+
|
| 1877 |
+
random_state : int, RandomState instance or None, default=None
|
| 1878 |
+
Determines random number generation for dataset creation. Pass an int
|
| 1879 |
+
for reproducible output across multiple function calls.
|
| 1880 |
+
See :term:`Glossary <random_state>`.
|
| 1881 |
+
|
| 1882 |
+
hole : bool, default=False
|
| 1883 |
+
If True generates the swiss roll with hole dataset.
|
| 1884 |
+
|
| 1885 |
+
Returns
|
| 1886 |
+
-------
|
| 1887 |
+
X : ndarray of shape (n_samples, 3)
|
| 1888 |
+
The points.
|
| 1889 |
+
|
| 1890 |
+
t : ndarray of shape (n_samples,)
|
| 1891 |
+
The univariate position of the sample according to the main dimension
|
| 1892 |
+
of the points in the manifold.
|
| 1893 |
+
|
| 1894 |
+
Notes
|
| 1895 |
+
-----
|
| 1896 |
+
The algorithm is from Marsland [1].
|
| 1897 |
+
|
| 1898 |
+
References
|
| 1899 |
+
----------
|
| 1900 |
+
.. [1] S. Marsland, "Machine Learning: An Algorithmic Perspective", 2nd edition,
|
| 1901 |
+
Chapter 6, 2014.
|
| 1902 |
+
https://homepages.ecs.vuw.ac.nz/~marslast/Code/Ch6/lle.py
|
| 1903 |
+
|
| 1904 |
+
Examples
|
| 1905 |
+
--------
|
| 1906 |
+
>>> from sklearn.datasets import make_swiss_roll
|
| 1907 |
+
>>> X, t = make_swiss_roll(noise=0.05, random_state=0)
|
| 1908 |
+
>>> X.shape
|
| 1909 |
+
(100, 3)
|
| 1910 |
+
>>> t.shape
|
| 1911 |
+
(100,)
|
| 1912 |
+
"""
|
| 1913 |
+
generator = check_random_state(random_state)
|
| 1914 |
+
|
| 1915 |
+
if not hole:
|
| 1916 |
+
t = 1.5 * np.pi * (1 + 2 * generator.uniform(size=n_samples))
|
| 1917 |
+
y = 21 * generator.uniform(size=n_samples)
|
| 1918 |
+
else:
|
| 1919 |
+
corners = np.array(
|
| 1920 |
+
[[np.pi * (1.5 + i), j * 7] for i in range(3) for j in range(3)]
|
| 1921 |
+
)
|
| 1922 |
+
corners = np.delete(corners, 4, axis=0)
|
| 1923 |
+
corner_index = generator.choice(8, n_samples)
|
| 1924 |
+
parameters = generator.uniform(size=(2, n_samples)) * np.array([[np.pi], [7]])
|
| 1925 |
+
t, y = corners[corner_index].T + parameters
|
| 1926 |
+
|
| 1927 |
+
x = t * np.cos(t)
|
| 1928 |
+
z = t * np.sin(t)
|
| 1929 |
+
|
| 1930 |
+
X = np.vstack((x, y, z))
|
| 1931 |
+
X += noise * generator.standard_normal(size=(3, n_samples))
|
| 1932 |
+
X = X.T
|
| 1933 |
+
t = np.squeeze(t)
|
| 1934 |
+
|
| 1935 |
+
return X, t
|
| 1936 |
+
|
| 1937 |
+
|
| 1938 |
+
@validate_params(
|
| 1939 |
+
{
|
| 1940 |
+
"n_samples": [Interval(Integral, 1, None, closed="left")],
|
| 1941 |
+
"noise": [Interval(Real, 0, None, closed="left")],
|
| 1942 |
+
"random_state": ["random_state"],
|
| 1943 |
+
},
|
| 1944 |
+
prefer_skip_nested_validation=True,
|
| 1945 |
+
)
|
| 1946 |
+
def make_s_curve(n_samples=100, *, noise=0.0, random_state=None):
|
| 1947 |
+
"""Generate an S curve dataset.
|
| 1948 |
+
|
| 1949 |
+
Read more in the :ref:`User Guide <sample_generators>`.
|
| 1950 |
+
|
| 1951 |
+
Parameters
|
| 1952 |
+
----------
|
| 1953 |
+
n_samples : int, default=100
|
| 1954 |
+
The number of sample points on the S curve.
|
| 1955 |
+
|
| 1956 |
+
noise : float, default=0.0
|
| 1957 |
+
The standard deviation of the gaussian noise.
|
| 1958 |
+
|
| 1959 |
+
random_state : int, RandomState instance or None, default=None
|
| 1960 |
+
Determines random number generation for dataset creation. Pass an int
|
| 1961 |
+
for reproducible output across multiple function calls.
|
| 1962 |
+
See :term:`Glossary <random_state>`.
|
| 1963 |
+
|
| 1964 |
+
Returns
|
| 1965 |
+
-------
|
| 1966 |
+
X : ndarray of shape (n_samples, 3)
|
| 1967 |
+
The points.
|
| 1968 |
+
|
| 1969 |
+
t : ndarray of shape (n_samples,)
|
| 1970 |
+
The univariate position of the sample according
|
| 1971 |
+
to the main dimension of the points in the manifold.
|
| 1972 |
+
|
| 1973 |
+
Examples
|
| 1974 |
+
--------
|
| 1975 |
+
>>> from sklearn.datasets import make_s_curve
|
| 1976 |
+
>>> X, t = make_s_curve(noise=0.05, random_state=0)
|
| 1977 |
+
>>> X.shape
|
| 1978 |
+
(100, 3)
|
| 1979 |
+
>>> t.shape
|
| 1980 |
+
(100,)
|
| 1981 |
+
"""
|
| 1982 |
+
generator = check_random_state(random_state)
|
| 1983 |
+
|
| 1984 |
+
t = 3 * np.pi * (generator.uniform(size=(1, n_samples)) - 0.5)
|
| 1985 |
+
X = np.empty(shape=(n_samples, 3), dtype=np.float64)
|
| 1986 |
+
X[:, 0] = np.sin(t)
|
| 1987 |
+
X[:, 1] = 2.0 * generator.uniform(size=n_samples)
|
| 1988 |
+
X[:, 2] = np.sign(t) * (np.cos(t) - 1)
|
| 1989 |
+
X += noise * generator.standard_normal(size=(3, n_samples)).T
|
| 1990 |
+
t = np.squeeze(t)
|
| 1991 |
+
|
| 1992 |
+
return X, t
|
| 1993 |
+
|
| 1994 |
+
|
| 1995 |
+
@validate_params(
|
| 1996 |
+
{
|
| 1997 |
+
"mean": ["array-like", None],
|
| 1998 |
+
"cov": [Interval(Real, 0, None, closed="left")],
|
| 1999 |
+
"n_samples": [Interval(Integral, 1, None, closed="left")],
|
| 2000 |
+
"n_features": [Interval(Integral, 1, None, closed="left")],
|
| 2001 |
+
"n_classes": [Interval(Integral, 1, None, closed="left")],
|
| 2002 |
+
"shuffle": ["boolean"],
|
| 2003 |
+
"random_state": ["random_state"],
|
| 2004 |
+
},
|
| 2005 |
+
prefer_skip_nested_validation=True,
|
| 2006 |
+
)
|
| 2007 |
+
def make_gaussian_quantiles(
|
| 2008 |
+
*,
|
| 2009 |
+
mean=None,
|
| 2010 |
+
cov=1.0,
|
| 2011 |
+
n_samples=100,
|
| 2012 |
+
n_features=2,
|
| 2013 |
+
n_classes=3,
|
| 2014 |
+
shuffle=True,
|
| 2015 |
+
random_state=None,
|
| 2016 |
+
):
|
| 2017 |
+
r"""Generate isotropic Gaussian and label samples by quantile.
|
| 2018 |
+
|
| 2019 |
+
This classification dataset is constructed by taking a multi-dimensional
|
| 2020 |
+
standard normal distribution and defining classes separated by nested
|
| 2021 |
+
concentric multi-dimensional spheres such that roughly equal numbers of
|
| 2022 |
+
samples are in each class (quantiles of the :math:`\chi^2` distribution).
|
| 2023 |
+
|
| 2024 |
+
Read more in the :ref:`User Guide <sample_generators>`.
|
| 2025 |
+
|
| 2026 |
+
Parameters
|
| 2027 |
+
----------
|
| 2028 |
+
mean : array-like of shape (n_features,), default=None
|
| 2029 |
+
The mean of the multi-dimensional normal distribution.
|
| 2030 |
+
If None then use the origin (0, 0, ...).
|
| 2031 |
+
|
| 2032 |
+
cov : float, default=1.0
|
| 2033 |
+
The covariance matrix will be this value times the unit matrix. This
|
| 2034 |
+
dataset only produces symmetric normal distributions.
|
| 2035 |
+
|
| 2036 |
+
n_samples : int, default=100
|
| 2037 |
+
The total number of points equally divided among classes.
|
| 2038 |
+
|
| 2039 |
+
n_features : int, default=2
|
| 2040 |
+
The number of features for each sample.
|
| 2041 |
+
|
| 2042 |
+
n_classes : int, default=3
|
| 2043 |
+
The number of classes.
|
| 2044 |
+
|
| 2045 |
+
shuffle : bool, default=True
|
| 2046 |
+
Shuffle the samples.
|
| 2047 |
+
|
| 2048 |
+
random_state : int, RandomState instance or None, default=None
|
| 2049 |
+
Determines random number generation for dataset creation. Pass an int
|
| 2050 |
+
for reproducible output across multiple function calls.
|
| 2051 |
+
See :term:`Glossary <random_state>`.
|
| 2052 |
+
|
| 2053 |
+
Returns
|
| 2054 |
+
-------
|
| 2055 |
+
X : ndarray of shape (n_samples, n_features)
|
| 2056 |
+
The generated samples.
|
| 2057 |
+
|
| 2058 |
+
y : ndarray of shape (n_samples,)
|
| 2059 |
+
The integer labels for quantile membership of each sample.
|
| 2060 |
+
|
| 2061 |
+
Notes
|
| 2062 |
+
-----
|
| 2063 |
+
The dataset is from Zhu et al [1].
|
| 2064 |
+
|
| 2065 |
+
References
|
| 2066 |
+
----------
|
| 2067 |
+
.. [1] J. Zhu, H. Zou, S. Rosset, T. Hastie, "Multi-class AdaBoost", 2009.
|
| 2068 |
+
|
| 2069 |
+
Examples
|
| 2070 |
+
--------
|
| 2071 |
+
>>> from sklearn.datasets import make_gaussian_quantiles
|
| 2072 |
+
>>> X, y = make_gaussian_quantiles(random_state=42)
|
| 2073 |
+
>>> X.shape
|
| 2074 |
+
(100, 2)
|
| 2075 |
+
>>> y.shape
|
| 2076 |
+
(100,)
|
| 2077 |
+
>>> list(y[:5])
|
| 2078 |
+
[np.int64(2), np.int64(0), np.int64(1), np.int64(0), np.int64(2)]
|
| 2079 |
+
"""
|
| 2080 |
+
if n_samples < n_classes:
|
| 2081 |
+
raise ValueError("n_samples must be at least n_classes")
|
| 2082 |
+
|
| 2083 |
+
generator = check_random_state(random_state)
|
| 2084 |
+
|
| 2085 |
+
if mean is None:
|
| 2086 |
+
mean = np.zeros(n_features)
|
| 2087 |
+
else:
|
| 2088 |
+
mean = np.array(mean)
|
| 2089 |
+
|
| 2090 |
+
# Build multivariate normal distribution
|
| 2091 |
+
X = generator.multivariate_normal(mean, cov * np.identity(n_features), (n_samples,))
|
| 2092 |
+
|
| 2093 |
+
# Sort by distance from origin
|
| 2094 |
+
idx = np.argsort(np.sum((X - mean[np.newaxis, :]) ** 2, axis=1))
|
| 2095 |
+
X = X[idx, :]
|
| 2096 |
+
|
| 2097 |
+
# Label by quantile
|
| 2098 |
+
step = n_samples // n_classes
|
| 2099 |
+
|
| 2100 |
+
y = np.hstack(
|
| 2101 |
+
[
|
| 2102 |
+
np.repeat(np.arange(n_classes), step),
|
| 2103 |
+
np.repeat(n_classes - 1, n_samples - step * n_classes),
|
| 2104 |
+
]
|
| 2105 |
+
)
|
| 2106 |
+
|
| 2107 |
+
if shuffle:
|
| 2108 |
+
X, y = util_shuffle(X, y, random_state=generator)
|
| 2109 |
+
|
| 2110 |
+
return X, y
|
| 2111 |
+
|
| 2112 |
+
|
| 2113 |
+
def _shuffle(data, random_state=None):
|
| 2114 |
+
generator = check_random_state(random_state)
|
| 2115 |
+
n_rows, n_cols = data.shape
|
| 2116 |
+
row_idx = generator.permutation(n_rows)
|
| 2117 |
+
col_idx = generator.permutation(n_cols)
|
| 2118 |
+
result = data[row_idx][:, col_idx]
|
| 2119 |
+
return result, row_idx, col_idx
|
| 2120 |
+
|
| 2121 |
+
|
| 2122 |
+
@validate_params(
|
| 2123 |
+
{
|
| 2124 |
+
"shape": [tuple],
|
| 2125 |
+
"n_clusters": [Interval(Integral, 1, None, closed="left")],
|
| 2126 |
+
"noise": [Interval(Real, 0, None, closed="left")],
|
| 2127 |
+
"minval": [Interval(Real, None, None, closed="neither")],
|
| 2128 |
+
"maxval": [Interval(Real, None, None, closed="neither")],
|
| 2129 |
+
"shuffle": ["boolean"],
|
| 2130 |
+
"random_state": ["random_state"],
|
| 2131 |
+
},
|
| 2132 |
+
prefer_skip_nested_validation=True,
|
| 2133 |
+
)
|
| 2134 |
+
def make_biclusters(
|
| 2135 |
+
shape,
|
| 2136 |
+
n_clusters,
|
| 2137 |
+
*,
|
| 2138 |
+
noise=0.0,
|
| 2139 |
+
minval=10,
|
| 2140 |
+
maxval=100,
|
| 2141 |
+
shuffle=True,
|
| 2142 |
+
random_state=None,
|
| 2143 |
+
):
|
| 2144 |
+
"""Generate a constant block diagonal structure array for biclustering.
|
| 2145 |
+
|
| 2146 |
+
Read more in the :ref:`User Guide <sample_generators>`.
|
| 2147 |
+
|
| 2148 |
+
Parameters
|
| 2149 |
+
----------
|
| 2150 |
+
shape : tuple of shape (n_rows, n_cols)
|
| 2151 |
+
The shape of the result.
|
| 2152 |
+
|
| 2153 |
+
n_clusters : int
|
| 2154 |
+
The number of biclusters.
|
| 2155 |
+
|
| 2156 |
+
noise : float, default=0.0
|
| 2157 |
+
The standard deviation of the gaussian noise.
|
| 2158 |
+
|
| 2159 |
+
minval : float, default=10
|
| 2160 |
+
Minimum value of a bicluster.
|
| 2161 |
+
|
| 2162 |
+
maxval : float, default=100
|
| 2163 |
+
Maximum value of a bicluster.
|
| 2164 |
+
|
| 2165 |
+
shuffle : bool, default=True
|
| 2166 |
+
Shuffle the samples.
|
| 2167 |
+
|
| 2168 |
+
random_state : int, RandomState instance or None, default=None
|
| 2169 |
+
Determines random number generation for dataset creation. Pass an int
|
| 2170 |
+
for reproducible output across multiple function calls.
|
| 2171 |
+
See :term:`Glossary <random_state>`.
|
| 2172 |
+
|
| 2173 |
+
Returns
|
| 2174 |
+
-------
|
| 2175 |
+
X : ndarray of shape `shape`
|
| 2176 |
+
The generated array.
|
| 2177 |
+
|
| 2178 |
+
rows : ndarray of shape (n_clusters, X.shape[0])
|
| 2179 |
+
The indicators for cluster membership of each row.
|
| 2180 |
+
|
| 2181 |
+
cols : ndarray of shape (n_clusters, X.shape[1])
|
| 2182 |
+
The indicators for cluster membership of each column.
|
| 2183 |
+
|
| 2184 |
+
See Also
|
| 2185 |
+
--------
|
| 2186 |
+
make_checkerboard: Generate an array with block checkerboard structure for
|
| 2187 |
+
biclustering.
|
| 2188 |
+
|
| 2189 |
+
References
|
| 2190 |
+
----------
|
| 2191 |
+
|
| 2192 |
+
.. [1] Dhillon, I. S. (2001, August). Co-clustering documents and
|
| 2193 |
+
words using bipartite spectral graph partitioning. In Proceedings
|
| 2194 |
+
of the seventh ACM SIGKDD international conference on Knowledge
|
| 2195 |
+
discovery and data mining (pp. 269-274). ACM.
|
| 2196 |
+
|
| 2197 |
+
Examples
|
| 2198 |
+
--------
|
| 2199 |
+
>>> from sklearn.datasets import make_biclusters
|
| 2200 |
+
>>> data, rows, cols = make_biclusters(
|
| 2201 |
+
... shape=(10, 20), n_clusters=2, random_state=42
|
| 2202 |
+
... )
|
| 2203 |
+
>>> data.shape
|
| 2204 |
+
(10, 20)
|
| 2205 |
+
>>> rows.shape
|
| 2206 |
+
(2, 10)
|
| 2207 |
+
>>> cols.shape
|
| 2208 |
+
(2, 20)
|
| 2209 |
+
"""
|
| 2210 |
+
generator = check_random_state(random_state)
|
| 2211 |
+
n_rows, n_cols = shape
|
| 2212 |
+
consts = generator.uniform(minval, maxval, n_clusters)
|
| 2213 |
+
|
| 2214 |
+
# row and column clusters of approximately equal sizes
|
| 2215 |
+
row_sizes = generator.multinomial(n_rows, np.repeat(1.0 / n_clusters, n_clusters))
|
| 2216 |
+
col_sizes = generator.multinomial(n_cols, np.repeat(1.0 / n_clusters, n_clusters))
|
| 2217 |
+
|
| 2218 |
+
row_labels = np.hstack(
|
| 2219 |
+
[np.repeat(val, rep) for val, rep in zip(range(n_clusters), row_sizes)]
|
| 2220 |
+
)
|
| 2221 |
+
col_labels = np.hstack(
|
| 2222 |
+
[np.repeat(val, rep) for val, rep in zip(range(n_clusters), col_sizes)]
|
| 2223 |
+
)
|
| 2224 |
+
|
| 2225 |
+
result = np.zeros(shape, dtype=np.float64)
|
| 2226 |
+
for i in range(n_clusters):
|
| 2227 |
+
selector = np.outer(row_labels == i, col_labels == i)
|
| 2228 |
+
result[selector] += consts[i]
|
| 2229 |
+
|
| 2230 |
+
if noise > 0:
|
| 2231 |
+
result += generator.normal(scale=noise, size=result.shape)
|
| 2232 |
+
|
| 2233 |
+
if shuffle:
|
| 2234 |
+
result, row_idx, col_idx = _shuffle(result, random_state)
|
| 2235 |
+
row_labels = row_labels[row_idx]
|
| 2236 |
+
col_labels = col_labels[col_idx]
|
| 2237 |
+
|
| 2238 |
+
rows = np.vstack([row_labels == c for c in range(n_clusters)])
|
| 2239 |
+
cols = np.vstack([col_labels == c for c in range(n_clusters)])
|
| 2240 |
+
|
| 2241 |
+
return result, rows, cols
|
| 2242 |
+
|
| 2243 |
+
|
| 2244 |
+
@validate_params(
|
| 2245 |
+
{
|
| 2246 |
+
"shape": [tuple],
|
| 2247 |
+
"n_clusters": [Interval(Integral, 1, None, closed="left"), "array-like"],
|
| 2248 |
+
"noise": [Interval(Real, 0, None, closed="left")],
|
| 2249 |
+
"minval": [Interval(Real, None, None, closed="neither")],
|
| 2250 |
+
"maxval": [Interval(Real, None, None, closed="neither")],
|
| 2251 |
+
"shuffle": ["boolean"],
|
| 2252 |
+
"random_state": ["random_state"],
|
| 2253 |
+
},
|
| 2254 |
+
prefer_skip_nested_validation=True,
|
| 2255 |
+
)
|
| 2256 |
+
def make_checkerboard(
|
| 2257 |
+
shape,
|
| 2258 |
+
n_clusters,
|
| 2259 |
+
*,
|
| 2260 |
+
noise=0.0,
|
| 2261 |
+
minval=10,
|
| 2262 |
+
maxval=100,
|
| 2263 |
+
shuffle=True,
|
| 2264 |
+
random_state=None,
|
| 2265 |
+
):
|
| 2266 |
+
"""Generate an array with block checkerboard structure for biclustering.
|
| 2267 |
+
|
| 2268 |
+
Read more in the :ref:`User Guide <sample_generators>`.
|
| 2269 |
+
|
| 2270 |
+
Parameters
|
| 2271 |
+
----------
|
| 2272 |
+
shape : tuple of shape (n_rows, n_cols)
|
| 2273 |
+
The shape of the result.
|
| 2274 |
+
|
| 2275 |
+
n_clusters : int or array-like or shape (n_row_clusters, n_column_clusters)
|
| 2276 |
+
The number of row and column clusters.
|
| 2277 |
+
|
| 2278 |
+
noise : float, default=0.0
|
| 2279 |
+
The standard deviation of the gaussian noise.
|
| 2280 |
+
|
| 2281 |
+
minval : float, default=10
|
| 2282 |
+
Minimum value of a bicluster.
|
| 2283 |
+
|
| 2284 |
+
maxval : float, default=100
|
| 2285 |
+
Maximum value of a bicluster.
|
| 2286 |
+
|
| 2287 |
+
shuffle : bool, default=True
|
| 2288 |
+
Shuffle the samples.
|
| 2289 |
+
|
| 2290 |
+
random_state : int, RandomState instance or None, default=None
|
| 2291 |
+
Determines random number generation for dataset creation. Pass an int
|
| 2292 |
+
for reproducible output across multiple function calls.
|
| 2293 |
+
See :term:`Glossary <random_state>`.
|
| 2294 |
+
|
| 2295 |
+
Returns
|
| 2296 |
+
-------
|
| 2297 |
+
X : ndarray of shape `shape`
|
| 2298 |
+
The generated array.
|
| 2299 |
+
|
| 2300 |
+
rows : ndarray of shape (n_clusters, X.shape[0])
|
| 2301 |
+
The indicators for cluster membership of each row.
|
| 2302 |
+
|
| 2303 |
+
cols : ndarray of shape (n_clusters, X.shape[1])
|
| 2304 |
+
The indicators for cluster membership of each column.
|
| 2305 |
+
|
| 2306 |
+
See Also
|
| 2307 |
+
--------
|
| 2308 |
+
make_biclusters : Generate an array with constant block diagonal structure
|
| 2309 |
+
for biclustering.
|
| 2310 |
+
|
| 2311 |
+
References
|
| 2312 |
+
----------
|
| 2313 |
+
.. [1] Kluger, Y., Basri, R., Chang, J. T., & Gerstein, M. (2003).
|
| 2314 |
+
Spectral biclustering of microarray data: coclustering genes
|
| 2315 |
+
and conditions. Genome research, 13(4), 703-716.
|
| 2316 |
+
|
| 2317 |
+
Examples
|
| 2318 |
+
--------
|
| 2319 |
+
>>> from sklearn.datasets import make_checkerboard
|
| 2320 |
+
>>> data, rows, columns = make_checkerboard(shape=(300, 300), n_clusters=10,
|
| 2321 |
+
... random_state=42)
|
| 2322 |
+
>>> data.shape
|
| 2323 |
+
(300, 300)
|
| 2324 |
+
>>> rows.shape
|
| 2325 |
+
(100, 300)
|
| 2326 |
+
>>> columns.shape
|
| 2327 |
+
(100, 300)
|
| 2328 |
+
>>> print(rows[0][:5], columns[0][:5])
|
| 2329 |
+
[False False False True False] [False False False False False]
|
| 2330 |
+
"""
|
| 2331 |
+
generator = check_random_state(random_state)
|
| 2332 |
+
|
| 2333 |
+
if hasattr(n_clusters, "__len__"):
|
| 2334 |
+
n_row_clusters, n_col_clusters = n_clusters
|
| 2335 |
+
else:
|
| 2336 |
+
n_row_clusters = n_col_clusters = n_clusters
|
| 2337 |
+
|
| 2338 |
+
# row and column clusters of approximately equal sizes
|
| 2339 |
+
n_rows, n_cols = shape
|
| 2340 |
+
row_sizes = generator.multinomial(
|
| 2341 |
+
n_rows, np.repeat(1.0 / n_row_clusters, n_row_clusters)
|
| 2342 |
+
)
|
| 2343 |
+
col_sizes = generator.multinomial(
|
| 2344 |
+
n_cols, np.repeat(1.0 / n_col_clusters, n_col_clusters)
|
| 2345 |
+
)
|
| 2346 |
+
|
| 2347 |
+
row_labels = np.hstack(
|
| 2348 |
+
[np.repeat(val, rep) for val, rep in zip(range(n_row_clusters), row_sizes)]
|
| 2349 |
+
)
|
| 2350 |
+
col_labels = np.hstack(
|
| 2351 |
+
[np.repeat(val, rep) for val, rep in zip(range(n_col_clusters), col_sizes)]
|
| 2352 |
+
)
|
| 2353 |
+
|
| 2354 |
+
result = np.zeros(shape, dtype=np.float64)
|
| 2355 |
+
for i in range(n_row_clusters):
|
| 2356 |
+
for j in range(n_col_clusters):
|
| 2357 |
+
selector = np.outer(row_labels == i, col_labels == j)
|
| 2358 |
+
result[selector] += generator.uniform(minval, maxval)
|
| 2359 |
+
|
| 2360 |
+
if noise > 0:
|
| 2361 |
+
result += generator.normal(scale=noise, size=result.shape)
|
| 2362 |
+
|
| 2363 |
+
if shuffle:
|
| 2364 |
+
result, row_idx, col_idx = _shuffle(result, random_state)
|
| 2365 |
+
row_labels = row_labels[row_idx]
|
| 2366 |
+
col_labels = col_labels[col_idx]
|
| 2367 |
+
|
| 2368 |
+
rows = np.vstack(
|
| 2369 |
+
[
|
| 2370 |
+
row_labels == label
|
| 2371 |
+
for label in range(n_row_clusters)
|
| 2372 |
+
for _ in range(n_col_clusters)
|
| 2373 |
+
]
|
| 2374 |
+
)
|
| 2375 |
+
cols = np.vstack(
|
| 2376 |
+
[
|
| 2377 |
+
col_labels == label
|
| 2378 |
+
for _ in range(n_row_clusters)
|
| 2379 |
+
for label in range(n_col_clusters)
|
| 2380 |
+
]
|
| 2381 |
+
)
|
| 2382 |
+
|
| 2383 |
+
return result, rows, cols
|
miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/datasets/_species_distributions.py
ADDED
|
@@ -0,0 +1,289 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
=============================
|
| 3 |
+
Species distribution dataset
|
| 4 |
+
=============================
|
| 5 |
+
|
| 6 |
+
This dataset represents the geographic distribution of species.
|
| 7 |
+
The dataset is provided by Phillips et. al. (2006).
|
| 8 |
+
|
| 9 |
+
The two species are:
|
| 10 |
+
|
| 11 |
+
- `"Bradypus variegatus"
|
| 12 |
+
<http://www.iucnredlist.org/details/3038/0>`_ ,
|
| 13 |
+
the Brown-throated Sloth.
|
| 14 |
+
|
| 15 |
+
- `"Microryzomys minutus"
|
| 16 |
+
<http://www.iucnredlist.org/details/13408/0>`_ ,
|
| 17 |
+
also known as the Forest Small Rice Rat, a rodent that lives in Peru,
|
| 18 |
+
Colombia, Ecuador, Peru, and Venezuela.
|
| 19 |
+
|
| 20 |
+
References
|
| 21 |
+
----------
|
| 22 |
+
|
| 23 |
+
`"Maximum entropy modeling of species geographic distributions"
|
| 24 |
+
<http://rob.schapire.net/papers/ecolmod.pdf>`_ S. J. Phillips,
|
| 25 |
+
R. P. Anderson, R. E. Schapire - Ecological Modelling, 190:231-259, 2006.
|
| 26 |
+
"""
|
| 27 |
+
|
| 28 |
+
# Authors: The scikit-learn developers
|
| 29 |
+
# SPDX-License-Identifier: BSD-3-Clause
|
| 30 |
+
|
| 31 |
+
import logging
|
| 32 |
+
from io import BytesIO
|
| 33 |
+
from numbers import Integral, Real
|
| 34 |
+
from os import PathLike, makedirs, remove
|
| 35 |
+
from os.path import exists
|
| 36 |
+
|
| 37 |
+
import joblib
|
| 38 |
+
import numpy as np
|
| 39 |
+
|
| 40 |
+
from ..utils import Bunch
|
| 41 |
+
from ..utils._param_validation import Interval, validate_params
|
| 42 |
+
from . import get_data_home
|
| 43 |
+
from ._base import RemoteFileMetadata, _fetch_remote, _pkl_filepath
|
| 44 |
+
|
| 45 |
+
# The original data can be found at:
|
| 46 |
+
# https://biodiversityinformatics.amnh.org/open_source/maxent/samples.zip
|
| 47 |
+
SAMPLES = RemoteFileMetadata(
|
| 48 |
+
filename="samples.zip",
|
| 49 |
+
url="https://ndownloader.figshare.com/files/5976075",
|
| 50 |
+
checksum="abb07ad284ac50d9e6d20f1c4211e0fd3c098f7f85955e89d321ee8efe37ac28",
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
# The original data can be found at:
|
| 54 |
+
# https://biodiversityinformatics.amnh.org/open_source/maxent/coverages.zip
|
| 55 |
+
COVERAGES = RemoteFileMetadata(
|
| 56 |
+
filename="coverages.zip",
|
| 57 |
+
url="https://ndownloader.figshare.com/files/5976078",
|
| 58 |
+
checksum="4d862674d72e79d6cee77e63b98651ec7926043ba7d39dcb31329cf3f6073807",
|
| 59 |
+
)
|
| 60 |
+
|
| 61 |
+
DATA_ARCHIVE_NAME = "species_coverage.pkz"
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
logger = logging.getLogger(__name__)
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def _load_coverage(F, header_length=6, dtype=np.int16):
|
| 68 |
+
"""Load a coverage file from an open file object.
|
| 69 |
+
|
| 70 |
+
This will return a numpy array of the given dtype
|
| 71 |
+
"""
|
| 72 |
+
header = [F.readline() for _ in range(header_length)]
|
| 73 |
+
make_tuple = lambda t: (t.split()[0], float(t.split()[1]))
|
| 74 |
+
header = dict([make_tuple(line) for line in header])
|
| 75 |
+
|
| 76 |
+
M = np.loadtxt(F, dtype=dtype)
|
| 77 |
+
nodata = int(header[b"NODATA_value"])
|
| 78 |
+
if nodata != -9999:
|
| 79 |
+
M[nodata] = -9999
|
| 80 |
+
return M
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def _load_csv(F):
|
| 84 |
+
"""Load csv file.
|
| 85 |
+
|
| 86 |
+
Parameters
|
| 87 |
+
----------
|
| 88 |
+
F : file object
|
| 89 |
+
CSV file open in byte mode.
|
| 90 |
+
|
| 91 |
+
Returns
|
| 92 |
+
-------
|
| 93 |
+
rec : np.ndarray
|
| 94 |
+
record array representing the data
|
| 95 |
+
"""
|
| 96 |
+
names = F.readline().decode("ascii").strip().split(",")
|
| 97 |
+
|
| 98 |
+
rec = np.loadtxt(F, skiprows=0, delimiter=",", dtype="S22,f4,f4")
|
| 99 |
+
rec.dtype.names = names
|
| 100 |
+
return rec
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def construct_grids(batch):
|
| 104 |
+
"""Construct the map grid from the batch object
|
| 105 |
+
|
| 106 |
+
Parameters
|
| 107 |
+
----------
|
| 108 |
+
batch : Batch object
|
| 109 |
+
The object returned by :func:`fetch_species_distributions`
|
| 110 |
+
|
| 111 |
+
Returns
|
| 112 |
+
-------
|
| 113 |
+
(xgrid, ygrid) : 1-D arrays
|
| 114 |
+
The grid corresponding to the values in batch.coverages
|
| 115 |
+
"""
|
| 116 |
+
# x,y coordinates for corner cells
|
| 117 |
+
xmin = batch.x_left_lower_corner + batch.grid_size
|
| 118 |
+
xmax = xmin + (batch.Nx * batch.grid_size)
|
| 119 |
+
ymin = batch.y_left_lower_corner + batch.grid_size
|
| 120 |
+
ymax = ymin + (batch.Ny * batch.grid_size)
|
| 121 |
+
|
| 122 |
+
# x coordinates of the grid cells
|
| 123 |
+
xgrid = np.arange(xmin, xmax, batch.grid_size)
|
| 124 |
+
# y coordinates of the grid cells
|
| 125 |
+
ygrid = np.arange(ymin, ymax, batch.grid_size)
|
| 126 |
+
|
| 127 |
+
return (xgrid, ygrid)
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
@validate_params(
|
| 131 |
+
{
|
| 132 |
+
"data_home": [str, PathLike, None],
|
| 133 |
+
"download_if_missing": ["boolean"],
|
| 134 |
+
"n_retries": [Interval(Integral, 1, None, closed="left")],
|
| 135 |
+
"delay": [Interval(Real, 0.0, None, closed="neither")],
|
| 136 |
+
},
|
| 137 |
+
prefer_skip_nested_validation=True,
|
| 138 |
+
)
|
| 139 |
+
def fetch_species_distributions(
|
| 140 |
+
*,
|
| 141 |
+
data_home=None,
|
| 142 |
+
download_if_missing=True,
|
| 143 |
+
n_retries=3,
|
| 144 |
+
delay=1.0,
|
| 145 |
+
):
|
| 146 |
+
"""Loader for species distribution dataset from Phillips et. al. (2006).
|
| 147 |
+
|
| 148 |
+
Read more in the :ref:`User Guide <species_distribution_dataset>`.
|
| 149 |
+
|
| 150 |
+
Parameters
|
| 151 |
+
----------
|
| 152 |
+
data_home : str or path-like, default=None
|
| 153 |
+
Specify another download and cache folder for the datasets. By default
|
| 154 |
+
all scikit-learn data is stored in '~/scikit_learn_data' subfolders.
|
| 155 |
+
|
| 156 |
+
download_if_missing : bool, default=True
|
| 157 |
+
If False, raise an OSError if the data is not locally available
|
| 158 |
+
instead of trying to download the data from the source site.
|
| 159 |
+
|
| 160 |
+
n_retries : int, default=3
|
| 161 |
+
Number of retries when HTTP errors are encountered.
|
| 162 |
+
|
| 163 |
+
.. versionadded:: 1.5
|
| 164 |
+
|
| 165 |
+
delay : float, default=1.0
|
| 166 |
+
Number of seconds between retries.
|
| 167 |
+
|
| 168 |
+
.. versionadded:: 1.5
|
| 169 |
+
|
| 170 |
+
Returns
|
| 171 |
+
-------
|
| 172 |
+
data : :class:`~sklearn.utils.Bunch`
|
| 173 |
+
Dictionary-like object, with the following attributes.
|
| 174 |
+
|
| 175 |
+
coverages : array, shape = [14, 1592, 1212]
|
| 176 |
+
These represent the 14 features measured
|
| 177 |
+
at each point of the map grid.
|
| 178 |
+
The latitude/longitude values for the grid are discussed below.
|
| 179 |
+
Missing data is represented by the value -9999.
|
| 180 |
+
train : record array, shape = (1624,)
|
| 181 |
+
The training points for the data. Each point has three fields:
|
| 182 |
+
|
| 183 |
+
- train['species'] is the species name
|
| 184 |
+
- train['dd long'] is the longitude, in degrees
|
| 185 |
+
- train['dd lat'] is the latitude, in degrees
|
| 186 |
+
test : record array, shape = (620,)
|
| 187 |
+
The test points for the data. Same format as the training data.
|
| 188 |
+
Nx, Ny : integers
|
| 189 |
+
The number of longitudes (x) and latitudes (y) in the grid
|
| 190 |
+
x_left_lower_corner, y_left_lower_corner : floats
|
| 191 |
+
The (x,y) position of the lower-left corner, in degrees
|
| 192 |
+
grid_size : float
|
| 193 |
+
The spacing between points of the grid, in degrees
|
| 194 |
+
|
| 195 |
+
Notes
|
| 196 |
+
-----
|
| 197 |
+
|
| 198 |
+
This dataset represents the geographic distribution of species.
|
| 199 |
+
The dataset is provided by Phillips et. al. (2006).
|
| 200 |
+
|
| 201 |
+
The two species are:
|
| 202 |
+
|
| 203 |
+
- `"Bradypus variegatus"
|
| 204 |
+
<http://www.iucnredlist.org/details/3038/0>`_ ,
|
| 205 |
+
the Brown-throated Sloth.
|
| 206 |
+
|
| 207 |
+
- `"Microryzomys minutus"
|
| 208 |
+
<http://www.iucnredlist.org/details/13408/0>`_ ,
|
| 209 |
+
also known as the Forest Small Rice Rat, a rodent that lives in Peru,
|
| 210 |
+
Colombia, Ecuador, Peru, and Venezuela.
|
| 211 |
+
|
| 212 |
+
References
|
| 213 |
+
----------
|
| 214 |
+
|
| 215 |
+
* `"Maximum entropy modeling of species geographic distributions"
|
| 216 |
+
<http://rob.schapire.net/papers/ecolmod.pdf>`_
|
| 217 |
+
S. J. Phillips, R. P. Anderson, R. E. Schapire - Ecological Modelling,
|
| 218 |
+
190:231-259, 2006.
|
| 219 |
+
|
| 220 |
+
Examples
|
| 221 |
+
--------
|
| 222 |
+
>>> from sklearn.datasets import fetch_species_distributions
|
| 223 |
+
>>> species = fetch_species_distributions()
|
| 224 |
+
>>> species.train[:5]
|
| 225 |
+
array([(b'microryzomys_minutus', -64.7 , -17.85 ),
|
| 226 |
+
(b'microryzomys_minutus', -67.8333, -16.3333),
|
| 227 |
+
(b'microryzomys_minutus', -67.8833, -16.3 ),
|
| 228 |
+
(b'microryzomys_minutus', -67.8 , -16.2667),
|
| 229 |
+
(b'microryzomys_minutus', -67.9833, -15.9 )],
|
| 230 |
+
dtype=[('species', 'S22'), ('dd long', '<f4'), ('dd lat', '<f4')])
|
| 231 |
+
|
| 232 |
+
For a more extended example,
|
| 233 |
+
see :ref:`sphx_glr_auto_examples_applications_plot_species_distribution_modeling.py`
|
| 234 |
+
"""
|
| 235 |
+
data_home = get_data_home(data_home)
|
| 236 |
+
if not exists(data_home):
|
| 237 |
+
makedirs(data_home)
|
| 238 |
+
|
| 239 |
+
# Define parameters for the data files. These should not be changed
|
| 240 |
+
# unless the data model changes. They will be saved in the npz file
|
| 241 |
+
# with the downloaded data.
|
| 242 |
+
extra_params = dict(
|
| 243 |
+
x_left_lower_corner=-94.8,
|
| 244 |
+
Nx=1212,
|
| 245 |
+
y_left_lower_corner=-56.05,
|
| 246 |
+
Ny=1592,
|
| 247 |
+
grid_size=0.05,
|
| 248 |
+
)
|
| 249 |
+
dtype = np.int16
|
| 250 |
+
|
| 251 |
+
archive_path = _pkl_filepath(data_home, DATA_ARCHIVE_NAME)
|
| 252 |
+
|
| 253 |
+
if not exists(archive_path):
|
| 254 |
+
if not download_if_missing:
|
| 255 |
+
raise OSError("Data not found and `download_if_missing` is False")
|
| 256 |
+
logger.info("Downloading species data from %s to %s" % (SAMPLES.url, data_home))
|
| 257 |
+
samples_path = _fetch_remote(
|
| 258 |
+
SAMPLES, dirname=data_home, n_retries=n_retries, delay=delay
|
| 259 |
+
)
|
| 260 |
+
with np.load(samples_path) as X: # samples.zip is a valid npz
|
| 261 |
+
for f in X.files:
|
| 262 |
+
fhandle = BytesIO(X[f])
|
| 263 |
+
if "train" in f:
|
| 264 |
+
train = _load_csv(fhandle)
|
| 265 |
+
if "test" in f:
|
| 266 |
+
test = _load_csv(fhandle)
|
| 267 |
+
remove(samples_path)
|
| 268 |
+
|
| 269 |
+
logger.info(
|
| 270 |
+
"Downloading coverage data from %s to %s" % (COVERAGES.url, data_home)
|
| 271 |
+
)
|
| 272 |
+
coverages_path = _fetch_remote(
|
| 273 |
+
COVERAGES, dirname=data_home, n_retries=n_retries, delay=delay
|
| 274 |
+
)
|
| 275 |
+
with np.load(coverages_path) as X: # coverages.zip is a valid npz
|
| 276 |
+
coverages = []
|
| 277 |
+
for f in X.files:
|
| 278 |
+
fhandle = BytesIO(X[f])
|
| 279 |
+
logger.debug(" - converting {}".format(f))
|
| 280 |
+
coverages.append(_load_coverage(fhandle))
|
| 281 |
+
coverages = np.asarray(coverages, dtype=dtype)
|
| 282 |
+
remove(coverages_path)
|
| 283 |
+
|
| 284 |
+
bunch = Bunch(coverages=coverages, test=test, train=train, **extra_params)
|
| 285 |
+
joblib.dump(bunch, archive_path, compress=9)
|
| 286 |
+
else:
|
| 287 |
+
bunch = joblib.load(archive_path)
|
| 288 |
+
|
| 289 |
+
return bunch
|
miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/datasets/_svmlight_format_fast.pyx
ADDED
|
@@ -0,0 +1,252 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Optimized inner loop of load_svmlight_file.
|
| 2 |
+
#
|
| 3 |
+
# Authors: The scikit-learn developers
|
| 4 |
+
# SPDX-License-Identifier: BSD-3-Clause
|
| 5 |
+
|
| 6 |
+
import array
|
| 7 |
+
from cpython cimport array
|
| 8 |
+
cimport cython
|
| 9 |
+
from libc.string cimport strchr
|
| 10 |
+
|
| 11 |
+
import numpy as np
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
cdef bytes COMMA = u','.encode('ascii')
|
| 15 |
+
cdef bytes COLON = u':'.encode('ascii')
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def _load_svmlight_file(f, dtype, bint multilabel, bint zero_based,
|
| 19 |
+
bint query_id, long long offset, long long length):
|
| 20 |
+
cdef array.array data, indices, indptr
|
| 21 |
+
cdef bytes line
|
| 22 |
+
cdef char *hash_ptr
|
| 23 |
+
cdef char *line_cstr
|
| 24 |
+
cdef int idx, prev_idx
|
| 25 |
+
cdef Py_ssize_t i
|
| 26 |
+
cdef bytes qid_prefix = b'qid'
|
| 27 |
+
cdef Py_ssize_t n_features
|
| 28 |
+
cdef long long offset_max = offset + length if length > 0 else -1
|
| 29 |
+
|
| 30 |
+
# Special-case float32 but use float64 for everything else;
|
| 31 |
+
# the Python code will do further conversions.
|
| 32 |
+
if dtype == np.float32:
|
| 33 |
+
data = array.array("f")
|
| 34 |
+
else:
|
| 35 |
+
dtype = np.float64
|
| 36 |
+
data = array.array("d")
|
| 37 |
+
|
| 38 |
+
indices = array.array("q")
|
| 39 |
+
indptr = array.array("q", [0])
|
| 40 |
+
query = np.arange(0, dtype=np.int64)
|
| 41 |
+
|
| 42 |
+
if multilabel:
|
| 43 |
+
labels = []
|
| 44 |
+
else:
|
| 45 |
+
labels = array.array("d")
|
| 46 |
+
|
| 47 |
+
if offset > 0:
|
| 48 |
+
f.seek(offset)
|
| 49 |
+
# drop the current line that might be truncated and is to be
|
| 50 |
+
# fetched by another call
|
| 51 |
+
f.readline()
|
| 52 |
+
|
| 53 |
+
for line in f:
|
| 54 |
+
# skip comments
|
| 55 |
+
line_cstr = line
|
| 56 |
+
hash_ptr = strchr(line_cstr, 35) # ASCII value of '#' is 35
|
| 57 |
+
if hash_ptr != NULL:
|
| 58 |
+
line = line[:hash_ptr - line_cstr]
|
| 59 |
+
|
| 60 |
+
line_parts = line.split()
|
| 61 |
+
if len(line_parts) == 0:
|
| 62 |
+
continue
|
| 63 |
+
|
| 64 |
+
target, features = line_parts[0], line_parts[1:]
|
| 65 |
+
if multilabel:
|
| 66 |
+
if COLON in target:
|
| 67 |
+
target, features = [], line_parts[0:]
|
| 68 |
+
else:
|
| 69 |
+
target = [float(y) for y in target.split(COMMA)]
|
| 70 |
+
target.sort()
|
| 71 |
+
labels.append(tuple(target))
|
| 72 |
+
else:
|
| 73 |
+
array.resize_smart(labels, len(labels) + 1)
|
| 74 |
+
labels[len(labels) - 1] = float(target)
|
| 75 |
+
|
| 76 |
+
prev_idx = -1
|
| 77 |
+
n_features = len(features)
|
| 78 |
+
if n_features and features[0].startswith(qid_prefix):
|
| 79 |
+
_, value = features[0].split(COLON, 1)
|
| 80 |
+
if query_id:
|
| 81 |
+
query.resize(len(query) + 1)
|
| 82 |
+
query[len(query) - 1] = np.int64(value)
|
| 83 |
+
features.pop(0)
|
| 84 |
+
n_features -= 1
|
| 85 |
+
|
| 86 |
+
for i in range(0, n_features):
|
| 87 |
+
idx_s, value = features[i].split(COLON, 1)
|
| 88 |
+
idx = int(idx_s)
|
| 89 |
+
if idx < 0 or not zero_based and idx == 0:
|
| 90 |
+
raise ValueError(
|
| 91 |
+
"Invalid index %d in SVMlight/LibSVM data file." % idx)
|
| 92 |
+
if idx <= prev_idx:
|
| 93 |
+
raise ValueError("Feature indices in SVMlight/LibSVM data "
|
| 94 |
+
"file should be sorted and unique.")
|
| 95 |
+
|
| 96 |
+
array.resize_smart(indices, len(indices) + 1)
|
| 97 |
+
indices[len(indices) - 1] = idx
|
| 98 |
+
|
| 99 |
+
array.resize_smart(data, len(data) + 1)
|
| 100 |
+
data[len(data) - 1] = float(value)
|
| 101 |
+
|
| 102 |
+
prev_idx = idx
|
| 103 |
+
|
| 104 |
+
# increment index pointer array size
|
| 105 |
+
array.resize_smart(indptr, len(indptr) + 1)
|
| 106 |
+
indptr[len(indptr) - 1] = len(data)
|
| 107 |
+
|
| 108 |
+
if offset_max != -1 and f.tell() > offset_max:
|
| 109 |
+
# Stop here and let another call deal with the following.
|
| 110 |
+
break
|
| 111 |
+
|
| 112 |
+
return (dtype, data, indices, indptr, labels, query)
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
# Two fused types are defined to be able to
|
| 116 |
+
# use all possible combinations of parameters.
|
| 117 |
+
ctypedef fused int_or_float:
|
| 118 |
+
cython.integral
|
| 119 |
+
cython.floating
|
| 120 |
+
signed long long
|
| 121 |
+
|
| 122 |
+
ctypedef fused double_or_longlong:
|
| 123 |
+
double
|
| 124 |
+
signed long long
|
| 125 |
+
|
| 126 |
+
ctypedef fused int_or_longlong:
|
| 127 |
+
cython.integral
|
| 128 |
+
signed long long
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def get_dense_row_string(
|
| 132 |
+
const int_or_float[:, :] X,
|
| 133 |
+
Py_ssize_t[:] x_inds,
|
| 134 |
+
double_or_longlong[:] x_vals,
|
| 135 |
+
Py_ssize_t row,
|
| 136 |
+
str value_pattern,
|
| 137 |
+
bint one_based,
|
| 138 |
+
):
|
| 139 |
+
cdef:
|
| 140 |
+
Py_ssize_t row_length = X.shape[1]
|
| 141 |
+
Py_ssize_t x_nz_used = 0
|
| 142 |
+
Py_ssize_t k
|
| 143 |
+
int_or_float val
|
| 144 |
+
|
| 145 |
+
for k in range(row_length):
|
| 146 |
+
val = X[row, k]
|
| 147 |
+
if val == 0:
|
| 148 |
+
continue
|
| 149 |
+
x_inds[x_nz_used] = k
|
| 150 |
+
x_vals[x_nz_used] = <double_or_longlong> val
|
| 151 |
+
x_nz_used += 1
|
| 152 |
+
|
| 153 |
+
reprs = [
|
| 154 |
+
value_pattern % (x_inds[i] + one_based, x_vals[i])
|
| 155 |
+
for i in range(x_nz_used)
|
| 156 |
+
]
|
| 157 |
+
|
| 158 |
+
return " ".join(reprs)
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def get_sparse_row_string(
|
| 162 |
+
int_or_float[:] X_data,
|
| 163 |
+
int[:] X_indptr,
|
| 164 |
+
int[:] X_indices,
|
| 165 |
+
Py_ssize_t row,
|
| 166 |
+
str value_pattern,
|
| 167 |
+
bint one_based,
|
| 168 |
+
):
|
| 169 |
+
cdef:
|
| 170 |
+
Py_ssize_t row_start = X_indptr[row]
|
| 171 |
+
Py_ssize_t row_end = X_indptr[row+1]
|
| 172 |
+
|
| 173 |
+
reprs = [
|
| 174 |
+
value_pattern % (X_indices[i] + one_based, X_data[i])
|
| 175 |
+
for i in range(row_start, row_end)
|
| 176 |
+
]
|
| 177 |
+
|
| 178 |
+
return " ".join(reprs)
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
def _dump_svmlight_file(
|
| 182 |
+
X,
|
| 183 |
+
y,
|
| 184 |
+
f,
|
| 185 |
+
bint multilabel,
|
| 186 |
+
bint one_based,
|
| 187 |
+
int_or_longlong[:] query_id,
|
| 188 |
+
bint X_is_sp,
|
| 189 |
+
bint y_is_sp,
|
| 190 |
+
):
|
| 191 |
+
cdef bint X_is_integral
|
| 192 |
+
cdef bint query_id_is_not_empty = query_id.size > 0
|
| 193 |
+
X_is_integral = X.dtype.kind == "i"
|
| 194 |
+
if X_is_integral:
|
| 195 |
+
value_pattern = "%d:%d"
|
| 196 |
+
else:
|
| 197 |
+
value_pattern = "%d:%.16g"
|
| 198 |
+
if y.dtype.kind == "i":
|
| 199 |
+
label_pattern = "%d"
|
| 200 |
+
else:
|
| 201 |
+
label_pattern = "%.16g"
|
| 202 |
+
|
| 203 |
+
line_pattern = "%s"
|
| 204 |
+
if query_id_is_not_empty:
|
| 205 |
+
line_pattern += " qid:%d"
|
| 206 |
+
line_pattern += " %s\n"
|
| 207 |
+
|
| 208 |
+
cdef:
|
| 209 |
+
Py_ssize_t num_labels = y.shape[1]
|
| 210 |
+
Py_ssize_t x_len = X.shape[0]
|
| 211 |
+
Py_ssize_t row_length = X.shape[1]
|
| 212 |
+
Py_ssize_t i
|
| 213 |
+
Py_ssize_t j
|
| 214 |
+
Py_ssize_t col_start
|
| 215 |
+
Py_ssize_t col_end
|
| 216 |
+
Py_ssize_t[:] x_inds = np.empty(row_length, dtype=np.intp)
|
| 217 |
+
signed long long[:] x_vals_int
|
| 218 |
+
double[:] x_vals_float
|
| 219 |
+
|
| 220 |
+
if not X_is_sp:
|
| 221 |
+
if X_is_integral:
|
| 222 |
+
x_vals_int = np.zeros(row_length, dtype=np.longlong)
|
| 223 |
+
else:
|
| 224 |
+
x_vals_float = np.zeros(row_length, dtype=np.float64)
|
| 225 |
+
|
| 226 |
+
for i in range(x_len):
|
| 227 |
+
if not X_is_sp:
|
| 228 |
+
if X_is_integral:
|
| 229 |
+
s = get_dense_row_string(X, x_inds, x_vals_int, i, value_pattern, one_based)
|
| 230 |
+
else:
|
| 231 |
+
s = get_dense_row_string(X, x_inds, x_vals_float, i, value_pattern, one_based)
|
| 232 |
+
else:
|
| 233 |
+
s = get_sparse_row_string(X.data, X.indptr, X.indices, i, value_pattern, one_based)
|
| 234 |
+
if multilabel:
|
| 235 |
+
if y_is_sp:
|
| 236 |
+
col_start = y.indptr[i]
|
| 237 |
+
col_end = y.indptr[i+1]
|
| 238 |
+
labels_str = ','.join(tuple(label_pattern % y.indices[j] for j in range(col_start, col_end) if y.data[j] != 0))
|
| 239 |
+
else:
|
| 240 |
+
labels_str = ','.join(label_pattern % j for j in range(num_labels) if y[i, j] != 0)
|
| 241 |
+
else:
|
| 242 |
+
if y_is_sp:
|
| 243 |
+
labels_str = label_pattern % y.data[i]
|
| 244 |
+
else:
|
| 245 |
+
labels_str = label_pattern % y[i, 0]
|
| 246 |
+
|
| 247 |
+
if query_id_is_not_empty:
|
| 248 |
+
feat = (labels_str, query_id[i], s)
|
| 249 |
+
else:
|
| 250 |
+
feat = (labels_str, s)
|
| 251 |
+
|
| 252 |
+
f.write((line_pattern % feat).encode("utf-8"))
|
miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/datasets/_svmlight_format_io.py
ADDED
|
@@ -0,0 +1,585 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""This module implements a loader and dumper for the svmlight format
|
| 2 |
+
|
| 3 |
+
This format is a text-based format, with one sample per line. It does
|
| 4 |
+
not store zero valued features hence is suitable for sparse dataset.
|
| 5 |
+
|
| 6 |
+
The first element of each line can be used to store a target variable to
|
| 7 |
+
predict.
|
| 8 |
+
|
| 9 |
+
This format is used as the default format for both svmlight and the
|
| 10 |
+
libsvm command line programs.
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
# Authors: The scikit-learn developers
|
| 14 |
+
# SPDX-License-Identifier: BSD-3-Clause
|
| 15 |
+
|
| 16 |
+
import os.path
|
| 17 |
+
from contextlib import closing
|
| 18 |
+
from numbers import Integral
|
| 19 |
+
|
| 20 |
+
import numpy as np
|
| 21 |
+
import scipy.sparse as sp
|
| 22 |
+
|
| 23 |
+
from .. import __version__
|
| 24 |
+
from ..utils import check_array
|
| 25 |
+
from ..utils._param_validation import HasMethods, Interval, StrOptions, validate_params
|
| 26 |
+
from ._svmlight_format_fast import (
|
| 27 |
+
_dump_svmlight_file,
|
| 28 |
+
_load_svmlight_file,
|
| 29 |
+
)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
@validate_params(
|
| 33 |
+
{
|
| 34 |
+
"f": [
|
| 35 |
+
str,
|
| 36 |
+
Interval(Integral, 0, None, closed="left"),
|
| 37 |
+
os.PathLike,
|
| 38 |
+
HasMethods("read"),
|
| 39 |
+
],
|
| 40 |
+
"n_features": [Interval(Integral, 1, None, closed="left"), None],
|
| 41 |
+
"dtype": "no_validation", # delegate validation to numpy
|
| 42 |
+
"multilabel": ["boolean"],
|
| 43 |
+
"zero_based": ["boolean", StrOptions({"auto"})],
|
| 44 |
+
"query_id": ["boolean"],
|
| 45 |
+
"offset": [Interval(Integral, 0, None, closed="left")],
|
| 46 |
+
"length": [Integral],
|
| 47 |
+
},
|
| 48 |
+
prefer_skip_nested_validation=True,
|
| 49 |
+
)
|
| 50 |
+
def load_svmlight_file(
|
| 51 |
+
f,
|
| 52 |
+
*,
|
| 53 |
+
n_features=None,
|
| 54 |
+
dtype=np.float64,
|
| 55 |
+
multilabel=False,
|
| 56 |
+
zero_based="auto",
|
| 57 |
+
query_id=False,
|
| 58 |
+
offset=0,
|
| 59 |
+
length=-1,
|
| 60 |
+
):
|
| 61 |
+
"""Load datasets in the svmlight / libsvm format into sparse CSR matrix.
|
| 62 |
+
|
| 63 |
+
This format is a text-based format, with one sample per line. It does
|
| 64 |
+
not store zero valued features hence is suitable for sparse dataset.
|
| 65 |
+
|
| 66 |
+
The first element of each line can be used to store a target variable
|
| 67 |
+
to predict.
|
| 68 |
+
|
| 69 |
+
This format is used as the default format for both svmlight and the
|
| 70 |
+
libsvm command line programs.
|
| 71 |
+
|
| 72 |
+
Parsing a text based source can be expensive. When repeatedly
|
| 73 |
+
working on the same dataset, it is recommended to wrap this
|
| 74 |
+
loader with joblib.Memory.cache to store a memmapped backup of the
|
| 75 |
+
CSR results of the first call and benefit from the near instantaneous
|
| 76 |
+
loading of memmapped structures for the subsequent calls.
|
| 77 |
+
|
| 78 |
+
In case the file contains a pairwise preference constraint (known
|
| 79 |
+
as "qid" in the svmlight format) these are ignored unless the
|
| 80 |
+
query_id parameter is set to True. These pairwise preference
|
| 81 |
+
constraints can be used to constraint the combination of samples
|
| 82 |
+
when using pairwise loss functions (as is the case in some
|
| 83 |
+
learning to rank problems) so that only pairs with the same
|
| 84 |
+
query_id value are considered.
|
| 85 |
+
|
| 86 |
+
This implementation is written in Cython and is reasonably fast.
|
| 87 |
+
However, a faster API-compatible loader is also available at:
|
| 88 |
+
https://github.com/mblondel/svmlight-loader
|
| 89 |
+
|
| 90 |
+
Parameters
|
| 91 |
+
----------
|
| 92 |
+
f : str, path-like, file-like or int
|
| 93 |
+
(Path to) a file to load. If a path ends in ".gz" or ".bz2", it will
|
| 94 |
+
be uncompressed on the fly. If an integer is passed, it is assumed to
|
| 95 |
+
be a file descriptor. A file-like or file descriptor will not be closed
|
| 96 |
+
by this function. A file-like object must be opened in binary mode.
|
| 97 |
+
|
| 98 |
+
.. versionchanged:: 1.2
|
| 99 |
+
Path-like objects are now accepted.
|
| 100 |
+
|
| 101 |
+
n_features : int, default=None
|
| 102 |
+
The number of features to use. If None, it will be inferred. This
|
| 103 |
+
argument is useful to load several files that are subsets of a
|
| 104 |
+
bigger sliced dataset: each subset might not have examples of
|
| 105 |
+
every feature, hence the inferred shape might vary from one
|
| 106 |
+
slice to another.
|
| 107 |
+
n_features is only required if ``offset`` or ``length`` are passed a
|
| 108 |
+
non-default value.
|
| 109 |
+
|
| 110 |
+
dtype : numpy data type, default=np.float64
|
| 111 |
+
Data type of dataset to be loaded. This will be the data type of the
|
| 112 |
+
output numpy arrays ``X`` and ``y``.
|
| 113 |
+
|
| 114 |
+
multilabel : bool, default=False
|
| 115 |
+
Samples may have several labels each (see
|
| 116 |
+
https://www.csie.ntu.edu.tw/~cjlin/libsvmtools/datasets/multilabel.html).
|
| 117 |
+
|
| 118 |
+
zero_based : bool or "auto", default="auto"
|
| 119 |
+
Whether column indices in f are zero-based (True) or one-based
|
| 120 |
+
(False). If column indices are one-based, they are transformed to
|
| 121 |
+
zero-based to match Python/NumPy conventions.
|
| 122 |
+
If set to "auto", a heuristic check is applied to determine this from
|
| 123 |
+
the file contents. Both kinds of files occur "in the wild", but they
|
| 124 |
+
are unfortunately not self-identifying. Using "auto" or True should
|
| 125 |
+
always be safe when no ``offset`` or ``length`` is passed.
|
| 126 |
+
If ``offset`` or ``length`` are passed, the "auto" mode falls back
|
| 127 |
+
to ``zero_based=True`` to avoid having the heuristic check yield
|
| 128 |
+
inconsistent results on different segments of the file.
|
| 129 |
+
|
| 130 |
+
query_id : bool, default=False
|
| 131 |
+
If True, will return the query_id array for each file.
|
| 132 |
+
|
| 133 |
+
offset : int, default=0
|
| 134 |
+
Ignore the offset first bytes by seeking forward, then
|
| 135 |
+
discarding the following bytes up until the next new line
|
| 136 |
+
character.
|
| 137 |
+
|
| 138 |
+
length : int, default=-1
|
| 139 |
+
If strictly positive, stop reading any new line of data once the
|
| 140 |
+
position in the file has reached the (offset + length) bytes threshold.
|
| 141 |
+
|
| 142 |
+
Returns
|
| 143 |
+
-------
|
| 144 |
+
X : scipy.sparse matrix of shape (n_samples, n_features)
|
| 145 |
+
The data matrix.
|
| 146 |
+
|
| 147 |
+
y : ndarray of shape (n_samples,), or a list of tuples of length n_samples
|
| 148 |
+
The target. It is a list of tuples when ``multilabel=True``, else a
|
| 149 |
+
ndarray.
|
| 150 |
+
|
| 151 |
+
query_id : array of shape (n_samples,)
|
| 152 |
+
The query_id for each sample. Only returned when query_id is set to
|
| 153 |
+
True.
|
| 154 |
+
|
| 155 |
+
See Also
|
| 156 |
+
--------
|
| 157 |
+
load_svmlight_files : Similar function for loading multiple files in this
|
| 158 |
+
format, enforcing the same number of features/columns on all of them.
|
| 159 |
+
|
| 160 |
+
Examples
|
| 161 |
+
--------
|
| 162 |
+
To use joblib.Memory to cache the svmlight file::
|
| 163 |
+
|
| 164 |
+
from joblib import Memory
|
| 165 |
+
from sklearn.datasets import load_svmlight_file
|
| 166 |
+
mem = Memory("./mycache")
|
| 167 |
+
|
| 168 |
+
@mem.cache
|
| 169 |
+
def get_data():
|
| 170 |
+
data = load_svmlight_file("mysvmlightfile")
|
| 171 |
+
return data[0], data[1]
|
| 172 |
+
|
| 173 |
+
X, y = get_data()
|
| 174 |
+
"""
|
| 175 |
+
return tuple(
|
| 176 |
+
load_svmlight_files(
|
| 177 |
+
[f],
|
| 178 |
+
n_features=n_features,
|
| 179 |
+
dtype=dtype,
|
| 180 |
+
multilabel=multilabel,
|
| 181 |
+
zero_based=zero_based,
|
| 182 |
+
query_id=query_id,
|
| 183 |
+
offset=offset,
|
| 184 |
+
length=length,
|
| 185 |
+
)
|
| 186 |
+
)
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
def _gen_open(f):
|
| 190 |
+
if isinstance(f, int): # file descriptor
|
| 191 |
+
return open(f, "rb", closefd=False)
|
| 192 |
+
elif isinstance(f, os.PathLike):
|
| 193 |
+
f = os.fspath(f)
|
| 194 |
+
elif not isinstance(f, str):
|
| 195 |
+
raise TypeError("expected {str, int, path-like, file-like}, got %s" % type(f))
|
| 196 |
+
|
| 197 |
+
_, ext = os.path.splitext(f)
|
| 198 |
+
if ext == ".gz":
|
| 199 |
+
import gzip
|
| 200 |
+
|
| 201 |
+
return gzip.open(f, "rb")
|
| 202 |
+
elif ext == ".bz2":
|
| 203 |
+
from bz2 import BZ2File
|
| 204 |
+
|
| 205 |
+
return BZ2File(f, "rb")
|
| 206 |
+
else:
|
| 207 |
+
return open(f, "rb")
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
def _open_and_load(f, dtype, multilabel, zero_based, query_id, offset=0, length=-1):
|
| 211 |
+
if hasattr(f, "read"):
|
| 212 |
+
actual_dtype, data, ind, indptr, labels, query = _load_svmlight_file(
|
| 213 |
+
f, dtype, multilabel, zero_based, query_id, offset, length
|
| 214 |
+
)
|
| 215 |
+
else:
|
| 216 |
+
with closing(_gen_open(f)) as f:
|
| 217 |
+
actual_dtype, data, ind, indptr, labels, query = _load_svmlight_file(
|
| 218 |
+
f, dtype, multilabel, zero_based, query_id, offset, length
|
| 219 |
+
)
|
| 220 |
+
|
| 221 |
+
# convert from array.array, give data the right dtype
|
| 222 |
+
if not multilabel:
|
| 223 |
+
labels = np.frombuffer(labels, np.float64)
|
| 224 |
+
data = np.frombuffer(data, actual_dtype)
|
| 225 |
+
indices = np.frombuffer(ind, np.longlong)
|
| 226 |
+
indptr = np.frombuffer(indptr, dtype=np.longlong) # never empty
|
| 227 |
+
query = np.frombuffer(query, np.int64)
|
| 228 |
+
|
| 229 |
+
data = np.asarray(data, dtype=dtype) # no-op for float{32,64}
|
| 230 |
+
return data, indices, indptr, labels, query
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
@validate_params(
|
| 234 |
+
{
|
| 235 |
+
"files": [
|
| 236 |
+
"array-like",
|
| 237 |
+
str,
|
| 238 |
+
os.PathLike,
|
| 239 |
+
HasMethods("read"),
|
| 240 |
+
Interval(Integral, 0, None, closed="left"),
|
| 241 |
+
],
|
| 242 |
+
"n_features": [Interval(Integral, 1, None, closed="left"), None],
|
| 243 |
+
"dtype": "no_validation", # delegate validation to numpy
|
| 244 |
+
"multilabel": ["boolean"],
|
| 245 |
+
"zero_based": ["boolean", StrOptions({"auto"})],
|
| 246 |
+
"query_id": ["boolean"],
|
| 247 |
+
"offset": [Interval(Integral, 0, None, closed="left")],
|
| 248 |
+
"length": [Integral],
|
| 249 |
+
},
|
| 250 |
+
prefer_skip_nested_validation=True,
|
| 251 |
+
)
|
| 252 |
+
def load_svmlight_files(
|
| 253 |
+
files,
|
| 254 |
+
*,
|
| 255 |
+
n_features=None,
|
| 256 |
+
dtype=np.float64,
|
| 257 |
+
multilabel=False,
|
| 258 |
+
zero_based="auto",
|
| 259 |
+
query_id=False,
|
| 260 |
+
offset=0,
|
| 261 |
+
length=-1,
|
| 262 |
+
):
|
| 263 |
+
"""Load dataset from multiple files in SVMlight format.
|
| 264 |
+
|
| 265 |
+
This function is equivalent to mapping load_svmlight_file over a list of
|
| 266 |
+
files, except that the results are concatenated into a single, flat list
|
| 267 |
+
and the samples vectors are constrained to all have the same number of
|
| 268 |
+
features.
|
| 269 |
+
|
| 270 |
+
In case the file contains a pairwise preference constraint (known
|
| 271 |
+
as "qid" in the svmlight format) these are ignored unless the
|
| 272 |
+
query_id parameter is set to True. These pairwise preference
|
| 273 |
+
constraints can be used to constraint the combination of samples
|
| 274 |
+
when using pairwise loss functions (as is the case in some
|
| 275 |
+
learning to rank problems) so that only pairs with the same
|
| 276 |
+
query_id value are considered.
|
| 277 |
+
|
| 278 |
+
Parameters
|
| 279 |
+
----------
|
| 280 |
+
files : array-like, dtype=str, path-like, file-like or int
|
| 281 |
+
(Paths of) files to load. If a path ends in ".gz" or ".bz2", it will
|
| 282 |
+
be uncompressed on the fly. If an integer is passed, it is assumed to
|
| 283 |
+
be a file descriptor. File-likes and file descriptors will not be
|
| 284 |
+
closed by this function. File-like objects must be opened in binary
|
| 285 |
+
mode.
|
| 286 |
+
|
| 287 |
+
.. versionchanged:: 1.2
|
| 288 |
+
Path-like objects are now accepted.
|
| 289 |
+
|
| 290 |
+
n_features : int, default=None
|
| 291 |
+
The number of features to use. If None, it will be inferred from the
|
| 292 |
+
maximum column index occurring in any of the files.
|
| 293 |
+
|
| 294 |
+
This can be set to a higher value than the actual number of features
|
| 295 |
+
in any of the input files, but setting it to a lower value will cause
|
| 296 |
+
an exception to be raised.
|
| 297 |
+
|
| 298 |
+
dtype : numpy data type, default=np.float64
|
| 299 |
+
Data type of dataset to be loaded. This will be the data type of the
|
| 300 |
+
output numpy arrays ``X`` and ``y``.
|
| 301 |
+
|
| 302 |
+
multilabel : bool, default=False
|
| 303 |
+
Samples may have several labels each (see
|
| 304 |
+
https://www.csie.ntu.edu.tw/~cjlin/libsvmtools/datasets/multilabel.html).
|
| 305 |
+
|
| 306 |
+
zero_based : bool or "auto", default="auto"
|
| 307 |
+
Whether column indices in f are zero-based (True) or one-based
|
| 308 |
+
(False). If column indices are one-based, they are transformed to
|
| 309 |
+
zero-based to match Python/NumPy conventions.
|
| 310 |
+
If set to "auto", a heuristic check is applied to determine this from
|
| 311 |
+
the file contents. Both kinds of files occur "in the wild", but they
|
| 312 |
+
are unfortunately not self-identifying. Using "auto" or True should
|
| 313 |
+
always be safe when no offset or length is passed.
|
| 314 |
+
If offset or length are passed, the "auto" mode falls back
|
| 315 |
+
to zero_based=True to avoid having the heuristic check yield
|
| 316 |
+
inconsistent results on different segments of the file.
|
| 317 |
+
|
| 318 |
+
query_id : bool, default=False
|
| 319 |
+
If True, will return the query_id array for each file.
|
| 320 |
+
|
| 321 |
+
offset : int, default=0
|
| 322 |
+
Ignore the offset first bytes by seeking forward, then
|
| 323 |
+
discarding the following bytes up until the next new line
|
| 324 |
+
character.
|
| 325 |
+
|
| 326 |
+
length : int, default=-1
|
| 327 |
+
If strictly positive, stop reading any new line of data once the
|
| 328 |
+
position in the file has reached the (offset + length) bytes threshold.
|
| 329 |
+
|
| 330 |
+
Returns
|
| 331 |
+
-------
|
| 332 |
+
[X1, y1, ..., Xn, yn] or [X1, y1, q1, ..., Xn, yn, qn]: list of arrays
|
| 333 |
+
Each (Xi, yi) pair is the result from load_svmlight_file(files[i]).
|
| 334 |
+
If query_id is set to True, this will return instead (Xi, yi, qi)
|
| 335 |
+
triplets.
|
| 336 |
+
|
| 337 |
+
See Also
|
| 338 |
+
--------
|
| 339 |
+
load_svmlight_file: Similar function for loading a single file in this
|
| 340 |
+
format.
|
| 341 |
+
|
| 342 |
+
Notes
|
| 343 |
+
-----
|
| 344 |
+
When fitting a model to a matrix X_train and evaluating it against a
|
| 345 |
+
matrix X_test, it is essential that X_train and X_test have the same
|
| 346 |
+
number of features (X_train.shape[1] == X_test.shape[1]). This may not
|
| 347 |
+
be the case if you load the files individually with load_svmlight_file.
|
| 348 |
+
|
| 349 |
+
Examples
|
| 350 |
+
--------
|
| 351 |
+
To use joblib.Memory to cache the svmlight file::
|
| 352 |
+
|
| 353 |
+
from joblib import Memory
|
| 354 |
+
from sklearn.datasets import load_svmlight_file
|
| 355 |
+
mem = Memory("./mycache")
|
| 356 |
+
|
| 357 |
+
@mem.cache
|
| 358 |
+
def get_data():
|
| 359 |
+
data_train, target_train, data_test, target_test = load_svmlight_files(
|
| 360 |
+
["svmlight_file_train", "svmlight_file_test"]
|
| 361 |
+
)
|
| 362 |
+
return data_train, target_train, data_test, target_test
|
| 363 |
+
|
| 364 |
+
X_train, y_train, X_test, y_test = get_data()
|
| 365 |
+
"""
|
| 366 |
+
if (offset != 0 or length > 0) and zero_based == "auto":
|
| 367 |
+
# disable heuristic search to avoid getting inconsistent results on
|
| 368 |
+
# different segments of the file
|
| 369 |
+
zero_based = True
|
| 370 |
+
|
| 371 |
+
if (offset != 0 or length > 0) and n_features is None:
|
| 372 |
+
raise ValueError("n_features is required when offset or length is specified.")
|
| 373 |
+
|
| 374 |
+
r = [
|
| 375 |
+
_open_and_load(
|
| 376 |
+
f,
|
| 377 |
+
dtype,
|
| 378 |
+
multilabel,
|
| 379 |
+
bool(zero_based),
|
| 380 |
+
bool(query_id),
|
| 381 |
+
offset=offset,
|
| 382 |
+
length=length,
|
| 383 |
+
)
|
| 384 |
+
for f in files
|
| 385 |
+
]
|
| 386 |
+
|
| 387 |
+
if zero_based is False or (
|
| 388 |
+
zero_based == "auto" and all(len(tmp[1]) and np.min(tmp[1]) > 0 for tmp in r)
|
| 389 |
+
):
|
| 390 |
+
for _, indices, _, _, _ in r:
|
| 391 |
+
indices -= 1
|
| 392 |
+
|
| 393 |
+
n_f = max(ind[1].max() if len(ind[1]) else 0 for ind in r) + 1
|
| 394 |
+
|
| 395 |
+
if n_features is None:
|
| 396 |
+
n_features = n_f
|
| 397 |
+
elif n_features < n_f:
|
| 398 |
+
raise ValueError(
|
| 399 |
+
"n_features was set to {}, but input file contains {} features".format(
|
| 400 |
+
n_features, n_f
|
| 401 |
+
)
|
| 402 |
+
)
|
| 403 |
+
|
| 404 |
+
result = []
|
| 405 |
+
for data, indices, indptr, y, query_values in r:
|
| 406 |
+
shape = (indptr.shape[0] - 1, n_features)
|
| 407 |
+
X = sp.csr_matrix((data, indices, indptr), shape)
|
| 408 |
+
X.sort_indices()
|
| 409 |
+
result += X, y
|
| 410 |
+
if query_id:
|
| 411 |
+
result.append(query_values)
|
| 412 |
+
|
| 413 |
+
return result
|
| 414 |
+
|
| 415 |
+
|
| 416 |
+
def _dump_svmlight(X, y, f, multilabel, one_based, comment, query_id):
|
| 417 |
+
if comment:
|
| 418 |
+
f.write(
|
| 419 |
+
(
|
| 420 |
+
"# Generated by dump_svmlight_file from scikit-learn %s\n" % __version__
|
| 421 |
+
).encode()
|
| 422 |
+
)
|
| 423 |
+
f.write(
|
| 424 |
+
("# Column indices are %s-based\n" % ["zero", "one"][one_based]).encode()
|
| 425 |
+
)
|
| 426 |
+
|
| 427 |
+
f.write(b"#\n")
|
| 428 |
+
f.writelines(b"# %s\n" % line for line in comment.splitlines())
|
| 429 |
+
X_is_sp = sp.issparse(X)
|
| 430 |
+
y_is_sp = sp.issparse(y)
|
| 431 |
+
if not multilabel and not y_is_sp:
|
| 432 |
+
y = y[:, np.newaxis]
|
| 433 |
+
_dump_svmlight_file(
|
| 434 |
+
X,
|
| 435 |
+
y,
|
| 436 |
+
f,
|
| 437 |
+
multilabel,
|
| 438 |
+
one_based,
|
| 439 |
+
query_id,
|
| 440 |
+
X_is_sp,
|
| 441 |
+
y_is_sp,
|
| 442 |
+
)
|
| 443 |
+
|
| 444 |
+
|
| 445 |
+
@validate_params(
|
| 446 |
+
{
|
| 447 |
+
"X": ["array-like", "sparse matrix"],
|
| 448 |
+
"y": ["array-like", "sparse matrix"],
|
| 449 |
+
"f": [str, HasMethods(["write"])],
|
| 450 |
+
"zero_based": ["boolean"],
|
| 451 |
+
"comment": [str, bytes, None],
|
| 452 |
+
"query_id": ["array-like", None],
|
| 453 |
+
"multilabel": ["boolean"],
|
| 454 |
+
},
|
| 455 |
+
prefer_skip_nested_validation=True,
|
| 456 |
+
)
|
| 457 |
+
def dump_svmlight_file(
|
| 458 |
+
X,
|
| 459 |
+
y,
|
| 460 |
+
f,
|
| 461 |
+
*,
|
| 462 |
+
zero_based=True,
|
| 463 |
+
comment=None,
|
| 464 |
+
query_id=None,
|
| 465 |
+
multilabel=False,
|
| 466 |
+
):
|
| 467 |
+
"""Dump the dataset in svmlight / libsvm file format.
|
| 468 |
+
|
| 469 |
+
This format is a text-based format, with one sample per line. It does
|
| 470 |
+
not store zero valued features hence is suitable for sparse dataset.
|
| 471 |
+
|
| 472 |
+
The first element of each line can be used to store a target variable
|
| 473 |
+
to predict.
|
| 474 |
+
|
| 475 |
+
Parameters
|
| 476 |
+
----------
|
| 477 |
+
X : {array-like, sparse matrix} of shape (n_samples, n_features)
|
| 478 |
+
Training vectors, where `n_samples` is the number of samples and
|
| 479 |
+
`n_features` is the number of features.
|
| 480 |
+
|
| 481 |
+
y : {array-like, sparse matrix}, shape = (n_samples,) or (n_samples, n_labels)
|
| 482 |
+
Target values. Class labels must be an
|
| 483 |
+
integer or float, or array-like objects of integer or float for
|
| 484 |
+
multilabel classifications.
|
| 485 |
+
|
| 486 |
+
f : str or file-like in binary mode
|
| 487 |
+
If string, specifies the path that will contain the data.
|
| 488 |
+
If file-like, data will be written to f. f should be opened in binary
|
| 489 |
+
mode.
|
| 490 |
+
|
| 491 |
+
zero_based : bool, default=True
|
| 492 |
+
Whether column indices should be written zero-based (True) or one-based
|
| 493 |
+
(False).
|
| 494 |
+
|
| 495 |
+
comment : str or bytes, default=None
|
| 496 |
+
Comment to insert at the top of the file. This should be either a
|
| 497 |
+
Unicode string, which will be encoded as UTF-8, or an ASCII byte
|
| 498 |
+
string.
|
| 499 |
+
If a comment is given, then it will be preceded by one that identifies
|
| 500 |
+
the file as having been dumped by scikit-learn. Note that not all
|
| 501 |
+
tools grok comments in SVMlight files.
|
| 502 |
+
|
| 503 |
+
query_id : array-like of shape (n_samples,), default=None
|
| 504 |
+
Array containing pairwise preference constraints (qid in svmlight
|
| 505 |
+
format).
|
| 506 |
+
|
| 507 |
+
multilabel : bool, default=False
|
| 508 |
+
Samples may have several labels each (see
|
| 509 |
+
https://www.csie.ntu.edu.tw/~cjlin/libsvmtools/datasets/multilabel.html).
|
| 510 |
+
|
| 511 |
+
.. versionadded:: 0.17
|
| 512 |
+
parameter `multilabel` to support multilabel datasets.
|
| 513 |
+
|
| 514 |
+
Examples
|
| 515 |
+
--------
|
| 516 |
+
>>> from sklearn.datasets import dump_svmlight_file, make_classification
|
| 517 |
+
>>> X, y = make_classification(random_state=0)
|
| 518 |
+
>>> output_file = "my_dataset.svmlight"
|
| 519 |
+
>>> dump_svmlight_file(X, y, output_file) # doctest: +SKIP
|
| 520 |
+
"""
|
| 521 |
+
if comment is not None:
|
| 522 |
+
# Convert comment string to list of lines in UTF-8.
|
| 523 |
+
# If a byte string is passed, then check whether it's ASCII;
|
| 524 |
+
# if a user wants to get fancy, they'll have to decode themselves.
|
| 525 |
+
if isinstance(comment, bytes):
|
| 526 |
+
comment.decode("ascii") # just for the exception
|
| 527 |
+
else:
|
| 528 |
+
comment = comment.encode("utf-8")
|
| 529 |
+
if b"\0" in comment:
|
| 530 |
+
raise ValueError("comment string contains NUL byte")
|
| 531 |
+
|
| 532 |
+
yval = check_array(y, accept_sparse="csr", ensure_2d=False)
|
| 533 |
+
if sp.issparse(yval):
|
| 534 |
+
if yval.shape[1] != 1 and not multilabel:
|
| 535 |
+
raise ValueError(
|
| 536 |
+
"expected y of shape (n_samples, 1), got %r" % (yval.shape,)
|
| 537 |
+
)
|
| 538 |
+
else:
|
| 539 |
+
if yval.ndim != 1 and not multilabel:
|
| 540 |
+
raise ValueError("expected y of shape (n_samples,), got %r" % (yval.shape,))
|
| 541 |
+
|
| 542 |
+
Xval = check_array(X, accept_sparse="csr")
|
| 543 |
+
if Xval.shape[0] != yval.shape[0]:
|
| 544 |
+
raise ValueError(
|
| 545 |
+
"X.shape[0] and y.shape[0] should be the same, got %r and %r instead."
|
| 546 |
+
% (Xval.shape[0], yval.shape[0])
|
| 547 |
+
)
|
| 548 |
+
|
| 549 |
+
# We had some issues with CSR matrices with unsorted indices (e.g. #1501),
|
| 550 |
+
# so sort them here, but first make sure we don't modify the user's X.
|
| 551 |
+
# TODO We can do this cheaper; sorted_indices copies the whole matrix.
|
| 552 |
+
if yval is y and hasattr(yval, "sorted_indices"):
|
| 553 |
+
y = yval.sorted_indices()
|
| 554 |
+
else:
|
| 555 |
+
y = yval
|
| 556 |
+
if hasattr(y, "sort_indices"):
|
| 557 |
+
y.sort_indices()
|
| 558 |
+
|
| 559 |
+
if Xval is X and hasattr(Xval, "sorted_indices"):
|
| 560 |
+
X = Xval.sorted_indices()
|
| 561 |
+
else:
|
| 562 |
+
X = Xval
|
| 563 |
+
if hasattr(X, "sort_indices"):
|
| 564 |
+
X.sort_indices()
|
| 565 |
+
|
| 566 |
+
if query_id is None:
|
| 567 |
+
# NOTE: query_id is passed to Cython functions using a fused type on query_id.
|
| 568 |
+
# Yet as of Cython>=3.0, memory views can't be None otherwise the runtime
|
| 569 |
+
# would not known which concrete implementation to dispatch the Python call to.
|
| 570 |
+
# TODO: simplify interfaces and implementations in _svmlight_format_fast.pyx.
|
| 571 |
+
query_id = np.array([], dtype=np.int32)
|
| 572 |
+
else:
|
| 573 |
+
query_id = np.asarray(query_id)
|
| 574 |
+
if query_id.shape[0] != y.shape[0]:
|
| 575 |
+
raise ValueError(
|
| 576 |
+
"expected query_id of shape (n_samples,), got %r" % (query_id.shape,)
|
| 577 |
+
)
|
| 578 |
+
|
| 579 |
+
one_based = not zero_based
|
| 580 |
+
|
| 581 |
+
if hasattr(f, "write"):
|
| 582 |
+
_dump_svmlight(X, y, f, multilabel, one_based, comment, query_id)
|
| 583 |
+
else:
|
| 584 |
+
with open(f, "wb") as f:
|
| 585 |
+
_dump_svmlight(X, y, f, multilabel, one_based, comment, query_id)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/datasets/_twenty_newsgroups.py
ADDED
|
@@ -0,0 +1,625 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
"""Caching loader for the 20 newsgroups text classification dataset.
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
The description of the dataset is available on the official website at:
|
| 5 |
+
|
| 6 |
+
http://people.csail.mit.edu/jrennie/20Newsgroups/
|
| 7 |
+
|
| 8 |
+
Quoting the introduction:
|
| 9 |
+
|
| 10 |
+
The 20 Newsgroups data set is a collection of approximately 20,000
|
| 11 |
+
newsgroup documents, partitioned (nearly) evenly across 20 different
|
| 12 |
+
newsgroups. To the best of my knowledge, it was originally collected
|
| 13 |
+
by Ken Lang, probably for his Newsweeder: Learning to filter netnews
|
| 14 |
+
paper, though he does not explicitly mention this collection. The 20
|
| 15 |
+
newsgroups collection has become a popular data set for experiments
|
| 16 |
+
in text applications of machine learning techniques, such as text
|
| 17 |
+
classification and text clustering.
|
| 18 |
+
|
| 19 |
+
This dataset loader will download the recommended "by date" variant of the
|
| 20 |
+
dataset and which features a point in time split between the train and
|
| 21 |
+
test sets. The compressed dataset size is around 14 Mb compressed. Once
|
| 22 |
+
uncompressed the train set is 52 MB and the test set is 34 MB.
|
| 23 |
+
"""
|
| 24 |
+
|
| 25 |
+
# Authors: The scikit-learn developers
|
| 26 |
+
# SPDX-License-Identifier: BSD-3-Clause
|
| 27 |
+
|
| 28 |
+
import codecs
|
| 29 |
+
import logging
|
| 30 |
+
import os
|
| 31 |
+
import pickle
|
| 32 |
+
import re
|
| 33 |
+
import shutil
|
| 34 |
+
import tarfile
|
| 35 |
+
from contextlib import suppress
|
| 36 |
+
from numbers import Integral, Real
|
| 37 |
+
|
| 38 |
+
import joblib
|
| 39 |
+
import numpy as np
|
| 40 |
+
import scipy.sparse as sp
|
| 41 |
+
|
| 42 |
+
from .. import preprocessing
|
| 43 |
+
from ..feature_extraction.text import CountVectorizer
|
| 44 |
+
from ..utils import Bunch, check_random_state
|
| 45 |
+
from ..utils._param_validation import Interval, StrOptions, validate_params
|
| 46 |
+
from ..utils.fixes import tarfile_extractall
|
| 47 |
+
from . import get_data_home, load_files
|
| 48 |
+
from ._base import (
|
| 49 |
+
RemoteFileMetadata,
|
| 50 |
+
_convert_data_dataframe,
|
| 51 |
+
_fetch_remote,
|
| 52 |
+
_pkl_filepath,
|
| 53 |
+
load_descr,
|
| 54 |
+
)
|
| 55 |
+
|
| 56 |
+
logger = logging.getLogger(__name__)
|
| 57 |
+
|
| 58 |
+
# The original data can be found at:
|
| 59 |
+
# https://people.csail.mit.edu/jrennie/20Newsgroups/20news-bydate.tar.gz
|
| 60 |
+
ARCHIVE = RemoteFileMetadata(
|
| 61 |
+
filename="20news-bydate.tar.gz",
|
| 62 |
+
url="https://ndownloader.figshare.com/files/5975967",
|
| 63 |
+
checksum="8f1b2514ca22a5ade8fbb9cfa5727df95fa587f4c87b786e15c759fa66d95610",
|
| 64 |
+
)
|
| 65 |
+
|
| 66 |
+
CACHE_NAME = "20news-bydate.pkz"
|
| 67 |
+
TRAIN_FOLDER = "20news-bydate-train"
|
| 68 |
+
TEST_FOLDER = "20news-bydate-test"
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def _download_20newsgroups(target_dir, cache_path, n_retries, delay):
|
| 72 |
+
"""Download the 20 newsgroups data and stored it as a zipped pickle."""
|
| 73 |
+
train_path = os.path.join(target_dir, TRAIN_FOLDER)
|
| 74 |
+
test_path = os.path.join(target_dir, TEST_FOLDER)
|
| 75 |
+
|
| 76 |
+
os.makedirs(target_dir, exist_ok=True)
|
| 77 |
+
|
| 78 |
+
logger.info("Downloading dataset from %s (14 MB)", ARCHIVE.url)
|
| 79 |
+
archive_path = _fetch_remote(
|
| 80 |
+
ARCHIVE, dirname=target_dir, n_retries=n_retries, delay=delay
|
| 81 |
+
)
|
| 82 |
+
|
| 83 |
+
logger.debug("Decompressing %s", archive_path)
|
| 84 |
+
with tarfile.open(archive_path, "r:gz") as fp:
|
| 85 |
+
tarfile_extractall(fp, path=target_dir)
|
| 86 |
+
|
| 87 |
+
with suppress(FileNotFoundError):
|
| 88 |
+
os.remove(archive_path)
|
| 89 |
+
|
| 90 |
+
# Store a zipped pickle
|
| 91 |
+
cache = dict(
|
| 92 |
+
train=load_files(train_path, encoding="latin1"),
|
| 93 |
+
test=load_files(test_path, encoding="latin1"),
|
| 94 |
+
)
|
| 95 |
+
compressed_content = codecs.encode(pickle.dumps(cache), "zlib_codec")
|
| 96 |
+
with open(cache_path, "wb") as f:
|
| 97 |
+
f.write(compressed_content)
|
| 98 |
+
|
| 99 |
+
shutil.rmtree(target_dir)
|
| 100 |
+
return cache
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def strip_newsgroup_header(text):
|
| 104 |
+
"""
|
| 105 |
+
Given text in "news" format, strip the headers, by removing everything
|
| 106 |
+
before the first blank line.
|
| 107 |
+
|
| 108 |
+
Parameters
|
| 109 |
+
----------
|
| 110 |
+
text : str
|
| 111 |
+
The text from which to remove the signature block.
|
| 112 |
+
"""
|
| 113 |
+
_before, _blankline, after = text.partition("\n\n")
|
| 114 |
+
return after
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
_QUOTE_RE = re.compile(
|
| 118 |
+
r"(writes in|writes:|wrote:|says:|said:|^In article|^Quoted from|^\||^>)"
|
| 119 |
+
)
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def strip_newsgroup_quoting(text):
|
| 123 |
+
"""
|
| 124 |
+
Given text in "news" format, strip lines beginning with the quote
|
| 125 |
+
characters > or |, plus lines that often introduce a quoted section
|
| 126 |
+
(for example, because they contain the string 'writes:'.)
|
| 127 |
+
|
| 128 |
+
Parameters
|
| 129 |
+
----------
|
| 130 |
+
text : str
|
| 131 |
+
The text from which to remove the signature block.
|
| 132 |
+
"""
|
| 133 |
+
good_lines = [line for line in text.split("\n") if not _QUOTE_RE.search(line)]
|
| 134 |
+
return "\n".join(good_lines)
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def strip_newsgroup_footer(text):
|
| 138 |
+
"""
|
| 139 |
+
Given text in "news" format, attempt to remove a signature block.
|
| 140 |
+
|
| 141 |
+
As a rough heuristic, we assume that signatures are set apart by either
|
| 142 |
+
a blank line or a line made of hyphens, and that it is the last such line
|
| 143 |
+
in the file (disregarding blank lines at the end).
|
| 144 |
+
|
| 145 |
+
Parameters
|
| 146 |
+
----------
|
| 147 |
+
text : str
|
| 148 |
+
The text from which to remove the signature block.
|
| 149 |
+
"""
|
| 150 |
+
lines = text.strip().split("\n")
|
| 151 |
+
for line_num in range(len(lines) - 1, -1, -1):
|
| 152 |
+
line = lines[line_num]
|
| 153 |
+
if line.strip().strip("-") == "":
|
| 154 |
+
break
|
| 155 |
+
|
| 156 |
+
if line_num > 0:
|
| 157 |
+
return "\n".join(lines[:line_num])
|
| 158 |
+
else:
|
| 159 |
+
return text
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
@validate_params(
|
| 163 |
+
{
|
| 164 |
+
"data_home": [str, os.PathLike, None],
|
| 165 |
+
"subset": [StrOptions({"train", "test", "all"})],
|
| 166 |
+
"categories": ["array-like", None],
|
| 167 |
+
"shuffle": ["boolean"],
|
| 168 |
+
"random_state": ["random_state"],
|
| 169 |
+
"remove": [tuple],
|
| 170 |
+
"download_if_missing": ["boolean"],
|
| 171 |
+
"return_X_y": ["boolean"],
|
| 172 |
+
"n_retries": [Interval(Integral, 1, None, closed="left")],
|
| 173 |
+
"delay": [Interval(Real, 0.0, None, closed="neither")],
|
| 174 |
+
},
|
| 175 |
+
prefer_skip_nested_validation=True,
|
| 176 |
+
)
|
| 177 |
+
def fetch_20newsgroups(
|
| 178 |
+
*,
|
| 179 |
+
data_home=None,
|
| 180 |
+
subset="train",
|
| 181 |
+
categories=None,
|
| 182 |
+
shuffle=True,
|
| 183 |
+
random_state=42,
|
| 184 |
+
remove=(),
|
| 185 |
+
download_if_missing=True,
|
| 186 |
+
return_X_y=False,
|
| 187 |
+
n_retries=3,
|
| 188 |
+
delay=1.0,
|
| 189 |
+
):
|
| 190 |
+
"""Load the filenames and data from the 20 newsgroups dataset \
|
| 191 |
+
(classification).
|
| 192 |
+
|
| 193 |
+
Download it if necessary.
|
| 194 |
+
|
| 195 |
+
================= ==========
|
| 196 |
+
Classes 20
|
| 197 |
+
Samples total 18846
|
| 198 |
+
Dimensionality 1
|
| 199 |
+
Features text
|
| 200 |
+
================= ==========
|
| 201 |
+
|
| 202 |
+
Read more in the :ref:`User Guide <20newsgroups_dataset>`.
|
| 203 |
+
|
| 204 |
+
Parameters
|
| 205 |
+
----------
|
| 206 |
+
data_home : str or path-like, default=None
|
| 207 |
+
Specify a download and cache folder for the datasets. If None,
|
| 208 |
+
all scikit-learn data is stored in '~/scikit_learn_data' subfolders.
|
| 209 |
+
|
| 210 |
+
subset : {'train', 'test', 'all'}, default='train'
|
| 211 |
+
Select the dataset to load: 'train' for the training set, 'test'
|
| 212 |
+
for the test set, 'all' for both, with shuffled ordering.
|
| 213 |
+
|
| 214 |
+
categories : array-like, dtype=str, default=None
|
| 215 |
+
If None (default), load all the categories.
|
| 216 |
+
If not None, list of category names to load (other categories
|
| 217 |
+
ignored).
|
| 218 |
+
|
| 219 |
+
shuffle : bool, default=True
|
| 220 |
+
Whether or not to shuffle the data: might be important for models that
|
| 221 |
+
make the assumption that the samples are independent and identically
|
| 222 |
+
distributed (i.i.d.), such as stochastic gradient descent.
|
| 223 |
+
|
| 224 |
+
random_state : int, RandomState instance or None, default=42
|
| 225 |
+
Determines random number generation for dataset shuffling. Pass an int
|
| 226 |
+
for reproducible output across multiple function calls.
|
| 227 |
+
See :term:`Glossary <random_state>`.
|
| 228 |
+
|
| 229 |
+
remove : tuple, default=()
|
| 230 |
+
May contain any subset of ('headers', 'footers', 'quotes'). Each of
|
| 231 |
+
these are kinds of text that will be detected and removed from the
|
| 232 |
+
newsgroup posts, preventing classifiers from overfitting on
|
| 233 |
+
metadata.
|
| 234 |
+
|
| 235 |
+
'headers' removes newsgroup headers, 'footers' removes blocks at the
|
| 236 |
+
ends of posts that look like signatures, and 'quotes' removes lines
|
| 237 |
+
that appear to be quoting another post.
|
| 238 |
+
|
| 239 |
+
'headers' follows an exact standard; the other filters are not always
|
| 240 |
+
correct.
|
| 241 |
+
|
| 242 |
+
download_if_missing : bool, default=True
|
| 243 |
+
If False, raise an OSError if the data is not locally available
|
| 244 |
+
instead of trying to download the data from the source site.
|
| 245 |
+
|
| 246 |
+
return_X_y : bool, default=False
|
| 247 |
+
If True, returns `(data.data, data.target)` instead of a Bunch
|
| 248 |
+
object.
|
| 249 |
+
|
| 250 |
+
.. versionadded:: 0.22
|
| 251 |
+
|
| 252 |
+
n_retries : int, default=3
|
| 253 |
+
Number of retries when HTTP errors are encountered.
|
| 254 |
+
|
| 255 |
+
.. versionadded:: 1.5
|
| 256 |
+
|
| 257 |
+
delay : float, default=1.0
|
| 258 |
+
Number of seconds between retries.
|
| 259 |
+
|
| 260 |
+
.. versionadded:: 1.5
|
| 261 |
+
|
| 262 |
+
Returns
|
| 263 |
+
-------
|
| 264 |
+
bunch : :class:`~sklearn.utils.Bunch`
|
| 265 |
+
Dictionary-like object, with the following attributes.
|
| 266 |
+
|
| 267 |
+
data : list of shape (n_samples,)
|
| 268 |
+
The data list to learn.
|
| 269 |
+
target: ndarray of shape (n_samples,)
|
| 270 |
+
The target labels.
|
| 271 |
+
filenames: list of shape (n_samples,)
|
| 272 |
+
The path to the location of the data.
|
| 273 |
+
DESCR: str
|
| 274 |
+
The full description of the dataset.
|
| 275 |
+
target_names: list of shape (n_classes,)
|
| 276 |
+
The names of target classes.
|
| 277 |
+
|
| 278 |
+
(data, target) : tuple if `return_X_y=True`
|
| 279 |
+
A tuple of two ndarrays. The first contains a 2D array of shape
|
| 280 |
+
(n_samples, n_classes) with each row representing one sample and each
|
| 281 |
+
column representing the features. The second array of shape
|
| 282 |
+
(n_samples,) contains the target samples.
|
| 283 |
+
|
| 284 |
+
.. versionadded:: 0.22
|
| 285 |
+
|
| 286 |
+
Examples
|
| 287 |
+
--------
|
| 288 |
+
>>> from sklearn.datasets import fetch_20newsgroups
|
| 289 |
+
>>> cats = ['alt.atheism', 'sci.space']
|
| 290 |
+
>>> newsgroups_train = fetch_20newsgroups(subset='train', categories=cats)
|
| 291 |
+
>>> list(newsgroups_train.target_names)
|
| 292 |
+
['alt.atheism', 'sci.space']
|
| 293 |
+
>>> newsgroups_train.filenames.shape
|
| 294 |
+
(1073,)
|
| 295 |
+
>>> newsgroups_train.target.shape
|
| 296 |
+
(1073,)
|
| 297 |
+
>>> newsgroups_train.target[:10]
|
| 298 |
+
array([0, 1, 1, 1, 0, 1, 1, 0, 0, 0])
|
| 299 |
+
"""
|
| 300 |
+
|
| 301 |
+
data_home = get_data_home(data_home=data_home)
|
| 302 |
+
cache_path = _pkl_filepath(data_home, CACHE_NAME)
|
| 303 |
+
twenty_home = os.path.join(data_home, "20news_home")
|
| 304 |
+
cache = None
|
| 305 |
+
if os.path.exists(cache_path):
|
| 306 |
+
try:
|
| 307 |
+
with open(cache_path, "rb") as f:
|
| 308 |
+
compressed_content = f.read()
|
| 309 |
+
uncompressed_content = codecs.decode(compressed_content, "zlib_codec")
|
| 310 |
+
cache = pickle.loads(uncompressed_content)
|
| 311 |
+
except Exception as e:
|
| 312 |
+
print(80 * "_")
|
| 313 |
+
print("Cache loading failed")
|
| 314 |
+
print(80 * "_")
|
| 315 |
+
print(e)
|
| 316 |
+
|
| 317 |
+
if cache is None:
|
| 318 |
+
if download_if_missing:
|
| 319 |
+
logger.info("Downloading 20news dataset. This may take a few minutes.")
|
| 320 |
+
cache = _download_20newsgroups(
|
| 321 |
+
target_dir=twenty_home,
|
| 322 |
+
cache_path=cache_path,
|
| 323 |
+
n_retries=n_retries,
|
| 324 |
+
delay=delay,
|
| 325 |
+
)
|
| 326 |
+
else:
|
| 327 |
+
raise OSError("20Newsgroups dataset not found")
|
| 328 |
+
|
| 329 |
+
if subset in ("train", "test"):
|
| 330 |
+
data = cache[subset]
|
| 331 |
+
elif subset == "all":
|
| 332 |
+
data_lst = list()
|
| 333 |
+
target = list()
|
| 334 |
+
filenames = list()
|
| 335 |
+
for subset in ("train", "test"):
|
| 336 |
+
data = cache[subset]
|
| 337 |
+
data_lst.extend(data.data)
|
| 338 |
+
target.extend(data.target)
|
| 339 |
+
filenames.extend(data.filenames)
|
| 340 |
+
|
| 341 |
+
data.data = data_lst
|
| 342 |
+
data.target = np.array(target)
|
| 343 |
+
data.filenames = np.array(filenames)
|
| 344 |
+
|
| 345 |
+
fdescr = load_descr("twenty_newsgroups.rst")
|
| 346 |
+
|
| 347 |
+
data.DESCR = fdescr
|
| 348 |
+
|
| 349 |
+
if "headers" in remove:
|
| 350 |
+
data.data = [strip_newsgroup_header(text) for text in data.data]
|
| 351 |
+
if "footers" in remove:
|
| 352 |
+
data.data = [strip_newsgroup_footer(text) for text in data.data]
|
| 353 |
+
if "quotes" in remove:
|
| 354 |
+
data.data = [strip_newsgroup_quoting(text) for text in data.data]
|
| 355 |
+
|
| 356 |
+
if categories is not None:
|
| 357 |
+
labels = [(data.target_names.index(cat), cat) for cat in categories]
|
| 358 |
+
# Sort the categories to have the ordering of the labels
|
| 359 |
+
labels.sort()
|
| 360 |
+
labels, categories = zip(*labels)
|
| 361 |
+
mask = np.isin(data.target, labels)
|
| 362 |
+
data.filenames = data.filenames[mask]
|
| 363 |
+
data.target = data.target[mask]
|
| 364 |
+
# searchsorted to have continuous labels
|
| 365 |
+
data.target = np.searchsorted(labels, data.target)
|
| 366 |
+
data.target_names = list(categories)
|
| 367 |
+
# Use an object array to shuffle: avoids memory copy
|
| 368 |
+
data_lst = np.array(data.data, dtype=object)
|
| 369 |
+
data_lst = data_lst[mask]
|
| 370 |
+
data.data = data_lst.tolist()
|
| 371 |
+
|
| 372 |
+
if shuffle:
|
| 373 |
+
random_state = check_random_state(random_state)
|
| 374 |
+
indices = np.arange(data.target.shape[0])
|
| 375 |
+
random_state.shuffle(indices)
|
| 376 |
+
data.filenames = data.filenames[indices]
|
| 377 |
+
data.target = data.target[indices]
|
| 378 |
+
# Use an object array to shuffle: avoids memory copy
|
| 379 |
+
data_lst = np.array(data.data, dtype=object)
|
| 380 |
+
data_lst = data_lst[indices]
|
| 381 |
+
data.data = data_lst.tolist()
|
| 382 |
+
|
| 383 |
+
if return_X_y:
|
| 384 |
+
return data.data, data.target
|
| 385 |
+
|
| 386 |
+
return data
|
| 387 |
+
|
| 388 |
+
|
| 389 |
+
@validate_params(
|
| 390 |
+
{
|
| 391 |
+
"subset": [StrOptions({"train", "test", "all"})],
|
| 392 |
+
"remove": [tuple],
|
| 393 |
+
"data_home": [str, os.PathLike, None],
|
| 394 |
+
"download_if_missing": ["boolean"],
|
| 395 |
+
"return_X_y": ["boolean"],
|
| 396 |
+
"normalize": ["boolean"],
|
| 397 |
+
"as_frame": ["boolean"],
|
| 398 |
+
"n_retries": [Interval(Integral, 1, None, closed="left")],
|
| 399 |
+
"delay": [Interval(Real, 0.0, None, closed="neither")],
|
| 400 |
+
},
|
| 401 |
+
prefer_skip_nested_validation=True,
|
| 402 |
+
)
|
| 403 |
+
def fetch_20newsgroups_vectorized(
|
| 404 |
+
*,
|
| 405 |
+
subset="train",
|
| 406 |
+
remove=(),
|
| 407 |
+
data_home=None,
|
| 408 |
+
download_if_missing=True,
|
| 409 |
+
return_X_y=False,
|
| 410 |
+
normalize=True,
|
| 411 |
+
as_frame=False,
|
| 412 |
+
n_retries=3,
|
| 413 |
+
delay=1.0,
|
| 414 |
+
):
|
| 415 |
+
"""Load and vectorize the 20 newsgroups dataset (classification).
|
| 416 |
+
|
| 417 |
+
Download it if necessary.
|
| 418 |
+
|
| 419 |
+
This is a convenience function; the transformation is done using the
|
| 420 |
+
default settings for
|
| 421 |
+
:class:`~sklearn.feature_extraction.text.CountVectorizer`. For more
|
| 422 |
+
advanced usage (stopword filtering, n-gram extraction, etc.), combine
|
| 423 |
+
fetch_20newsgroups with a custom
|
| 424 |
+
:class:`~sklearn.feature_extraction.text.CountVectorizer`,
|
| 425 |
+
:class:`~sklearn.feature_extraction.text.HashingVectorizer`,
|
| 426 |
+
:class:`~sklearn.feature_extraction.text.TfidfTransformer` or
|
| 427 |
+
:class:`~sklearn.feature_extraction.text.TfidfVectorizer`.
|
| 428 |
+
|
| 429 |
+
The resulting counts are normalized using
|
| 430 |
+
:func:`sklearn.preprocessing.normalize` unless normalize is set to False.
|
| 431 |
+
|
| 432 |
+
================= ==========
|
| 433 |
+
Classes 20
|
| 434 |
+
Samples total 18846
|
| 435 |
+
Dimensionality 130107
|
| 436 |
+
Features real
|
| 437 |
+
================= ==========
|
| 438 |
+
|
| 439 |
+
Read more in the :ref:`User Guide <20newsgroups_dataset>`.
|
| 440 |
+
|
| 441 |
+
Parameters
|
| 442 |
+
----------
|
| 443 |
+
subset : {'train', 'test', 'all'}, default='train'
|
| 444 |
+
Select the dataset to load: 'train' for the training set, 'test'
|
| 445 |
+
for the test set, 'all' for both, with shuffled ordering.
|
| 446 |
+
|
| 447 |
+
remove : tuple, default=()
|
| 448 |
+
May contain any subset of ('headers', 'footers', 'quotes'). Each of
|
| 449 |
+
these are kinds of text that will be detected and removed from the
|
| 450 |
+
newsgroup posts, preventing classifiers from overfitting on
|
| 451 |
+
metadata.
|
| 452 |
+
|
| 453 |
+
'headers' removes newsgroup headers, 'footers' removes blocks at the
|
| 454 |
+
ends of posts that look like signatures, and 'quotes' removes lines
|
| 455 |
+
that appear to be quoting another post.
|
| 456 |
+
|
| 457 |
+
data_home : str or path-like, default=None
|
| 458 |
+
Specify an download and cache folder for the datasets. If None,
|
| 459 |
+
all scikit-learn data is stored in '~/scikit_learn_data' subfolders.
|
| 460 |
+
|
| 461 |
+
download_if_missing : bool, default=True
|
| 462 |
+
If False, raise an OSError if the data is not locally available
|
| 463 |
+
instead of trying to download the data from the source site.
|
| 464 |
+
|
| 465 |
+
return_X_y : bool, default=False
|
| 466 |
+
If True, returns ``(data.data, data.target)`` instead of a Bunch
|
| 467 |
+
object.
|
| 468 |
+
|
| 469 |
+
.. versionadded:: 0.20
|
| 470 |
+
|
| 471 |
+
normalize : bool, default=True
|
| 472 |
+
If True, normalizes each document's feature vector to unit norm using
|
| 473 |
+
:func:`sklearn.preprocessing.normalize`.
|
| 474 |
+
|
| 475 |
+
.. versionadded:: 0.22
|
| 476 |
+
|
| 477 |
+
as_frame : bool, default=False
|
| 478 |
+
If True, the data is a pandas DataFrame including columns with
|
| 479 |
+
appropriate dtypes (numeric, string, or categorical). The target is
|
| 480 |
+
a pandas DataFrame or Series depending on the number of
|
| 481 |
+
`target_columns`.
|
| 482 |
+
|
| 483 |
+
.. versionadded:: 0.24
|
| 484 |
+
|
| 485 |
+
n_retries : int, default=3
|
| 486 |
+
Number of retries when HTTP errors are encountered.
|
| 487 |
+
|
| 488 |
+
.. versionadded:: 1.5
|
| 489 |
+
|
| 490 |
+
delay : float, default=1.0
|
| 491 |
+
Number of seconds between retries.
|
| 492 |
+
|
| 493 |
+
.. versionadded:: 1.5
|
| 494 |
+
|
| 495 |
+
Returns
|
| 496 |
+
-------
|
| 497 |
+
bunch : :class:`~sklearn.utils.Bunch`
|
| 498 |
+
Dictionary-like object, with the following attributes.
|
| 499 |
+
|
| 500 |
+
data: {sparse matrix, dataframe} of shape (n_samples, n_features)
|
| 501 |
+
The input data matrix. If ``as_frame`` is `True`, ``data`` is
|
| 502 |
+
a pandas DataFrame with sparse columns.
|
| 503 |
+
target: {ndarray, series} of shape (n_samples,)
|
| 504 |
+
The target labels. If ``as_frame`` is `True`, ``target`` is a
|
| 505 |
+
pandas Series.
|
| 506 |
+
target_names: list of shape (n_classes,)
|
| 507 |
+
The names of target classes.
|
| 508 |
+
DESCR: str
|
| 509 |
+
The full description of the dataset.
|
| 510 |
+
frame: dataframe of shape (n_samples, n_features + 1)
|
| 511 |
+
Only present when `as_frame=True`. Pandas DataFrame with ``data``
|
| 512 |
+
and ``target``.
|
| 513 |
+
|
| 514 |
+
.. versionadded:: 0.24
|
| 515 |
+
|
| 516 |
+
(data, target) : tuple if ``return_X_y`` is True
|
| 517 |
+
`data` and `target` would be of the format defined in the `Bunch`
|
| 518 |
+
description above.
|
| 519 |
+
|
| 520 |
+
.. versionadded:: 0.20
|
| 521 |
+
|
| 522 |
+
Examples
|
| 523 |
+
--------
|
| 524 |
+
>>> from sklearn.datasets import fetch_20newsgroups_vectorized
|
| 525 |
+
>>> newsgroups_vectorized = fetch_20newsgroups_vectorized(subset='test')
|
| 526 |
+
>>> newsgroups_vectorized.data.shape
|
| 527 |
+
(7532, 130107)
|
| 528 |
+
>>> newsgroups_vectorized.target.shape
|
| 529 |
+
(7532,)
|
| 530 |
+
"""
|
| 531 |
+
data_home = get_data_home(data_home=data_home)
|
| 532 |
+
filebase = "20newsgroup_vectorized"
|
| 533 |
+
if remove:
|
| 534 |
+
filebase += "remove-" + "-".join(remove)
|
| 535 |
+
target_file = _pkl_filepath(data_home, filebase + ".pkl")
|
| 536 |
+
|
| 537 |
+
# we shuffle but use a fixed seed for the memoization
|
| 538 |
+
data_train = fetch_20newsgroups(
|
| 539 |
+
data_home=data_home,
|
| 540 |
+
subset="train",
|
| 541 |
+
categories=None,
|
| 542 |
+
shuffle=True,
|
| 543 |
+
random_state=12,
|
| 544 |
+
remove=remove,
|
| 545 |
+
download_if_missing=download_if_missing,
|
| 546 |
+
n_retries=n_retries,
|
| 547 |
+
delay=delay,
|
| 548 |
+
)
|
| 549 |
+
|
| 550 |
+
data_test = fetch_20newsgroups(
|
| 551 |
+
data_home=data_home,
|
| 552 |
+
subset="test",
|
| 553 |
+
categories=None,
|
| 554 |
+
shuffle=True,
|
| 555 |
+
random_state=12,
|
| 556 |
+
remove=remove,
|
| 557 |
+
download_if_missing=download_if_missing,
|
| 558 |
+
n_retries=n_retries,
|
| 559 |
+
delay=delay,
|
| 560 |
+
)
|
| 561 |
+
|
| 562 |
+
if os.path.exists(target_file):
|
| 563 |
+
try:
|
| 564 |
+
X_train, X_test, feature_names = joblib.load(target_file)
|
| 565 |
+
except ValueError as e:
|
| 566 |
+
raise ValueError(
|
| 567 |
+
f"The cached dataset located in {target_file} was fetched "
|
| 568 |
+
"with an older scikit-learn version and it is not compatible "
|
| 569 |
+
"with the scikit-learn version imported. You need to "
|
| 570 |
+
f"manually delete the file: {target_file}."
|
| 571 |
+
) from e
|
| 572 |
+
else:
|
| 573 |
+
vectorizer = CountVectorizer(dtype=np.int16)
|
| 574 |
+
X_train = vectorizer.fit_transform(data_train.data).tocsr()
|
| 575 |
+
X_test = vectorizer.transform(data_test.data).tocsr()
|
| 576 |
+
feature_names = vectorizer.get_feature_names_out()
|
| 577 |
+
|
| 578 |
+
joblib.dump((X_train, X_test, feature_names), target_file, compress=9)
|
| 579 |
+
|
| 580 |
+
# the data is stored as int16 for compactness
|
| 581 |
+
# but normalize needs floats
|
| 582 |
+
if normalize:
|
| 583 |
+
X_train = X_train.astype(np.float64)
|
| 584 |
+
X_test = X_test.astype(np.float64)
|
| 585 |
+
preprocessing.normalize(X_train, copy=False)
|
| 586 |
+
preprocessing.normalize(X_test, copy=False)
|
| 587 |
+
|
| 588 |
+
target_names = data_train.target_names
|
| 589 |
+
|
| 590 |
+
if subset == "train":
|
| 591 |
+
data = X_train
|
| 592 |
+
target = data_train.target
|
| 593 |
+
elif subset == "test":
|
| 594 |
+
data = X_test
|
| 595 |
+
target = data_test.target
|
| 596 |
+
elif subset == "all":
|
| 597 |
+
data = sp.vstack((X_train, X_test)).tocsr()
|
| 598 |
+
target = np.concatenate((data_train.target, data_test.target))
|
| 599 |
+
|
| 600 |
+
fdescr = load_descr("twenty_newsgroups.rst")
|
| 601 |
+
|
| 602 |
+
frame = None
|
| 603 |
+
target_name = ["category_class"]
|
| 604 |
+
|
| 605 |
+
if as_frame:
|
| 606 |
+
frame, data, target = _convert_data_dataframe(
|
| 607 |
+
"fetch_20newsgroups_vectorized",
|
| 608 |
+
data,
|
| 609 |
+
target,
|
| 610 |
+
feature_names,
|
| 611 |
+
target_names=target_name,
|
| 612 |
+
sparse_data=True,
|
| 613 |
+
)
|
| 614 |
+
|
| 615 |
+
if return_X_y:
|
| 616 |
+
return data, target
|
| 617 |
+
|
| 618 |
+
return Bunch(
|
| 619 |
+
data=data,
|
| 620 |
+
target=target,
|
| 621 |
+
frame=frame,
|
| 622 |
+
target_names=target_names,
|
| 623 |
+
feature_names=feature_names,
|
| 624 |
+
DESCR=fdescr,
|
| 625 |
+
)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/datasets/data/__init__.py
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Authors: The scikit-learn developers
|
| 2 |
+
# SPDX-License-Identifier: BSD-3-Clause
|
miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/datasets/data/breast_cancer.csv
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/datasets/data/iris.csv
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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.7,3.0,6.1,2.3,2
|
| 138 |
+
6.3,3.4,5.6,2.4,2
|
| 139 |
+
6.4,3.1,5.5,1.8,2
|
| 140 |
+
6.0,3.0,4.8,1.8,2
|
| 141 |
+
6.9,3.1,5.4,2.1,2
|
| 142 |
+
6.7,3.1,5.6,2.4,2
|
| 143 |
+
6.9,3.1,5.1,2.3,2
|
| 144 |
+
5.8,2.7,5.1,1.9,2
|
| 145 |
+
6.8,3.2,5.9,2.3,2
|
| 146 |
+
6.7,3.3,5.7,2.5,2
|
| 147 |
+
6.7,3.0,5.2,2.3,2
|
| 148 |
+
6.3,2.5,5.0,1.9,2
|
| 149 |
+
6.5,3.0,5.2,2.0,2
|
| 150 |
+
6.2,3.4,5.4,2.3,2
|
| 151 |
+
5.9,3.0,5.1,1.8,2
|
miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/datasets/data/linnerud_exercise.csv
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Chins Situps Jumps
|
| 2 |
+
5 162 60
|
| 3 |
+
2 110 60
|
| 4 |
+
12 101 101
|
| 5 |
+
12 105 37
|
| 6 |
+
13 155 58
|
| 7 |
+
4 101 42
|
| 8 |
+
8 101 38
|
| 9 |
+
6 125 40
|
| 10 |
+
15 200 40
|
| 11 |
+
17 251 250
|
| 12 |
+
17 120 38
|
| 13 |
+
13 210 115
|
| 14 |
+
14 215 105
|
| 15 |
+
1 50 50
|
| 16 |
+
6 70 31
|
| 17 |
+
12 210 120
|
| 18 |
+
4 60 25
|
| 19 |
+
11 230 80
|
| 20 |
+
15 225 73
|
| 21 |
+
2 110 43
|
miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/datasets/data/linnerud_physiological.csv
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Weight Waist Pulse
|
| 2 |
+
191 36 50
|
| 3 |
+
189 37 52
|
| 4 |
+
193 38 58
|
| 5 |
+
162 35 62
|
| 6 |
+
189 35 46
|
| 7 |
+
182 36 56
|
| 8 |
+
211 38 56
|
| 9 |
+
167 34 60
|
| 10 |
+
176 31 74
|
| 11 |
+
154 33 56
|
| 12 |
+
169 34 50
|
| 13 |
+
166 33 52
|
| 14 |
+
154 34 64
|
| 15 |
+
247 46 50
|
| 16 |
+
193 36 46
|
| 17 |
+
202 37 62
|
| 18 |
+
176 37 54
|
| 19 |
+
157 32 52
|
| 20 |
+
156 33 54
|
| 21 |
+
138 33 68
|
miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/datasets/data/wine_data.csv
ADDED
|
@@ -0,0 +1,179 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
178,13,class_0,class_1,class_2
|
| 2 |
+
14.23,1.71,2.43,15.6,127,2.8,3.06,0.28,2.29,5.64,1.04,3.92,1065,0
|
| 3 |
+
13.2,1.78,2.14,11.2,100,2.65,2.76,0.26,1.28,4.38,1.05,3.4,1050,0
|
| 4 |
+
13.16,2.36,2.67,18.6,101,2.8,3.24,0.3,2.81,5.68,1.03,3.17,1185,0
|
| 5 |
+
14.37,1.95,2.5,16.8,113,3.85,3.49,0.24,2.18,7.8,0.86,3.45,1480,0
|
| 6 |
+
13.24,2.59,2.87,21,118,2.8,2.69,0.39,1.82,4.32,1.04,2.93,735,0
|
| 7 |
+
14.2,1.76,2.45,15.2,112,3.27,3.39,0.34,1.97,6.75,1.05,2.85,1450,0
|
| 8 |
+
14.39,1.87,2.45,14.6,96,2.5,2.52,0.3,1.98,5.25,1.02,3.58,1290,0
|
| 9 |
+
14.06,2.15,2.61,17.6,121,2.6,2.51,0.31,1.25,5.05,1.06,3.58,1295,0
|
| 10 |
+
14.83,1.64,2.17,14,97,2.8,2.98,0.29,1.98,5.2,1.08,2.85,1045,0
|
| 11 |
+
13.86,1.35,2.27,16,98,2.98,3.15,0.22,1.85,7.22,1.01,3.55,1045,0
|
| 12 |
+
14.1,2.16,2.3,18,105,2.95,3.32,0.22,2.38,5.75,1.25,3.17,1510,0
|
| 13 |
+
14.12,1.48,2.32,16.8,95,2.2,2.43,0.26,1.57,5,1.17,2.82,1280,0
|
| 14 |
+
13.75,1.73,2.41,16,89,2.6,2.76,0.29,1.81,5.6,1.15,2.9,1320,0
|
| 15 |
+
14.75,1.73,2.39,11.4,91,3.1,3.69,0.43,2.81,5.4,1.25,2.73,1150,0
|
| 16 |
+
14.38,1.87,2.38,12,102,3.3,3.64,0.29,2.96,7.5,1.2,3,1547,0
|
| 17 |
+
13.63,1.81,2.7,17.2,112,2.85,2.91,0.3,1.46,7.3,1.28,2.88,1310,0
|
| 18 |
+
14.3,1.92,2.72,20,120,2.8,3.14,0.33,1.97,6.2,1.07,2.65,1280,0
|
| 19 |
+
13.83,1.57,2.62,20,115,2.95,3.4,0.4,1.72,6.6,1.13,2.57,1130,0
|
| 20 |
+
14.19,1.59,2.48,16.5,108,3.3,3.93,0.32,1.86,8.7,1.23,2.82,1680,0
|
| 21 |
+
13.64,3.1,2.56,15.2,116,2.7,3.03,0.17,1.66,5.1,0.96,3.36,845,0
|
| 22 |
+
14.06,1.63,2.28,16,126,3,3.17,0.24,2.1,5.65,1.09,3.71,780,0
|
| 23 |
+
12.93,3.8,2.65,18.6,102,2.41,2.41,0.25,1.98,4.5,1.03,3.52,770,0
|
| 24 |
+
13.71,1.86,2.36,16.6,101,2.61,2.88,0.27,1.69,3.8,1.11,4,1035,0
|
| 25 |
+
12.85,1.6,2.52,17.8,95,2.48,2.37,0.26,1.46,3.93,1.09,3.63,1015,0
|
| 26 |
+
13.5,1.81,2.61,20,96,2.53,2.61,0.28,1.66,3.52,1.12,3.82,845,0
|
| 27 |
+
13.05,2.05,3.22,25,124,2.63,2.68,0.47,1.92,3.58,1.13,3.2,830,0
|
| 28 |
+
13.39,1.77,2.62,16.1,93,2.85,2.94,0.34,1.45,4.8,0.92,3.22,1195,0
|
| 29 |
+
13.3,1.72,2.14,17,94,2.4,2.19,0.27,1.35,3.95,1.02,2.77,1285,0
|
| 30 |
+
13.87,1.9,2.8,19.4,107,2.95,2.97,0.37,1.76,4.5,1.25,3.4,915,0
|
| 31 |
+
14.02,1.68,2.21,16,96,2.65,2.33,0.26,1.98,4.7,1.04,3.59,1035,0
|
| 32 |
+
13.73,1.5,2.7,22.5,101,3,3.25,0.29,2.38,5.7,1.19,2.71,1285,0
|
| 33 |
+
13.58,1.66,2.36,19.1,106,2.86,3.19,0.22,1.95,6.9,1.09,2.88,1515,0
|
| 34 |
+
13.68,1.83,2.36,17.2,104,2.42,2.69,0.42,1.97,3.84,1.23,2.87,990,0
|
| 35 |
+
13.76,1.53,2.7,19.5,132,2.95,2.74,0.5,1.35,5.4,1.25,3,1235,0
|
| 36 |
+
13.51,1.8,2.65,19,110,2.35,2.53,0.29,1.54,4.2,1.1,2.87,1095,0
|
| 37 |
+
13.48,1.81,2.41,20.5,100,2.7,2.98,0.26,1.86,5.1,1.04,3.47,920,0
|
| 38 |
+
13.28,1.64,2.84,15.5,110,2.6,2.68,0.34,1.36,4.6,1.09,2.78,880,0
|
| 39 |
+
13.05,1.65,2.55,18,98,2.45,2.43,0.29,1.44,4.25,1.12,2.51,1105,0
|
| 40 |
+
13.07,1.5,2.1,15.5,98,2.4,2.64,0.28,1.37,3.7,1.18,2.69,1020,0
|
| 41 |
+
14.22,3.99,2.51,13.2,128,3,3.04,0.2,2.08,5.1,0.89,3.53,760,0
|
| 42 |
+
13.56,1.71,2.31,16.2,117,3.15,3.29,0.34,2.34,6.13,0.95,3.38,795,0
|
| 43 |
+
13.41,3.84,2.12,18.8,90,2.45,2.68,0.27,1.48,4.28,0.91,3,1035,0
|
| 44 |
+
13.88,1.89,2.59,15,101,3.25,3.56,0.17,1.7,5.43,0.88,3.56,1095,0
|
| 45 |
+
13.24,3.98,2.29,17.5,103,2.64,2.63,0.32,1.66,4.36,0.82,3,680,0
|
| 46 |
+
13.05,1.77,2.1,17,107,3,3,0.28,2.03,5.04,0.88,3.35,885,0
|
| 47 |
+
14.21,4.04,2.44,18.9,111,2.85,2.65,0.3,1.25,5.24,0.87,3.33,1080,0
|
| 48 |
+
14.38,3.59,2.28,16,102,3.25,3.17,0.27,2.19,4.9,1.04,3.44,1065,0
|
| 49 |
+
13.9,1.68,2.12,16,101,3.1,3.39,0.21,2.14,6.1,0.91,3.33,985,0
|
| 50 |
+
14.1,2.02,2.4,18.8,103,2.75,2.92,0.32,2.38,6.2,1.07,2.75,1060,0
|
| 51 |
+
13.94,1.73,2.27,17.4,108,2.88,3.54,0.32,2.08,8.9,1.12,3.1,1260,0
|
| 52 |
+
13.05,1.73,2.04,12.4,92,2.72,3.27,0.17,2.91,7.2,1.12,2.91,1150,0
|
| 53 |
+
13.83,1.65,2.6,17.2,94,2.45,2.99,0.22,2.29,5.6,1.24,3.37,1265,0
|
| 54 |
+
13.82,1.75,2.42,14,111,3.88,3.74,0.32,1.87,7.05,1.01,3.26,1190,0
|
| 55 |
+
13.77,1.9,2.68,17.1,115,3,2.79,0.39,1.68,6.3,1.13,2.93,1375,0
|
| 56 |
+
13.74,1.67,2.25,16.4,118,2.6,2.9,0.21,1.62,5.85,0.92,3.2,1060,0
|
| 57 |
+
13.56,1.73,2.46,20.5,116,2.96,2.78,0.2,2.45,6.25,0.98,3.03,1120,0
|
| 58 |
+
14.22,1.7,2.3,16.3,118,3.2,3,0.26,2.03,6.38,0.94,3.31,970,0
|
| 59 |
+
13.29,1.97,2.68,16.8,102,3,3.23,0.31,1.66,6,1.07,2.84,1270,0
|
| 60 |
+
13.72,1.43,2.5,16.7,108,3.4,3.67,0.19,2.04,6.8,0.89,2.87,1285,0
|
| 61 |
+
12.37,0.94,1.36,10.6,88,1.98,0.57,0.28,0.42,1.95,1.05,1.82,520,1
|
| 62 |
+
12.33,1.1,2.28,16,101,2.05,1.09,0.63,0.41,3.27,1.25,1.67,680,1
|
| 63 |
+
12.64,1.36,2.02,16.8,100,2.02,1.41,0.53,0.62,5.75,0.98,1.59,450,1
|
| 64 |
+
13.67,1.25,1.92,18,94,2.1,1.79,0.32,0.73,3.8,1.23,2.46,630,1
|
| 65 |
+
12.37,1.13,2.16,19,87,3.5,3.1,0.19,1.87,4.45,1.22,2.87,420,1
|
| 66 |
+
12.17,1.45,2.53,19,104,1.89,1.75,0.45,1.03,2.95,1.45,2.23,355,1
|
| 67 |
+
12.37,1.21,2.56,18.1,98,2.42,2.65,0.37,2.08,4.6,1.19,2.3,678,1
|
| 68 |
+
13.11,1.01,1.7,15,78,2.98,3.18,0.26,2.28,5.3,1.12,3.18,502,1
|
| 69 |
+
12.37,1.17,1.92,19.6,78,2.11,2,0.27,1.04,4.68,1.12,3.48,510,1
|
| 70 |
+
13.34,0.94,2.36,17,110,2.53,1.3,0.55,0.42,3.17,1.02,1.93,750,1
|
| 71 |
+
12.21,1.19,1.75,16.8,151,1.85,1.28,0.14,2.5,2.85,1.28,3.07,718,1
|
| 72 |
+
12.29,1.61,2.21,20.4,103,1.1,1.02,0.37,1.46,3.05,0.906,1.82,870,1
|
| 73 |
+
13.86,1.51,2.67,25,86,2.95,2.86,0.21,1.87,3.38,1.36,3.16,410,1
|
| 74 |
+
13.49,1.66,2.24,24,87,1.88,1.84,0.27,1.03,3.74,0.98,2.78,472,1
|
| 75 |
+
12.99,1.67,2.6,30,139,3.3,2.89,0.21,1.96,3.35,1.31,3.5,985,1
|
| 76 |
+
11.96,1.09,2.3,21,101,3.38,2.14,0.13,1.65,3.21,0.99,3.13,886,1
|
| 77 |
+
11.66,1.88,1.92,16,97,1.61,1.57,0.34,1.15,3.8,1.23,2.14,428,1
|
| 78 |
+
13.03,0.9,1.71,16,86,1.95,2.03,0.24,1.46,4.6,1.19,2.48,392,1
|
| 79 |
+
11.84,2.89,2.23,18,112,1.72,1.32,0.43,0.95,2.65,0.96,2.52,500,1
|
| 80 |
+
12.33,0.99,1.95,14.8,136,1.9,1.85,0.35,2.76,3.4,1.06,2.31,750,1
|
| 81 |
+
12.7,3.87,2.4,23,101,2.83,2.55,0.43,1.95,2.57,1.19,3.13,463,1
|
| 82 |
+
12,0.92,2,19,86,2.42,2.26,0.3,1.43,2.5,1.38,3.12,278,1
|
| 83 |
+
12.72,1.81,2.2,18.8,86,2.2,2.53,0.26,1.77,3.9,1.16,3.14,714,1
|
| 84 |
+
12.08,1.13,2.51,24,78,2,1.58,0.4,1.4,2.2,1.31,2.72,630,1
|
| 85 |
+
13.05,3.86,2.32,22.5,85,1.65,1.59,0.61,1.62,4.8,0.84,2.01,515,1
|
| 86 |
+
11.84,0.89,2.58,18,94,2.2,2.21,0.22,2.35,3.05,0.79,3.08,520,1
|
| 87 |
+
12.67,0.98,2.24,18,99,2.2,1.94,0.3,1.46,2.62,1.23,3.16,450,1
|
| 88 |
+
12.16,1.61,2.31,22.8,90,1.78,1.69,0.43,1.56,2.45,1.33,2.26,495,1
|
| 89 |
+
11.65,1.67,2.62,26,88,1.92,1.61,0.4,1.34,2.6,1.36,3.21,562,1
|
| 90 |
+
11.64,2.06,2.46,21.6,84,1.95,1.69,0.48,1.35,2.8,1,2.75,680,1
|
| 91 |
+
12.08,1.33,2.3,23.6,70,2.2,1.59,0.42,1.38,1.74,1.07,3.21,625,1
|
| 92 |
+
12.08,1.83,2.32,18.5,81,1.6,1.5,0.52,1.64,2.4,1.08,2.27,480,1
|
| 93 |
+
12,1.51,2.42,22,86,1.45,1.25,0.5,1.63,3.6,1.05,2.65,450,1
|
| 94 |
+
12.69,1.53,2.26,20.7,80,1.38,1.46,0.58,1.62,3.05,0.96,2.06,495,1
|
| 95 |
+
12.29,2.83,2.22,18,88,2.45,2.25,0.25,1.99,2.15,1.15,3.3,290,1
|
| 96 |
+
11.62,1.99,2.28,18,98,3.02,2.26,0.17,1.35,3.25,1.16,2.96,345,1
|
| 97 |
+
12.47,1.52,2.2,19,162,2.5,2.27,0.32,3.28,2.6,1.16,2.63,937,1
|
| 98 |
+
11.81,2.12,2.74,21.5,134,1.6,0.99,0.14,1.56,2.5,0.95,2.26,625,1
|
| 99 |
+
12.29,1.41,1.98,16,85,2.55,2.5,0.29,1.77,2.9,1.23,2.74,428,1
|
| 100 |
+
12.37,1.07,2.1,18.5,88,3.52,3.75,0.24,1.95,4.5,1.04,2.77,660,1
|
| 101 |
+
12.29,3.17,2.21,18,88,2.85,2.99,0.45,2.81,2.3,1.42,2.83,406,1
|
| 102 |
+
12.08,2.08,1.7,17.5,97,2.23,2.17,0.26,1.4,3.3,1.27,2.96,710,1
|
| 103 |
+
12.6,1.34,1.9,18.5,88,1.45,1.36,0.29,1.35,2.45,1.04,2.77,562,1
|
| 104 |
+
12.34,2.45,2.46,21,98,2.56,2.11,0.34,1.31,2.8,0.8,3.38,438,1
|
| 105 |
+
11.82,1.72,1.88,19.5,86,2.5,1.64,0.37,1.42,2.06,0.94,2.44,415,1
|
| 106 |
+
12.51,1.73,1.98,20.5,85,2.2,1.92,0.32,1.48,2.94,1.04,3.57,672,1
|
| 107 |
+
12.42,2.55,2.27,22,90,1.68,1.84,0.66,1.42,2.7,0.86,3.3,315,1
|
| 108 |
+
12.25,1.73,2.12,19,80,1.65,2.03,0.37,1.63,3.4,1,3.17,510,1
|
| 109 |
+
12.72,1.75,2.28,22.5,84,1.38,1.76,0.48,1.63,3.3,0.88,2.42,488,1
|
| 110 |
+
12.22,1.29,1.94,19,92,2.36,2.04,0.39,2.08,2.7,0.86,3.02,312,1
|
| 111 |
+
11.61,1.35,2.7,20,94,2.74,2.92,0.29,2.49,2.65,0.96,3.26,680,1
|
| 112 |
+
11.46,3.74,1.82,19.5,107,3.18,2.58,0.24,3.58,2.9,0.75,2.81,562,1
|
| 113 |
+
12.52,2.43,2.17,21,88,2.55,2.27,0.26,1.22,2,0.9,2.78,325,1
|
| 114 |
+
11.76,2.68,2.92,20,103,1.75,2.03,0.6,1.05,3.8,1.23,2.5,607,1
|
| 115 |
+
11.41,0.74,2.5,21,88,2.48,2.01,0.42,1.44,3.08,1.1,2.31,434,1
|
| 116 |
+
12.08,1.39,2.5,22.5,84,2.56,2.29,0.43,1.04,2.9,0.93,3.19,385,1
|
| 117 |
+
11.03,1.51,2.2,21.5,85,2.46,2.17,0.52,2.01,1.9,1.71,2.87,407,1
|
| 118 |
+
11.82,1.47,1.99,20.8,86,1.98,1.6,0.3,1.53,1.95,0.95,3.33,495,1
|
| 119 |
+
12.42,1.61,2.19,22.5,108,2,2.09,0.34,1.61,2.06,1.06,2.96,345,1
|
| 120 |
+
12.77,3.43,1.98,16,80,1.63,1.25,0.43,0.83,3.4,0.7,2.12,372,1
|
| 121 |
+
12,3.43,2,19,87,2,1.64,0.37,1.87,1.28,0.93,3.05,564,1
|
| 122 |
+
11.45,2.4,2.42,20,96,2.9,2.79,0.32,1.83,3.25,0.8,3.39,625,1
|
| 123 |
+
11.56,2.05,3.23,28.5,119,3.18,5.08,0.47,1.87,6,0.93,3.69,465,1
|
| 124 |
+
12.42,4.43,2.73,26.5,102,2.2,2.13,0.43,1.71,2.08,0.92,3.12,365,1
|
| 125 |
+
13.05,5.8,2.13,21.5,86,2.62,2.65,0.3,2.01,2.6,0.73,3.1,380,1
|
| 126 |
+
11.87,4.31,2.39,21,82,2.86,3.03,0.21,2.91,2.8,0.75,3.64,380,1
|
| 127 |
+
12.07,2.16,2.17,21,85,2.6,2.65,0.37,1.35,2.76,0.86,3.28,378,1
|
| 128 |
+
12.43,1.53,2.29,21.5,86,2.74,3.15,0.39,1.77,3.94,0.69,2.84,352,1
|
| 129 |
+
11.79,2.13,2.78,28.5,92,2.13,2.24,0.58,1.76,3,0.97,2.44,466,1
|
| 130 |
+
12.37,1.63,2.3,24.5,88,2.22,2.45,0.4,1.9,2.12,0.89,2.78,342,1
|
| 131 |
+
12.04,4.3,2.38,22,80,2.1,1.75,0.42,1.35,2.6,0.79,2.57,580,1
|
| 132 |
+
12.86,1.35,2.32,18,122,1.51,1.25,0.21,0.94,4.1,0.76,1.29,630,2
|
| 133 |
+
12.88,2.99,2.4,20,104,1.3,1.22,0.24,0.83,5.4,0.74,1.42,530,2
|
| 134 |
+
12.81,2.31,2.4,24,98,1.15,1.09,0.27,0.83,5.7,0.66,1.36,560,2
|
| 135 |
+
12.7,3.55,2.36,21.5,106,1.7,1.2,0.17,0.84,5,0.78,1.29,600,2
|
| 136 |
+
12.51,1.24,2.25,17.5,85,2,0.58,0.6,1.25,5.45,0.75,1.51,650,2
|
| 137 |
+
12.6,2.46,2.2,18.5,94,1.62,0.66,0.63,0.94,7.1,0.73,1.58,695,2
|
| 138 |
+
12.25,4.72,2.54,21,89,1.38,0.47,0.53,0.8,3.85,0.75,1.27,720,2
|
| 139 |
+
12.53,5.51,2.64,25,96,1.79,0.6,0.63,1.1,5,0.82,1.69,515,2
|
| 140 |
+
13.49,3.59,2.19,19.5,88,1.62,0.48,0.58,0.88,5.7,0.81,1.82,580,2
|
| 141 |
+
12.84,2.96,2.61,24,101,2.32,0.6,0.53,0.81,4.92,0.89,2.15,590,2
|
| 142 |
+
12.93,2.81,2.7,21,96,1.54,0.5,0.53,0.75,4.6,0.77,2.31,600,2
|
| 143 |
+
13.36,2.56,2.35,20,89,1.4,0.5,0.37,0.64,5.6,0.7,2.47,780,2
|
| 144 |
+
13.52,3.17,2.72,23.5,97,1.55,0.52,0.5,0.55,4.35,0.89,2.06,520,2
|
| 145 |
+
13.62,4.95,2.35,20,92,2,0.8,0.47,1.02,4.4,0.91,2.05,550,2
|
| 146 |
+
12.25,3.88,2.2,18.5,112,1.38,0.78,0.29,1.14,8.21,0.65,2,855,2
|
| 147 |
+
13.16,3.57,2.15,21,102,1.5,0.55,0.43,1.3,4,0.6,1.68,830,2
|
| 148 |
+
13.88,5.04,2.23,20,80,0.98,0.34,0.4,0.68,4.9,0.58,1.33,415,2
|
| 149 |
+
12.87,4.61,2.48,21.5,86,1.7,0.65,0.47,0.86,7.65,0.54,1.86,625,2
|
| 150 |
+
13.32,3.24,2.38,21.5,92,1.93,0.76,0.45,1.25,8.42,0.55,1.62,650,2
|
| 151 |
+
13.08,3.9,2.36,21.5,113,1.41,1.39,0.34,1.14,9.4,0.57,1.33,550,2
|
| 152 |
+
13.5,3.12,2.62,24,123,1.4,1.57,0.22,1.25,8.6,0.59,1.3,500,2
|
| 153 |
+
12.79,2.67,2.48,22,112,1.48,1.36,0.24,1.26,10.8,0.48,1.47,480,2
|
| 154 |
+
13.11,1.9,2.75,25.5,116,2.2,1.28,0.26,1.56,7.1,0.61,1.33,425,2
|
| 155 |
+
13.23,3.3,2.28,18.5,98,1.8,0.83,0.61,1.87,10.52,0.56,1.51,675,2
|
| 156 |
+
12.58,1.29,2.1,20,103,1.48,0.58,0.53,1.4,7.6,0.58,1.55,640,2
|
| 157 |
+
13.17,5.19,2.32,22,93,1.74,0.63,0.61,1.55,7.9,0.6,1.48,725,2
|
| 158 |
+
13.84,4.12,2.38,19.5,89,1.8,0.83,0.48,1.56,9.01,0.57,1.64,480,2
|
| 159 |
+
12.45,3.03,2.64,27,97,1.9,0.58,0.63,1.14,7.5,0.67,1.73,880,2
|
| 160 |
+
14.34,1.68,2.7,25,98,2.8,1.31,0.53,2.7,13,0.57,1.96,660,2
|
| 161 |
+
13.48,1.67,2.64,22.5,89,2.6,1.1,0.52,2.29,11.75,0.57,1.78,620,2
|
| 162 |
+
12.36,3.83,2.38,21,88,2.3,0.92,0.5,1.04,7.65,0.56,1.58,520,2
|
| 163 |
+
13.69,3.26,2.54,20,107,1.83,0.56,0.5,0.8,5.88,0.96,1.82,680,2
|
| 164 |
+
12.85,3.27,2.58,22,106,1.65,0.6,0.6,0.96,5.58,0.87,2.11,570,2
|
| 165 |
+
12.96,3.45,2.35,18.5,106,1.39,0.7,0.4,0.94,5.28,0.68,1.75,675,2
|
| 166 |
+
13.78,2.76,2.3,22,90,1.35,0.68,0.41,1.03,9.58,0.7,1.68,615,2
|
| 167 |
+
13.73,4.36,2.26,22.5,88,1.28,0.47,0.52,1.15,6.62,0.78,1.75,520,2
|
| 168 |
+
13.45,3.7,2.6,23,111,1.7,0.92,0.43,1.46,10.68,0.85,1.56,695,2
|
| 169 |
+
12.82,3.37,2.3,19.5,88,1.48,0.66,0.4,0.97,10.26,0.72,1.75,685,2
|
| 170 |
+
13.58,2.58,2.69,24.5,105,1.55,0.84,0.39,1.54,8.66,0.74,1.8,750,2
|
| 171 |
+
13.4,4.6,2.86,25,112,1.98,0.96,0.27,1.11,8.5,0.67,1.92,630,2
|
| 172 |
+
12.2,3.03,2.32,19,96,1.25,0.49,0.4,0.73,5.5,0.66,1.83,510,2
|
| 173 |
+
12.77,2.39,2.28,19.5,86,1.39,0.51,0.48,0.64,9.899999,0.57,1.63,470,2
|
| 174 |
+
14.16,2.51,2.48,20,91,1.68,0.7,0.44,1.24,9.7,0.62,1.71,660,2
|
| 175 |
+
13.71,5.65,2.45,20.5,95,1.68,0.61,0.52,1.06,7.7,0.64,1.74,740,2
|
| 176 |
+
13.4,3.91,2.48,23,102,1.8,0.75,0.43,1.41,7.3,0.7,1.56,750,2
|
| 177 |
+
13.27,4.28,2.26,20,120,1.59,0.69,0.43,1.35,10.2,0.59,1.56,835,2
|
| 178 |
+
13.17,2.59,2.37,20,120,1.65,0.68,0.53,1.46,9.3,0.6,1.62,840,2
|
| 179 |
+
14.13,4.1,2.74,24.5,96,2.05,0.76,0.56,1.35,9.2,0.61,1.6,560,2
|
miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/datasets/descr/__init__.py
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Authors: The scikit-learn developers
|
| 2 |
+
# SPDX-License-Identifier: BSD-3-Clause
|
miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/datasets/descr/breast_cancer.rst
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
.. _breast_cancer_dataset:
|
| 2 |
+
|
| 3 |
+
Breast cancer Wisconsin (diagnostic) dataset
|
| 4 |
+
--------------------------------------------
|
| 5 |
+
|
| 6 |
+
**Data Set Characteristics:**
|
| 7 |
+
|
| 8 |
+
:Number of Instances: 569
|
| 9 |
+
|
| 10 |
+
:Number of Attributes: 30 numeric, predictive attributes and the class
|
| 11 |
+
|
| 12 |
+
:Attribute Information:
|
| 13 |
+
- radius (mean of distances from center to points on the perimeter)
|
| 14 |
+
- texture (standard deviation of gray-scale values)
|
| 15 |
+
- perimeter
|
| 16 |
+
- area
|
| 17 |
+
- smoothness (local variation in radius lengths)
|
| 18 |
+
- compactness (perimeter^2 / area - 1.0)
|
| 19 |
+
- concavity (severity of concave portions of the contour)
|
| 20 |
+
- concave points (number of concave portions of the contour)
|
| 21 |
+
- symmetry
|
| 22 |
+
- fractal dimension ("coastline approximation" - 1)
|
| 23 |
+
|
| 24 |
+
The mean, standard error, and "worst" or largest (mean of the three
|
| 25 |
+
worst/largest values) of these features were computed for each image,
|
| 26 |
+
resulting in 30 features. For instance, field 0 is Mean Radius, field
|
| 27 |
+
10 is Radius SE, field 20 is Worst Radius.
|
| 28 |
+
|
| 29 |
+
- class:
|
| 30 |
+
- WDBC-Malignant
|
| 31 |
+
- WDBC-Benign
|
| 32 |
+
|
| 33 |
+
:Summary Statistics:
|
| 34 |
+
|
| 35 |
+
===================================== ====== ======
|
| 36 |
+
Min Max
|
| 37 |
+
===================================== ====== ======
|
| 38 |
+
radius (mean): 6.981 28.11
|
| 39 |
+
texture (mean): 9.71 39.28
|
| 40 |
+
perimeter (mean): 43.79 188.5
|
| 41 |
+
area (mean): 143.5 2501.0
|
| 42 |
+
smoothness (mean): 0.053 0.163
|
| 43 |
+
compactness (mean): 0.019 0.345
|
| 44 |
+
concavity (mean): 0.0 0.427
|
| 45 |
+
concave points (mean): 0.0 0.201
|
| 46 |
+
symmetry (mean): 0.106 0.304
|
| 47 |
+
fractal dimension (mean): 0.05 0.097
|
| 48 |
+
radius (standard error): 0.112 2.873
|
| 49 |
+
texture (standard error): 0.36 4.885
|
| 50 |
+
perimeter (standard error): 0.757 21.98
|
| 51 |
+
area (standard error): 6.802 542.2
|
| 52 |
+
smoothness (standard error): 0.002 0.031
|
| 53 |
+
compactness (standard error): 0.002 0.135
|
| 54 |
+
concavity (standard error): 0.0 0.396
|
| 55 |
+
concave points (standard error): 0.0 0.053
|
| 56 |
+
symmetry (standard error): 0.008 0.079
|
| 57 |
+
fractal dimension (standard error): 0.001 0.03
|
| 58 |
+
radius (worst): 7.93 36.04
|
| 59 |
+
texture (worst): 12.02 49.54
|
| 60 |
+
perimeter (worst): 50.41 251.2
|
| 61 |
+
area (worst): 185.2 4254.0
|
| 62 |
+
smoothness (worst): 0.071 0.223
|
| 63 |
+
compactness (worst): 0.027 1.058
|
| 64 |
+
concavity (worst): 0.0 1.252
|
| 65 |
+
concave points (worst): 0.0 0.291
|
| 66 |
+
symmetry (worst): 0.156 0.664
|
| 67 |
+
fractal dimension (worst): 0.055 0.208
|
| 68 |
+
===================================== ====== ======
|
| 69 |
+
|
| 70 |
+
:Missing Attribute Values: None
|
| 71 |
+
|
| 72 |
+
:Class Distribution: 212 - Malignant, 357 - Benign
|
| 73 |
+
|
| 74 |
+
:Creator: Dr. William H. Wolberg, W. Nick Street, Olvi L. Mangasarian
|
| 75 |
+
|
| 76 |
+
:Donor: Nick Street
|
| 77 |
+
|
| 78 |
+
:Date: November, 1995
|
| 79 |
+
|
| 80 |
+
This is a copy of UCI ML Breast Cancer Wisconsin (Diagnostic) datasets.
|
| 81 |
+
https://goo.gl/U2Uwz2
|
| 82 |
+
|
| 83 |
+
Features are computed from a digitized image of a fine needle
|
| 84 |
+
aspirate (FNA) of a breast mass. They describe
|
| 85 |
+
characteristics of the cell nuclei present in the image.
|
| 86 |
+
|
| 87 |
+
Separating plane described above was obtained using
|
| 88 |
+
Multisurface Method-Tree (MSM-T) [K. P. Bennett, "Decision Tree
|
| 89 |
+
Construction Via Linear Programming." Proceedings of the 4th
|
| 90 |
+
Midwest Artificial Intelligence and Cognitive Science Society,
|
| 91 |
+
pp. 97-101, 1992], a classification method which uses linear
|
| 92 |
+
programming to construct a decision tree. Relevant features
|
| 93 |
+
were selected using an exhaustive search in the space of 1-4
|
| 94 |
+
features and 1-3 separating planes.
|
| 95 |
+
|
| 96 |
+
The actual linear program used to obtain the separating plane
|
| 97 |
+
in the 3-dimensional space is that described in:
|
| 98 |
+
[K. P. Bennett and O. L. Mangasarian: "Robust Linear
|
| 99 |
+
Programming Discrimination of Two Linearly Inseparable Sets",
|
| 100 |
+
Optimization Methods and Software 1, 1992, 23-34].
|
| 101 |
+
|
| 102 |
+
This database is also available through the UW CS ftp server:
|
| 103 |
+
|
| 104 |
+
ftp ftp.cs.wisc.edu
|
| 105 |
+
cd math-prog/cpo-dataset/machine-learn/WDBC/
|
| 106 |
+
|
| 107 |
+
.. dropdown:: References
|
| 108 |
+
|
| 109 |
+
- W.N. Street, W.H. Wolberg and O.L. Mangasarian. Nuclear feature extraction
|
| 110 |
+
for breast tumor diagnosis. IS&T/SPIE 1993 International Symposium on
|
| 111 |
+
Electronic Imaging: Science and Technology, volume 1905, pages 861-870,
|
| 112 |
+
San Jose, CA, 1993.
|
| 113 |
+
- O.L. Mangasarian, W.N. Street and W.H. Wolberg. Breast cancer diagnosis and
|
| 114 |
+
prognosis via linear programming. Operations Research, 43(4), pages 570-577,
|
| 115 |
+
July-August 1995.
|
| 116 |
+
- W.H. Wolberg, W.N. Street, and O.L. Mangasarian. Machine learning techniques
|
| 117 |
+
to diagnose breast cancer from fine-needle aspirates. Cancer Letters 77 (1994)
|
| 118 |
+
163-171.
|
miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/datasets/descr/california_housing.rst
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
.. _california_housing_dataset:
|
| 2 |
+
|
| 3 |
+
California Housing dataset
|
| 4 |
+
--------------------------
|
| 5 |
+
|
| 6 |
+
**Data Set Characteristics:**
|
| 7 |
+
|
| 8 |
+
:Number of Instances: 20640
|
| 9 |
+
|
| 10 |
+
:Number of Attributes: 8 numeric, predictive attributes and the target
|
| 11 |
+
|
| 12 |
+
:Attribute Information:
|
| 13 |
+
- MedInc median income in block group
|
| 14 |
+
- HouseAge median house age in block group
|
| 15 |
+
- AveRooms average number of rooms per household
|
| 16 |
+
- AveBedrms average number of bedrooms per household
|
| 17 |
+
- Population block group population
|
| 18 |
+
- AveOccup average number of household members
|
| 19 |
+
- Latitude block group latitude
|
| 20 |
+
- Longitude block group longitude
|
| 21 |
+
|
| 22 |
+
:Missing Attribute Values: None
|
| 23 |
+
|
| 24 |
+
This dataset was obtained from the StatLib repository.
|
| 25 |
+
https://www.dcc.fc.up.pt/~ltorgo/Regression/cal_housing.html
|
| 26 |
+
|
| 27 |
+
The target variable is the median house value for California districts,
|
| 28 |
+
expressed in hundreds of thousands of dollars ($100,000).
|
| 29 |
+
|
| 30 |
+
This dataset was derived from the 1990 U.S. census, using one row per census
|
| 31 |
+
block group. A block group is the smallest geographical unit for which the U.S.
|
| 32 |
+
Census Bureau publishes sample data (a block group typically has a population
|
| 33 |
+
of 600 to 3,000 people).
|
| 34 |
+
|
| 35 |
+
A household is a group of people residing within a home. Since the average
|
| 36 |
+
number of rooms and bedrooms in this dataset are provided per household, these
|
| 37 |
+
columns may take surprisingly large values for block groups with few households
|
| 38 |
+
and many empty houses, such as vacation resorts.
|
| 39 |
+
|
| 40 |
+
It can be downloaded/loaded using the
|
| 41 |
+
:func:`sklearn.datasets.fetch_california_housing` function.
|
| 42 |
+
|
| 43 |
+
.. rubric:: References
|
| 44 |
+
|
| 45 |
+
- Pace, R. Kelley and Ronald Barry, Sparse Spatial Autoregressions,
|
| 46 |
+
Statistics and Probability Letters, 33:291-297, 1997.
|
miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/datasets/descr/covtype.rst
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
.. _covtype_dataset:
|
| 2 |
+
|
| 3 |
+
Forest covertypes
|
| 4 |
+
-----------------
|
| 5 |
+
|
| 6 |
+
The samples in this dataset correspond to 30×30m patches of forest in the US,
|
| 7 |
+
collected for the task of predicting each patch's cover type,
|
| 8 |
+
i.e. the dominant species of tree.
|
| 9 |
+
There are seven covertypes, making this a multiclass classification problem.
|
| 10 |
+
Each sample has 54 features, described on the
|
| 11 |
+
`dataset's homepage <https://archive.ics.uci.edu/ml/datasets/Covertype>`__.
|
| 12 |
+
Some of the features are boolean indicators,
|
| 13 |
+
while others are discrete or continuous measurements.
|
| 14 |
+
|
| 15 |
+
**Data Set Characteristics:**
|
| 16 |
+
|
| 17 |
+
================= ============
|
| 18 |
+
Classes 7
|
| 19 |
+
Samples total 581012
|
| 20 |
+
Dimensionality 54
|
| 21 |
+
Features int
|
| 22 |
+
================= ============
|
| 23 |
+
|
| 24 |
+
:func:`sklearn.datasets.fetch_covtype` will load the covertype dataset;
|
| 25 |
+
it returns a dictionary-like 'Bunch' object
|
| 26 |
+
with the feature matrix in the ``data`` member
|
| 27 |
+
and the target values in ``target``. If optional argument 'as_frame' is
|
| 28 |
+
set to 'True', it will return ``data`` and ``target`` as pandas
|
| 29 |
+
data frame, and there will be an additional member ``frame`` as well.
|
| 30 |
+
The dataset will be downloaded from the web if necessary.
|
miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/datasets/descr/diabetes.rst
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
.. _diabetes_dataset:
|
| 2 |
+
|
| 3 |
+
Diabetes dataset
|
| 4 |
+
----------------
|
| 5 |
+
|
| 6 |
+
Ten baseline variables, age, sex, body mass index, average blood
|
| 7 |
+
pressure, and six blood serum measurements were obtained for each of n =
|
| 8 |
+
442 diabetes patients, as well as the response of interest, a
|
| 9 |
+
quantitative measure of disease progression one year after baseline.
|
| 10 |
+
|
| 11 |
+
**Data Set Characteristics:**
|
| 12 |
+
|
| 13 |
+
:Number of Instances: 442
|
| 14 |
+
|
| 15 |
+
:Number of Attributes: First 10 columns are numeric predictive values
|
| 16 |
+
|
| 17 |
+
:Target: Column 11 is a quantitative measure of disease progression one year after baseline
|
| 18 |
+
|
| 19 |
+
:Attribute Information:
|
| 20 |
+
- age age in years
|
| 21 |
+
- sex
|
| 22 |
+
- bmi body mass index
|
| 23 |
+
- bp average blood pressure
|
| 24 |
+
- s1 tc, total serum cholesterol
|
| 25 |
+
- s2 ldl, low-density lipoproteins
|
| 26 |
+
- s3 hdl, high-density lipoproteins
|
| 27 |
+
- s4 tch, total cholesterol / HDL
|
| 28 |
+
- s5 ltg, possibly log of serum triglycerides level
|
| 29 |
+
- s6 glu, blood sugar level
|
| 30 |
+
|
| 31 |
+
Note: Each of these 10 feature variables have been mean centered and scaled by the standard deviation times the square root of `n_samples` (i.e. the sum of squares of each column totals 1).
|
| 32 |
+
|
| 33 |
+
Source URL:
|
| 34 |
+
https://www4.stat.ncsu.edu/~boos/var.select/diabetes.html
|
| 35 |
+
|
| 36 |
+
For more information see:
|
| 37 |
+
Bradley Efron, Trevor Hastie, Iain Johnstone and Robert Tibshirani (2004) "Least Angle Regression," Annals of Statistics (with discussion), 407-499.
|
| 38 |
+
(https://web.stanford.edu/~hastie/Papers/LARS/LeastAngle_2002.pdf)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/datasets/descr/digits.rst
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
.. _digits_dataset:
|
| 2 |
+
|
| 3 |
+
Optical recognition of handwritten digits dataset
|
| 4 |
+
--------------------------------------------------
|
| 5 |
+
|
| 6 |
+
**Data Set Characteristics:**
|
| 7 |
+
|
| 8 |
+
:Number of Instances: 1797
|
| 9 |
+
:Number of Attributes: 64
|
| 10 |
+
:Attribute Information: 8x8 image of integer pixels in the range 0..16.
|
| 11 |
+
:Missing Attribute Values: None
|
| 12 |
+
:Creator: E. Alpaydin (alpaydin '@' boun.edu.tr)
|
| 13 |
+
:Date: July; 1998
|
| 14 |
+
|
| 15 |
+
This is a copy of the test set of the UCI ML hand-written digits datasets
|
| 16 |
+
https://archive.ics.uci.edu/ml/datasets/Optical+Recognition+of+Handwritten+Digits
|
| 17 |
+
|
| 18 |
+
The data set contains images of hand-written digits: 10 classes where
|
| 19 |
+
each class refers to a digit.
|
| 20 |
+
|
| 21 |
+
Preprocessing programs made available by NIST were used to extract
|
| 22 |
+
normalized bitmaps of handwritten digits from a preprinted form. From a
|
| 23 |
+
total of 43 people, 30 contributed to the training set and different 13
|
| 24 |
+
to the test set. 32x32 bitmaps are divided into nonoverlapping blocks of
|
| 25 |
+
4x4 and the number of on pixels are counted in each block. This generates
|
| 26 |
+
an input matrix of 8x8 where each element is an integer in the range
|
| 27 |
+
0..16. This reduces dimensionality and gives invariance to small
|
| 28 |
+
distortions.
|
| 29 |
+
|
| 30 |
+
For info on NIST preprocessing routines, see M. D. Garris, J. L. Blue, G.
|
| 31 |
+
T. Candela, D. L. Dimmick, J. Geist, P. J. Grother, S. A. Janet, and C.
|
| 32 |
+
L. Wilson, NIST Form-Based Handprint Recognition System, NISTIR 5469,
|
| 33 |
+
1994.
|
| 34 |
+
|
| 35 |
+
.. dropdown:: References
|
| 36 |
+
|
| 37 |
+
- C. Kaynak (1995) Methods of Combining Multiple Classifiers and Their
|
| 38 |
+
Applications to Handwritten Digit Recognition, MSc Thesis, Institute of
|
| 39 |
+
Graduate Studies in Science and Engineering, Bogazici University.
|
| 40 |
+
- E. Alpaydin, C. Kaynak (1998) Cascading Classifiers, Kybernetika.
|
| 41 |
+
- Ken Tang and Ponnuthurai N. Suganthan and Xi Yao and A. Kai Qin.
|
| 42 |
+
Linear dimensionalityreduction using relevance weighted LDA. School of
|
| 43 |
+
Electrical and Electronic Engineering Nanyang Technological University.
|
| 44 |
+
2005.
|
| 45 |
+
- Claudio Gentile. A New Approximate Maximal Margin Classification
|
| 46 |
+
Algorithm. NIPS. 2000.
|
miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/datasets/descr/iris.rst
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
.. _iris_dataset:
|
| 2 |
+
|
| 3 |
+
Iris plants dataset
|
| 4 |
+
--------------------
|
| 5 |
+
|
| 6 |
+
**Data Set Characteristics:**
|
| 7 |
+
|
| 8 |
+
:Number of Instances: 150 (50 in each of three classes)
|
| 9 |
+
:Number of Attributes: 4 numeric, predictive attributes and the class
|
| 10 |
+
:Attribute Information:
|
| 11 |
+
- sepal length in cm
|
| 12 |
+
- sepal width in cm
|
| 13 |
+
- petal length in cm
|
| 14 |
+
- petal width in cm
|
| 15 |
+
- class:
|
| 16 |
+
- Iris-Setosa
|
| 17 |
+
- Iris-Versicolour
|
| 18 |
+
- Iris-Virginica
|
| 19 |
+
|
| 20 |
+
:Summary Statistics:
|
| 21 |
+
|
| 22 |
+
============== ==== ==== ======= ===== ====================
|
| 23 |
+
Min Max Mean SD Class Correlation
|
| 24 |
+
============== ==== ==== ======= ===== ====================
|
| 25 |
+
sepal length: 4.3 7.9 5.84 0.83 0.7826
|
| 26 |
+
sepal width: 2.0 4.4 3.05 0.43 -0.4194
|
| 27 |
+
petal length: 1.0 6.9 3.76 1.76 0.9490 (high!)
|
| 28 |
+
petal width: 0.1 2.5 1.20 0.76 0.9565 (high!)
|
| 29 |
+
============== ==== ==== ======= ===== ====================
|
| 30 |
+
|
| 31 |
+
:Missing Attribute Values: None
|
| 32 |
+
:Class Distribution: 33.3% for each of 3 classes.
|
| 33 |
+
:Creator: R.A. Fisher
|
| 34 |
+
:Donor: Michael Marshall (MARSHALL%PLU@io.arc.nasa.gov)
|
| 35 |
+
:Date: July, 1988
|
| 36 |
+
|
| 37 |
+
The famous Iris database, first used by Sir R.A. Fisher. The dataset is taken
|
| 38 |
+
from Fisher's paper. Note that it's the same as in R, but not as in the UCI
|
| 39 |
+
Machine Learning Repository, which has two wrong data points.
|
| 40 |
+
|
| 41 |
+
This is perhaps the best known database to be found in the
|
| 42 |
+
pattern recognition literature. Fisher's paper is a classic in the field and
|
| 43 |
+
is referenced frequently to this day. (See Duda & Hart, for example.) The
|
| 44 |
+
data set contains 3 classes of 50 instances each, where each class refers to a
|
| 45 |
+
type of iris plant. One class is linearly separable from the other 2; the
|
| 46 |
+
latter are NOT linearly separable from each other.
|
| 47 |
+
|
| 48 |
+
.. dropdown:: References
|
| 49 |
+
|
| 50 |
+
- Fisher, R.A. "The use of multiple measurements in taxonomic problems"
|
| 51 |
+
Annual Eugenics, 7, Part II, 179-188 (1936); also in "Contributions to
|
| 52 |
+
Mathematical Statistics" (John Wiley, NY, 1950).
|
| 53 |
+
- Duda, R.O., & Hart, P.E. (1973) Pattern Classification and Scene Analysis.
|
| 54 |
+
(Q327.D83) John Wiley & Sons. ISBN 0-471-22361-1. See page 218.
|
| 55 |
+
- Dasarathy, B.V. (1980) "Nosing Around the Neighborhood: A New System
|
| 56 |
+
Structure and Classification Rule for Recognition in Partially Exposed
|
| 57 |
+
Environments". IEEE Transactions on Pattern Analysis and Machine
|
| 58 |
+
Intelligence, Vol. PAMI-2, No. 1, 67-71.
|
| 59 |
+
- Gates, G.W. (1972) "The Reduced Nearest Neighbor Rule". IEEE Transactions
|
| 60 |
+
on Information Theory, May 1972, 431-433.
|
| 61 |
+
- See also: 1988 MLC Proceedings, 54-64. Cheeseman et al"s AUTOCLASS II
|
| 62 |
+
conceptual clustering system finds 3 classes in the data.
|
| 63 |
+
- Many, many more ...
|
miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/datasets/descr/kddcup99.rst
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
.. _kddcup99_dataset:
|
| 2 |
+
|
| 3 |
+
Kddcup 99 dataset
|
| 4 |
+
-----------------
|
| 5 |
+
|
| 6 |
+
The KDD Cup '99 dataset was created by processing the tcpdump portions
|
| 7 |
+
of the 1998 DARPA Intrusion Detection System (IDS) Evaluation dataset,
|
| 8 |
+
created by MIT Lincoln Lab [2]_. The artificial data (described on the `dataset's
|
| 9 |
+
homepage <https://kdd.ics.uci.edu/databases/kddcup99/kddcup99.html>`_) was
|
| 10 |
+
generated using a closed network and hand-injected attacks to produce a
|
| 11 |
+
large number of different types of attack with normal activity in the
|
| 12 |
+
background. As the initial goal was to produce a large training set for
|
| 13 |
+
supervised learning algorithms, there is a large proportion (80.1%) of
|
| 14 |
+
abnormal data which is unrealistic in real world, and inappropriate for
|
| 15 |
+
unsupervised anomaly detection which aims at detecting 'abnormal' data, i.e.:
|
| 16 |
+
|
| 17 |
+
* qualitatively different from normal data
|
| 18 |
+
* in large minority among the observations.
|
| 19 |
+
|
| 20 |
+
We thus transform the KDD Data set into two different data sets: SA and SF.
|
| 21 |
+
|
| 22 |
+
* SA is obtained by simply selecting all the normal data, and a small
|
| 23 |
+
proportion of abnormal data to gives an anomaly proportion of 1%.
|
| 24 |
+
|
| 25 |
+
* SF is obtained as in [3]_
|
| 26 |
+
by simply picking up the data whose attribute logged_in is positive, thus
|
| 27 |
+
focusing on the intrusion attack, which gives a proportion of 0.3% of
|
| 28 |
+
attack.
|
| 29 |
+
|
| 30 |
+
* http and smtp are two subsets of SF corresponding with third feature
|
| 31 |
+
equal to 'http' (resp. to 'smtp').
|
| 32 |
+
|
| 33 |
+
General KDD structure:
|
| 34 |
+
|
| 35 |
+
================ ==========================================
|
| 36 |
+
Samples total 4898431
|
| 37 |
+
Dimensionality 41
|
| 38 |
+
Features discrete (int) or continuous (float)
|
| 39 |
+
Targets str, 'normal.' or name of the anomaly type
|
| 40 |
+
================ ==========================================
|
| 41 |
+
|
| 42 |
+
SA structure:
|
| 43 |
+
|
| 44 |
+
================ ==========================================
|
| 45 |
+
Samples total 976158
|
| 46 |
+
Dimensionality 41
|
| 47 |
+
Features discrete (int) or continuous (float)
|
| 48 |
+
Targets str, 'normal.' or name of the anomaly type
|
| 49 |
+
================ ==========================================
|
| 50 |
+
|
| 51 |
+
SF structure:
|
| 52 |
+
|
| 53 |
+
================ ==========================================
|
| 54 |
+
Samples total 699691
|
| 55 |
+
Dimensionality 4
|
| 56 |
+
Features discrete (int) or continuous (float)
|
| 57 |
+
Targets str, 'normal.' or name of the anomaly type
|
| 58 |
+
================ ==========================================
|
| 59 |
+
|
| 60 |
+
http structure:
|
| 61 |
+
|
| 62 |
+
================ ==========================================
|
| 63 |
+
Samples total 619052
|
| 64 |
+
Dimensionality 3
|
| 65 |
+
Features discrete (int) or continuous (float)
|
| 66 |
+
Targets str, 'normal.' or name of the anomaly type
|
| 67 |
+
================ ==========================================
|
| 68 |
+
|
| 69 |
+
smtp structure:
|
| 70 |
+
|
| 71 |
+
================ ==========================================
|
| 72 |
+
Samples total 95373
|
| 73 |
+
Dimensionality 3
|
| 74 |
+
Features discrete (int) or continuous (float)
|
| 75 |
+
Targets str, 'normal.' or name of the anomaly type
|
| 76 |
+
================ ==========================================
|
| 77 |
+
|
| 78 |
+
:func:`sklearn.datasets.fetch_kddcup99` will load the kddcup99 dataset; it
|
| 79 |
+
returns a dictionary-like object with the feature matrix in the ``data`` member
|
| 80 |
+
and the target values in ``target``. The "as_frame" optional argument converts
|
| 81 |
+
``data`` into a pandas DataFrame and ``target`` into a pandas Series. The
|
| 82 |
+
dataset will be downloaded from the web if necessary.
|
| 83 |
+
|
| 84 |
+
.. rubric:: References
|
| 85 |
+
|
| 86 |
+
.. [2] Analysis and Results of the 1999 DARPA Off-Line Intrusion
|
| 87 |
+
Detection Evaluation, Richard Lippmann, Joshua W. Haines,
|
| 88 |
+
David J. Fried, Jonathan Korba, Kumar Das.
|
| 89 |
+
|
| 90 |
+
.. [3] K. Yamanishi, J.-I. Takeuchi, G. Williams, and P. Milne. Online
|
| 91 |
+
unsupervised outlier detection using finite mixtures with
|
| 92 |
+
discounting learning algorithms. In Proceedings of the sixth
|
| 93 |
+
ACM SIGKDD international conference on Knowledge discovery
|
| 94 |
+
and data mining, pages 320-324. ACM Press, 2000.
|
miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/datasets/descr/lfw.rst
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
.. _labeled_faces_in_the_wild_dataset:
|
| 2 |
+
|
| 3 |
+
The Labeled Faces in the Wild face recognition dataset
|
| 4 |
+
------------------------------------------------------
|
| 5 |
+
|
| 6 |
+
This dataset is a collection of JPEG pictures of famous people collected
|
| 7 |
+
over the internet, and the details are available on the Kaggle website:
|
| 8 |
+
|
| 9 |
+
https://www.kaggle.com/datasets/jessicali9530/lfw-dataset
|
| 10 |
+
|
| 11 |
+
Each picture is centered on a single face. The typical task is called
|
| 12 |
+
Face Verification: given a pair of two pictures, a binary classifier
|
| 13 |
+
must predict whether the two images are from the same person.
|
| 14 |
+
|
| 15 |
+
An alternative task, Face Recognition or Face Identification is:
|
| 16 |
+
given the picture of the face of an unknown person, identify the name
|
| 17 |
+
of the person by referring to a gallery of previously seen pictures of
|
| 18 |
+
identified persons.
|
| 19 |
+
|
| 20 |
+
Both Face Verification and Face Recognition are tasks that are typically
|
| 21 |
+
performed on the output of a model trained to perform Face Detection. The
|
| 22 |
+
most popular model for Face Detection is called Viola-Jones and is
|
| 23 |
+
implemented in the OpenCV library. The LFW faces were extracted by this
|
| 24 |
+
face detector from various online websites.
|
| 25 |
+
|
| 26 |
+
**Data Set Characteristics:**
|
| 27 |
+
|
| 28 |
+
================= =======================
|
| 29 |
+
Classes 5749
|
| 30 |
+
Samples total 13233
|
| 31 |
+
Dimensionality 5828
|
| 32 |
+
Features real, between 0 and 255
|
| 33 |
+
================= =======================
|
| 34 |
+
|
| 35 |
+
.. dropdown:: Usage
|
| 36 |
+
|
| 37 |
+
``scikit-learn`` provides two loaders that will automatically download,
|
| 38 |
+
cache, parse the metadata files, decode the jpeg and convert the
|
| 39 |
+
interesting slices into memmapped numpy arrays. This dataset size is more
|
| 40 |
+
than 200 MB. The first load typically takes more than a couple of minutes
|
| 41 |
+
to fully decode the relevant part of the JPEG files into numpy arrays. If
|
| 42 |
+
the dataset has been loaded once, the following times the loading times
|
| 43 |
+
less than 200ms by using a memmapped version memoized on the disk in the
|
| 44 |
+
``~/scikit_learn_data/lfw_home/`` folder using ``joblib``.
|
| 45 |
+
|
| 46 |
+
The first loader is used for the Face Identification task: a multi-class
|
| 47 |
+
classification task (hence supervised learning)::
|
| 48 |
+
|
| 49 |
+
>>> from sklearn.datasets import fetch_lfw_people
|
| 50 |
+
>>> lfw_people = fetch_lfw_people(min_faces_per_person=70, resize=0.4)
|
| 51 |
+
|
| 52 |
+
>>> for name in lfw_people.target_names:
|
| 53 |
+
... print(name)
|
| 54 |
+
...
|
| 55 |
+
Ariel Sharon
|
| 56 |
+
Colin Powell
|
| 57 |
+
Donald Rumsfeld
|
| 58 |
+
George W Bush
|
| 59 |
+
Gerhard Schroeder
|
| 60 |
+
Hugo Chavez
|
| 61 |
+
Tony Blair
|
| 62 |
+
|
| 63 |
+
The default slice is a rectangular shape around the face, removing
|
| 64 |
+
most of the background::
|
| 65 |
+
|
| 66 |
+
>>> lfw_people.data.dtype
|
| 67 |
+
dtype('float32')
|
| 68 |
+
|
| 69 |
+
>>> lfw_people.data.shape
|
| 70 |
+
(1288, 1850)
|
| 71 |
+
|
| 72 |
+
>>> lfw_people.images.shape
|
| 73 |
+
(1288, 50, 37)
|
| 74 |
+
|
| 75 |
+
Each of the ``1140`` faces is assigned to a single person id in the ``target``
|
| 76 |
+
array::
|
| 77 |
+
|
| 78 |
+
>>> lfw_people.target.shape
|
| 79 |
+
(1288,)
|
| 80 |
+
|
| 81 |
+
>>> list(lfw_people.target[:10])
|
| 82 |
+
[5, 6, 3, 1, 0, 1, 3, 4, 3, 0]
|
| 83 |
+
|
| 84 |
+
The second loader is typically used for the face verification task: each sample
|
| 85 |
+
is a pair of two picture belonging or not to the same person::
|
| 86 |
+
|
| 87 |
+
>>> from sklearn.datasets import fetch_lfw_pairs
|
| 88 |
+
>>> lfw_pairs_train = fetch_lfw_pairs(subset='train')
|
| 89 |
+
|
| 90 |
+
>>> list(lfw_pairs_train.target_names)
|
| 91 |
+
['Different persons', 'Same person']
|
| 92 |
+
|
| 93 |
+
>>> lfw_pairs_train.pairs.shape
|
| 94 |
+
(2200, 2, 62, 47)
|
| 95 |
+
|
| 96 |
+
>>> lfw_pairs_train.data.shape
|
| 97 |
+
(2200, 5828)
|
| 98 |
+
|
| 99 |
+
>>> lfw_pairs_train.target.shape
|
| 100 |
+
(2200,)
|
| 101 |
+
|
| 102 |
+
Both for the :func:`sklearn.datasets.fetch_lfw_people` and
|
| 103 |
+
:func:`sklearn.datasets.fetch_lfw_pairs` function it is
|
| 104 |
+
possible to get an additional dimension with the RGB color channels by
|
| 105 |
+
passing ``color=True``, in that case the shape will be
|
| 106 |
+
``(2200, 2, 62, 47, 3)``.
|
| 107 |
+
|
| 108 |
+
The :func:`sklearn.datasets.fetch_lfw_pairs` datasets is subdivided into
|
| 109 |
+
3 subsets: the development ``train`` set, the development ``test`` set and
|
| 110 |
+
an evaluation ``10_folds`` set meant to compute performance metrics using a
|
| 111 |
+
10-folds cross validation scheme.
|
| 112 |
+
|
| 113 |
+
.. rubric:: References
|
| 114 |
+
|
| 115 |
+
* `Labeled Faces in the Wild: A Database for Studying Face Recognition
|
| 116 |
+
in Unconstrained Environments.
|
| 117 |
+
<https://people.cs.umass.edu/~elm/papers/lfw.pdf>`_
|
| 118 |
+
Gary B. Huang, Manu Ramesh, Tamara Berg, and Erik Learned-Miller.
|
| 119 |
+
University of Massachusetts, Amherst, Technical Report 07-49, October, 2007.
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
.. rubric:: Examples
|
| 123 |
+
|
| 124 |
+
* :ref:`sphx_glr_auto_examples_applications_plot_face_recognition.py`
|
miniconda3/envs/ladir/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/ladir/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/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/sklearn/datasets/descr/twenty_newsgroups.rst
ADDED
|
@@ -0,0 +1,248 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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/ladir/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/ladir/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/ladir/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/ladir/lib/python3.10/site-packages/sklearn/datasets/meson.build
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
py.extension_module(
|
| 2 |
+
'_svmlight_format_fast',
|
| 3 |
+
cython_gen.process('_svmlight_format_fast.pyx'),
|
| 4 |
+
dependencies: [np_dep],
|
| 5 |
+
subdir: 'sklearn/datasets',
|
| 6 |
+
install: true
|
| 7 |
+
)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/datasets/tests/__init__.py
ADDED
|
File without changes
|
miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/datasets/tests/data/__init__.py
ADDED
|
File without changes
|
miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/datasets/tests/data/openml/__init__.py
ADDED
|
File without changes
|
miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/datasets/tests/data/openml/id_1/__init__.py
ADDED
|
File without changes
|
miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/datasets/tests/data/openml/id_1119/__init__.py
ADDED
|
File without changes
|
miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/datasets/tests/data/openml/id_1590/__init__.py
ADDED
|
File without changes
|
miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/datasets/tests/data/openml/id_2/__init__.py
ADDED
|
File without changes
|
miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/datasets/tests/data/openml/id_292/__init__.py
ADDED
|
File without changes
|
miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/datasets/tests/data/openml/id_3/__init__.py
ADDED
|
File without changes
|
miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/datasets/tests/data/openml/id_40589/__init__.py
ADDED
|
File without changes
|
miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/datasets/tests/data/openml/id_40675/__init__.py
ADDED
|
File without changes
|
miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/datasets/tests/data/openml/id_40945/__init__.py
ADDED
|
File without changes
|