sslearn.datasets
Summary of module sslearn.datasets:
This module contains functions to load and save datasets in different formats.
Functions
- read_csv : Load a dataset from a CSV file.
- read_keel : Load a dataset from a KEEL file.
- secure_dataset : Secure the dataset by converting it into a secure format.
- save_keel : Save a dataset in KEEL format.
1""" 2Summary of module `sslearn.datasets`: 3 4This module contains functions to load and save datasets in different formats. 5 6## Functions 7 81. read_csv : Load a dataset from a CSV file. 92. read_keel : Load a dataset from a KEEL file. 103. secure_dataset : Secure the dataset by converting it into a secure format. 114. save_keel : Save a dataset in KEEL format. 12 13 14""" 15 16from ._loader import read_csv, read_keel 17from ._writer import save_keel 18from ._preprocess import secure_dataset 19 20__all__ = ["read_csv", "read_keel", "secure_dataset", "save_keel"]
def
read_csv( path, format='pandas', secure=False, target_col=-1, is_regression=False, **kwards):
103def read_csv(path, format="pandas", secure=False, target_col=-1, is_regression=False, **kwards): 104 """Read a .csv file 105 106 Parameters 107 ---------- 108 path : str 109 File path 110 format : str, optional 111 Object that will contain the data, it can be `numpy` or `pandas`, by default "pandas" 112 secure : bool, optional 113 It guarantees that the dataset has not `-1` as valid class, in order to make it semi-supervised after, by default False 114 target_col : {str, int, None}, optional 115 Column name or index to select class column, if None use the default value stored in the file, by default None 116 is_regression: bool, optional 117 Indicates if the data set is for regression, if True, target value of unlabeled instances must be None in the csv, by default False 118 119 Returns 120 ------- 121 X, y: array_like 122 Dataset loaded. 123 """ 124 if format not in ["pandas", "numpy"]: 125 raise AttributeError("Formats allowed are `pandas` or `numpy`") 126 data = pd.read_csv(path, **kwards) 127 128 if target_col is None: 129 raise AttributeError("`read_csv` do not allow a `None` value for `target_col`, use `integer` or `string` instead.") 130 elif isinstance(target_col, str): 131 target_col = data.columns.index(target_col) 132 133 X = data.iloc[:, data.columns != data.columns[target_col]] 134 y = data.iloc[:, target_col] 135 136 if not is_regression and secure: 137 X, y = secure_dataset(X, y) 138 139 if is_regression: 140 y[y == "None"] = np.nan 141 y = y.astype(float) 142 # Transform of the Series x all values that is None to NaN 143 144 145 if format == "numpy": 146 X = X.to_numpy() 147 y = y.to_numpy() 148 return X, y
Read a .csv file
Parameters
- path (str): File path
- format (str, optional):
Object that will contain the data, it can be
numpyorpandas, by default "pandas" - secure (bool, optional):
It guarantees that the dataset has not
-1as valid class, in order to make it semi-supervised after, by default False - target_col ({str, int, None}, optional): Column name or index to select class column, if None use the default value stored in the file, by default None
- is_regression (bool, optional): Indicates if the data set is for regression, if True, target value of unlabeled instances must be None in the csv, by default False
Returns
- X, y (array_like): Dataset loaded.
def
read_keel( path, format='pandas', secure=False, target_col=None, encoding='utf-8', is_regression=False, **kwards):
16def read_keel(path, format="pandas", secure=False, target_col=None, encoding="utf-8", is_regression=False, **kwards): 17 """Read a .dat file from KEEL (http://www.keel.es/) 18 19 Parameters 20 ---------- 21 path : str 22 File path 23 format : str, optional 24 Object that will contain the data, it can be `numpy` or `pandas`, by default "pandas" 25 secure : bool, optional 26 It guarantees that the dataset has not `-1` as valid class, in order to make it semi-supervised after, by default False 27 target_col : {str, int, None}, optional 28 Column name or index to select class column, if None use the default value stored in the file, by default None 29 encoding: str, optional 30 Encoding of file, by default "utf-8" 31 is_regression: bool, optional 32 Indicates if the data set is for regression, if True, target value of unlabeled instances is set to np.nan, by default False 33 34 Returns 35 ------- 36 X, y: array_like 37 Dataset loaded. 38 """ 39 if format not in ["pandas", "numpy"]: 40 raise AttributeError("Formats allowed are `pandas` or `numpy`") 41 42 attributes = [] 43 types = [] 44 target = None 45 with open(path, "r") as file: 46 lines = file.readlines() 47 counter = 1 48 for line in lines: 49 counter += 1 50 if "@attribute" in line: 51 parts = line.split(" ") 52 name_ = parts[1] 53 type_ = parts[2] 54 if type_[0] == "{": 55 type_ = "string" 56 attributes.append(name_) 57 types.append(keel_type_cheat[type_]) 58 elif "@outputs" in line: 59 target = line.split(" ")[1].strip('\n') 60 elif "@data" in line: 61 break 62 if target is None: 63 target = attributes[-1] 64 data = pd.read_csv(path, skiprows=counter-1, header=None, **kwards) 65 if len(data.columns) != len(attributes): 66 warnings.warn(f"The dataset's have {len(data.columns)} columns but file declares {len(attributes)}.", RuntimeWarning) 67 X = data 68 y = None 69 else: 70 data.columns = attributes 71 data = data.astype(dict(zip(attributes, types))) 72 for att, tp in zip(attributes, types): 73 if tp == "string": 74 data[att] = data[att].str.strip() 75 if target_col is None: 76 target_col = target 77 elif isinstance(target_col, int): 78 target_col = data.columns[target_col] 79 80 att_columns = attributes.copy() 81 att_columns.remove(target_col) 82 83 X = data[att_columns] 84 y = data[target_col] 85 86 if is_regression: 87 y[y == "unlabeled"] = np.nan 88 y = y.astype(float) 89 else: 90 y[y == "unlabeled"] = y.dtype.type(-1) 91 if secure: 92 X, y = secure_dataset(X, y) 93 94 if format == "numpy": 95 X = X.to_numpy().astype(float) 96 y = y.to_numpy() 97 if y.dtype == object: 98 y = y.astype("str") 99 100 return X, y
Read a .dat file from KEEL (http://www.keel.es/)
Parameters
- path (str): File path
- format (str, optional):
Object that will contain the data, it can be
numpyorpandas, by default "pandas" - secure (bool, optional):
It guarantees that the dataset has not
-1as valid class, in order to make it semi-supervised after, by default False - target_col ({str, int, None}, optional): Column name or index to select class column, if None use the default value stored in the file, by default None
- encoding (str, optional): Encoding of file, by default "utf-8"
- is_regression (bool, optional): Indicates if the data set is for regression, if True, target value of unlabeled instances is set to np.nan, by default False
Returns
- X, y (array_like): Dataset loaded.
def
secure_dataset(X, y):
2def secure_dataset(X, y): 3 """It guarantees that the dataset has not `-1` as valid class, in order to make it semi-supervised after 4 5 Parameters 6 ---------- 7 X : Array-like 8 Ignored 9 y : Array-like 10 Target array. 11 12 Returns 13 ------- 14 X, y: array_like 15 Dataset securized. 16 """ 17 if y.dtype.type(-1) in y.tolist(): 18 raise ValueError("The dataset contains -1 as valid class. Please, change it to another value.") 19 return X, y 20 # if np.issubdtype(y.dtype, np.number): 21 # y = y + 2 22 23 # return X, y
It guarantees that the dataset has not -1 as valid class, in order to make it semi-supervised after
Parameters
- X (Array-like): Ignored
- y (Array-like): Target array.
Returns
- X, y (array_like): Dataset securized.
def
save_keel( X, y, route, name=None, attribute_name=None, target_name='Class', classification=True, unlabeled=True, force_targets=None):
8def save_keel(X, y, route, name=None, attribute_name=None, target_name="Class", classification=True, unlabeled=True, force_targets=None): 9 """Save a dataset in the KEEL format 10 11 Parameters 12 ---------- 13 X : array-like 14 Dataset features 15 y : array-like 16 Dataset targets 17 route : str 18 Path to save the dataset 19 name : str, optional 20 Dataset name, if None the route basename will be selected, by default None 21 attribute_name : list, optional 22 List of attribute names, if None the default names will be used, by default None 23 target_name : str, optional 24 Target name, by default "Class" 25 classification : bool, optional 26 If the dataset is classification or regression, by default True 27 unlabeled : bool, optional 28 If the dataset has unlabeled instances, by default True 29 force_targets : collection, optional 30 Force the targets to be a specific value, by default None 31 """ 32 columns = [] 33 types = [] 34 min_max = [] 35 if name is None: 36 name = os.path.basename(route).split(".")[0] 37 38 unlabel_target = y == y.dtype.type(-1) 39 if classification: 40 y = y.astype("str") 41 42 if unlabeled: 43 y = y.astype("str") 44 if y.dtype.itemsize < np.array("unlabeled").dtype.itemsize: 45 y = y.astype(f"<U{len('unlabeled')}") 46 y[unlabel_target] = "unlabeled" 47 if force_targets is not None: 48 force_targets = force_targets.copy() 49 force_targets.append("unlabeled") 50 51 # Generate attributes: 52 if attribute_name is None: 53 if isinstance(X, pd.DataFrame): 54 attribute_name = X.columns 55 elif isinstance(X, np.ndarray): 56 attribute_name = [f"a{i}" for i in range(X.shape[-1])] 57 if not isinstance(X, pd.DataFrame): 58 X = pd.DataFrame(X) 59 data = pd.concat([X, pd.Series(y).rename(target_name)], axis=1) 60 for i, col in enumerate(data): 61 if i < len(attribute_name) and attribute_name[i] != col: 62 columns.append(attribute_name[i]) 63 else: 64 columns.append(col) 65 numeric = False 66 if data[col].dtype.kind in "ui": 67 numeric = True 68 types.append(" integer") 69 elif data[col].dtype.kind == "f": 70 numeric = True 71 types.append(" real") 72 elif data[col].dtype.kind in "bSOU": 73 types.append("") 74 if numeric: 75 min_max.append(f" [{data[col].min()},{data[col].max()}]") 76 else: 77 if col == target_name and force_targets is not None: 78 min_max.append(" {" + ",".join(force_targets) + "}") 79 else: 80 min_max.append(" {" + ",".join(data[col].unique()) + "}") 81 82 # Generate header 83 value = f"@relation {name}" 84 for c, t, mm in zip(columns, types, min_max): 85 value += f"\n@attribute {c}{t}{mm}" 86 87 value += "\n@inputs " + ",".join(attribute_name) 88 value += f"\n@outputs {target_name}" 89 value += "\n@data\n" 90 with open(route, "w") as f: 91 f.write(value) 92 data.to_csv(f, index=False, header=False)
Save a dataset in the KEEL format
Parameters
- X (array-like): Dataset features
- y (array-like): Dataset targets
- route (str): Path to save the dataset
- name (str, optional): Dataset name, if None the route basename will be selected, by default None
- attribute_name (list, optional): List of attribute names, if None the default names will be used, by default None
- target_name (str, optional): Target name, by default "Class"
- classification (bool, optional): If the dataset is classification or regression, by default True
- unlabeled (bool, optional): If the dataset has unlabeled instances, by default True
- force_targets (collection, optional): Force the targets to be a specific value, by default None