pucktrick 0.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pucktrick/__init__.py +1 -0
- pucktrick/duplicated.py +123 -0
- pucktrick/labels.py +44 -0
- pucktrick/missing.py +129 -0
- pucktrick/noisy.py +132 -0
- pucktrick/outliers.py +151 -0
- pucktrick/utils.py +421 -0
- pucktrick-0.0.0.dist-info/METADATA +5 -0
- pucktrick-0.0.0.dist-info/RECORD +12 -0
- pucktrick-0.0.0.dist-info/WHEEL +5 -0
- pucktrick-0.0.0.dist-info/licenses/LICENCE +79 -0
- pucktrick-0.0.0.dist-info/top_level.txt +1 -0
pucktrick/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.5.0"
|
pucktrick/duplicated.py
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
from pucktrick.utils import *
|
|
2
|
+
|
|
3
|
+
def duplicate(train_df, strategy=None, original_df=None ):
|
|
4
|
+
if original_df is None:
|
|
5
|
+
original_df = train_df
|
|
6
|
+
|
|
7
|
+
#with open(strategy, 'r') as file:
|
|
8
|
+
# strategy = json.load(file)
|
|
9
|
+
#strategy = strategy.get("strategy", {})
|
|
10
|
+
affected_features = strategy.get("affected_features")
|
|
11
|
+
selection_criteria = strategy.get("selection_criteria")
|
|
12
|
+
percentage = strategy.get("percentage")
|
|
13
|
+
mode = strategy.get("mode")
|
|
14
|
+
perturbate_config = strategy.get("perturbate_data", {})
|
|
15
|
+
distr1 = perturbate_config.get("distribution")
|
|
16
|
+
value = perturbate_config.get("value", [])
|
|
17
|
+
condition_logic = perturbate_config.get("condition_logic", None)
|
|
18
|
+
params = perturbate_config.get("param", {})
|
|
19
|
+
|
|
20
|
+
if affected_features and not isinstance(affected_features, list):
|
|
21
|
+
affected_features = [affected_features]
|
|
22
|
+
|
|
23
|
+
if selection_criteria in [
|
|
24
|
+
"class",
|
|
25
|
+
"upper_lower",
|
|
26
|
+
"replace_punctuation",
|
|
27
|
+
"remove_replace",
|
|
28
|
+
"abbreviate_text",
|
|
29
|
+
"shuffle_words",
|
|
30
|
+
]:
|
|
31
|
+
# Costruzione dei filtri
|
|
32
|
+
filters = []
|
|
33
|
+
|
|
34
|
+
if value is None or not any(value):
|
|
35
|
+
filters = [
|
|
36
|
+
(original_df[col].notnull() if mode == "extended" else train_df[col].notnull())
|
|
37
|
+
for col in affected_features
|
|
38
|
+
]
|
|
39
|
+
else:
|
|
40
|
+
for col, val in zip(affected_features, value):
|
|
41
|
+
if val is not None:
|
|
42
|
+
filters.append(
|
|
43
|
+
(original_df[col] == val) if mode == "extended" else (train_df[col] == val)
|
|
44
|
+
)
|
|
45
|
+
else:
|
|
46
|
+
filters.append(
|
|
47
|
+
(original_df[col].notnull()) if mode == "extended" else (train_df[col].notnull())
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
# Combina i filtri con logica "or" o "and"
|
|
51
|
+
if condition_logic == "and":
|
|
52
|
+
combined_filter = pd.Series(True, index=train_df.index if mode != "extended" else original_df.index)
|
|
53
|
+
for f in filters:
|
|
54
|
+
combined_filter &= f
|
|
55
|
+
elif condition_logic == "or":
|
|
56
|
+
combined_filter = pd.Series(False, index=train_df.index if mode != "extended" else original_df.index)
|
|
57
|
+
for f in filters:
|
|
58
|
+
combined_filter |= f
|
|
59
|
+
elif condition_logic is None:
|
|
60
|
+
# Default: "and" logic
|
|
61
|
+
combined_filter = pd.Series(True, index=train_df.index if mode != "extended" else original_df.index)
|
|
62
|
+
for f in filters:
|
|
63
|
+
combined_filter &= f
|
|
64
|
+
else:
|
|
65
|
+
raise ValueError(f"Unsupported condition_logic '{condition_logic}'")
|
|
66
|
+
|
|
67
|
+
# Filtrare le righe
|
|
68
|
+
target_df = original_df if mode == "extended" else train_df
|
|
69
|
+
filtered_df = target_df[combined_filter].reset_index(drop=True)
|
|
70
|
+
|
|
71
|
+
rowsToChange = int(len(filtered_df) * percentage)
|
|
72
|
+
if mode == "extended":
|
|
73
|
+
old_duplicated = len(train_df) - len(original_df)
|
|
74
|
+
new_rowsToChange = rowsToChange - old_duplicated
|
|
75
|
+
if new_rowsToChange <= 0:
|
|
76
|
+
return train_df
|
|
77
|
+
percentage = new_rowsToChange / len(filtered_df)
|
|
78
|
+
|
|
79
|
+
sampled_indices = sample_indices(distr1, filtered_df, percentage, params,number=None)
|
|
80
|
+
sampled_rows = filtered_df.iloc[sampled_indices].copy()
|
|
81
|
+
|
|
82
|
+
for col in affected_features:
|
|
83
|
+
if selection_criteria == "shuffle_words":
|
|
84
|
+
sampled_rows[col] = sampled_rows[col].astype(str).apply(shuffle_words)
|
|
85
|
+
elif selection_criteria == "abbreviate_text":
|
|
86
|
+
sampled_rows[col] = sampled_rows[col].astype(str).apply(abbreviate_text)
|
|
87
|
+
elif selection_criteria == "replace_punctuation":
|
|
88
|
+
sampled_rows[col] = sampled_rows[col].astype(str).apply(replace_punctuation)
|
|
89
|
+
elif selection_criteria == "remove_replace":
|
|
90
|
+
sampled_rows[col] = sampled_rows[col].astype(str).apply(remove_or_replace)
|
|
91
|
+
elif selection_criteria == "upper_lower":
|
|
92
|
+
sampled_rows[col] = random_upper_lower(sampled_rows[col])
|
|
93
|
+
|
|
94
|
+
noise_df = pd.concat([train_df, sampled_rows], ignore_index=True)
|
|
95
|
+
|
|
96
|
+
elif selection_criteria == 'all':
|
|
97
|
+
if mode == "extended":
|
|
98
|
+
rowsToChange = len(original_df) * percentage
|
|
99
|
+
old_duplicated = original_df.duplicated().sum()
|
|
100
|
+
new_duplicated = train_df.duplicated().sum()
|
|
101
|
+
diff = new_duplicated - old_duplicated
|
|
102
|
+
new_rowsToChange = rowsToChange - diff
|
|
103
|
+
if new_rowsToChange <= 0:
|
|
104
|
+
return train_df
|
|
105
|
+
new_percentage = new_rowsToChange / len(original_df)
|
|
106
|
+
noise_df = train_df.copy()
|
|
107
|
+
sampled_indices = sample_indices(distr1, original_df, new_percentage, params)
|
|
108
|
+
sampled_rows = original_df.iloc[sampled_indices]
|
|
109
|
+
noise_df = pd.concat([noise_df, sampled_rows], ignore_index=True)
|
|
110
|
+
else:
|
|
111
|
+
noise_df = train_df.copy()
|
|
112
|
+
sampled_indices = sample_indices(distr1, train_df, percentage, params)
|
|
113
|
+
sampled_rows = train_df.iloc[sampled_indices]
|
|
114
|
+
noise_df = pd.concat([noise_df, sampled_rows], ignore_index=True)
|
|
115
|
+
|
|
116
|
+
else:
|
|
117
|
+
raise ValueError(f"Unsupported selection_criteria '{selection_criteria}'.")
|
|
118
|
+
|
|
119
|
+
if "date" in noise_df.columns:
|
|
120
|
+
noise_df["date"] = noise_df["date"].astype(str).str.replace(r"\s00:00:00$", "", regex=True)
|
|
121
|
+
|
|
122
|
+
return noise_df
|
|
123
|
+
|
pucktrick/labels.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
def labels(train_df, original_df=None, strategy=None):
|
|
2
|
+
|
|
3
|
+
with open(strategy, 'r') as file:
|
|
4
|
+
strategy = json.load(file)
|
|
5
|
+
|
|
6
|
+
strategy = strategy.get("strategy", {})
|
|
7
|
+
target = strategy.get("affected_features")
|
|
8
|
+
selection_criteria = strategy.get("selection_criteria")
|
|
9
|
+
percentage = strategy.get("percentage")
|
|
10
|
+
mode = strategy.get("mode")
|
|
11
|
+
perturbate_config = strategy.get("perturbate_data", {})
|
|
12
|
+
distr1 = perturbate_config.get("distribution")
|
|
13
|
+
value = perturbate_config.get("value", [])
|
|
14
|
+
condition_logic = perturbate_config.get("condition_logic", None)
|
|
15
|
+
params= perturbate_config.get("param", {})
|
|
16
|
+
number=None
|
|
17
|
+
|
|
18
|
+
target_col = target[0] if isinstance(target, list) else target
|
|
19
|
+
unique_values = train_df[target_col].dropna().unique()
|
|
20
|
+
if len(unique_values) == 2:
|
|
21
|
+
var_type = "binary"
|
|
22
|
+
elif len(unique_values) > 2:
|
|
23
|
+
var_type = "categorical"
|
|
24
|
+
else:
|
|
25
|
+
raise ValueError(f"Unable to determine the type of target column '{target}'.")
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
if var_type == "binary":
|
|
29
|
+
#print("Target is binary")
|
|
30
|
+
if mode == 'extended':
|
|
31
|
+
noise_df= noiseBinaryExt(original_df, train_df, target_col,distr1, percentage,number,params)
|
|
32
|
+
else:
|
|
33
|
+
noise_df = noiseBinaryNew(train_df, target_col, distr1, percentage,params,number)
|
|
34
|
+
|
|
35
|
+
elif var_type == "categorical":
|
|
36
|
+
if mode == 'extended':
|
|
37
|
+
noise_df = noiseCategoricalIntExtendedExistingValues(original_df, train_df, target_col,distr1, percentage,number,params)
|
|
38
|
+
|
|
39
|
+
else:
|
|
40
|
+
noise_df = noiseCategoricalIntNewExistingValues(train_df, target_col, distr1, percentage,number,params)
|
|
41
|
+
for col in noise_df.select_dtypes(include=['int64']).columns:
|
|
42
|
+
noise_df[col] = noise_df[col].astype('Int64')
|
|
43
|
+
|
|
44
|
+
return noise_df
|
pucktrick/missing.py
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
from pucktrick.utils import *
|
|
2
|
+
|
|
3
|
+
def missing(train_df, strategy=None, original_df=None):
|
|
4
|
+
if original_df is None:
|
|
5
|
+
original_df = train_df
|
|
6
|
+
|
|
7
|
+
affected_features = strategy.get("affected_features")
|
|
8
|
+
selection_criteria = strategy.get("selection_criteria")
|
|
9
|
+
percentage = strategy.get("percentage")
|
|
10
|
+
mode = strategy.get("mode")
|
|
11
|
+
perturbate_config = strategy.get("perturbate_data", {})
|
|
12
|
+
distr1 = perturbate_config.get("distribution")
|
|
13
|
+
value = perturbate_config.get("value", [])
|
|
14
|
+
condition_logic = perturbate_config.get("condition_logic", None)
|
|
15
|
+
params= perturbate_config.get("param", {})
|
|
16
|
+
|
|
17
|
+
if affected_features and not isinstance(affected_features, list):
|
|
18
|
+
affected_features = [affected_features]
|
|
19
|
+
|
|
20
|
+
if value is None:
|
|
21
|
+
value = [None] * len(affected_features)
|
|
22
|
+
|
|
23
|
+
noise_df = train_df.copy()
|
|
24
|
+
|
|
25
|
+
if mode == 'extended':
|
|
26
|
+
filters_original = []
|
|
27
|
+
filters_train = []
|
|
28
|
+
|
|
29
|
+
for col, val in zip(affected_features, value):
|
|
30
|
+
if val is not None:
|
|
31
|
+
filters_original.append(original_df[col] == val)
|
|
32
|
+
filters_train.append(train_df[col] == val)
|
|
33
|
+
else:
|
|
34
|
+
|
|
35
|
+
filters_original.append(None)
|
|
36
|
+
filters_train.append(None)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
combined_filter_original = None
|
|
40
|
+
combined_filter_train = None
|
|
41
|
+
|
|
42
|
+
for filter_original in filters_original:
|
|
43
|
+
if filter_original is not None:
|
|
44
|
+
if combined_filter_original is None:
|
|
45
|
+
combined_filter_original = filter_original
|
|
46
|
+
else:
|
|
47
|
+
if condition_logic == "and":
|
|
48
|
+
combined_filter_original &= filter_original
|
|
49
|
+
elif condition_logic == "or":
|
|
50
|
+
combined_filter_original |= filter_original
|
|
51
|
+
|
|
52
|
+
for filter_train in filters_train:
|
|
53
|
+
if filter_train is not None:
|
|
54
|
+
if combined_filter_train is None:
|
|
55
|
+
combined_filter_train = filter_train
|
|
56
|
+
else:
|
|
57
|
+
if condition_logic == "and":
|
|
58
|
+
combined_filter_train &= filter_train
|
|
59
|
+
elif condition_logic == "or":
|
|
60
|
+
combined_filter_train |= filter_train
|
|
61
|
+
|
|
62
|
+
if combined_filter_original is not None:
|
|
63
|
+
origin_column_df = original_df[combined_filter_original]
|
|
64
|
+
else:
|
|
65
|
+
origin_column_df = original_df
|
|
66
|
+
|
|
67
|
+
if combined_filter_train is not None:
|
|
68
|
+
target_df = train_df[combined_filter_train]
|
|
69
|
+
else:
|
|
70
|
+
target_df = train_df
|
|
71
|
+
|
|
72
|
+
total_rows_to_change = round(len(origin_column_df) * percentage)
|
|
73
|
+
already_null_counts = train_df[affected_features].isnull().all(axis=1).sum()
|
|
74
|
+
new_rows_to_change = total_rows_to_change - already_null_counts
|
|
75
|
+
|
|
76
|
+
if new_rows_to_change > 0:
|
|
77
|
+
modifiable_df = target_df[~target_df[affected_features].isnull().all(axis=1)]
|
|
78
|
+
number= new_rows_to_change
|
|
79
|
+
percentage=None
|
|
80
|
+
sampled_indices = sample_indices(distr1, modifiable_df,percentage, number, params)
|
|
81
|
+
sampled_rows = modifiable_df.iloc[sampled_indices].index
|
|
82
|
+
for col in affected_features:
|
|
83
|
+
noise_df.loc[sampled_rows, col] = np.nan
|
|
84
|
+
|
|
85
|
+
else:
|
|
86
|
+
filters = []
|
|
87
|
+
|
|
88
|
+
for col, val in zip(affected_features, value):
|
|
89
|
+
if val is not None:
|
|
90
|
+
filters.append(train_df[col] == val)
|
|
91
|
+
else:
|
|
92
|
+
|
|
93
|
+
filters.append(None)
|
|
94
|
+
#print("Filtri:", filters)
|
|
95
|
+
if selection_criteria == "all":
|
|
96
|
+
combined_filter = pd.Series(True, index=train_df.index)
|
|
97
|
+
else:
|
|
98
|
+
combined_filter = None
|
|
99
|
+
for filter_condition in filters:
|
|
100
|
+
if filter_condition is not None:
|
|
101
|
+
if combined_filter is None:
|
|
102
|
+
combined_filter = filter_condition
|
|
103
|
+
else:
|
|
104
|
+
if condition_logic == "and":
|
|
105
|
+
combined_filter &= filter_condition
|
|
106
|
+
elif condition_logic == "or":
|
|
107
|
+
combined_filter |= filter_condition
|
|
108
|
+
if combined_filter is None:
|
|
109
|
+
combined_filter = pd.Series(True, index=train_df.index)
|
|
110
|
+
print("Righe selezionate:", combined_filter.sum())
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
if combined_filter is not None:
|
|
114
|
+
column_df = train_df[combined_filter]
|
|
115
|
+
else:
|
|
116
|
+
column_df = train_df
|
|
117
|
+
|
|
118
|
+
total_rows_to_change = int(len(column_df) * percentage)
|
|
119
|
+
if total_rows_to_change <= 0:
|
|
120
|
+
return noise_df
|
|
121
|
+
number= total_rows_to_change
|
|
122
|
+
percentage=None
|
|
123
|
+
sampled_indices = sample_indices(distr1, column_df, percentage,number, params)
|
|
124
|
+
sampled_rows = column_df.iloc[sampled_indices].index
|
|
125
|
+
#print(sampled_rows)
|
|
126
|
+
for col in affected_features:
|
|
127
|
+
noise_df.loc[sampled_rows, col] = np.nan
|
|
128
|
+
|
|
129
|
+
return noise_df
|
pucktrick/noisy.py
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
from pucktrick.utils import *
|
|
2
|
+
|
|
3
|
+
def noise(train_df, strategy, original_df=None):
|
|
4
|
+
if original_df is None:
|
|
5
|
+
original_df = train_df
|
|
6
|
+
|
|
7
|
+
affected_features = strategy.get("affected_features")
|
|
8
|
+
selection_criteria = strategy.get("selection_criteria")
|
|
9
|
+
percentage = strategy.get("percentage")
|
|
10
|
+
mode = strategy.get("mode")
|
|
11
|
+
perturbate_config = strategy.get("perturbate_data", {})
|
|
12
|
+
distr1 = perturbate_config.get("distribution")
|
|
13
|
+
value = perturbate_config.get("value", [])
|
|
14
|
+
condition_logic = perturbate_config.get("condition_logic", None)
|
|
15
|
+
params=perturbate_config.get("param", {})
|
|
16
|
+
|
|
17
|
+
train1_df = train_df.copy()
|
|
18
|
+
|
|
19
|
+
if mode == "extended":
|
|
20
|
+
train_df = original_df
|
|
21
|
+
noisy_df = train_df.copy()
|
|
22
|
+
if affected_features and not isinstance(affected_features, list):
|
|
23
|
+
affected_features = [affected_features]
|
|
24
|
+
|
|
25
|
+
if not value:
|
|
26
|
+
filtered_df = noisy_df
|
|
27
|
+
else:
|
|
28
|
+
row_filters = []
|
|
29
|
+
for feature, value in zip(affected_features, value):
|
|
30
|
+
if value is None:
|
|
31
|
+
row_filters.append(train_df[feature].notnull())
|
|
32
|
+
else:
|
|
33
|
+
row_filters.append(train_df[feature] == value)
|
|
34
|
+
|
|
35
|
+
if condition_logic == "and":
|
|
36
|
+
combined_filter = row_filters[0]
|
|
37
|
+
for f in row_filters[1:]:
|
|
38
|
+
combined_filter &= f
|
|
39
|
+
elif condition_logic == "or":
|
|
40
|
+
combined_filter = row_filters[0]
|
|
41
|
+
for f in row_filters[1:]:
|
|
42
|
+
combined_filter |= f
|
|
43
|
+
elif condition_logic is None:
|
|
44
|
+
combined_filter = row_filters[0]
|
|
45
|
+
for f in row_filters[1:]:
|
|
46
|
+
combined_filter &= f
|
|
47
|
+
else:
|
|
48
|
+
raise ValueError("condition_logic must be either 'and', 'or', or None.")
|
|
49
|
+
|
|
50
|
+
filtered_df = noisy_df[combined_filter]
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
total_rows_to_change = int(len(filtered_df) * percentage)
|
|
54
|
+
|
|
55
|
+
if mode == "extended" and original_df is not None:
|
|
56
|
+
train_df = train1_df
|
|
57
|
+
already_modified_mask = (train_df[affected_features[0]] != original_df[affected_features[0]])
|
|
58
|
+
already_modified_count = already_modified_mask.sum()
|
|
59
|
+
rows_to_change = total_rows_to_change - already_modified_count
|
|
60
|
+
|
|
61
|
+
if rows_to_change > 0:
|
|
62
|
+
modifiable_indices = filtered_df[~already_modified_mask.reindex(filtered_df.index, fill_value=False)]
|
|
63
|
+
if len(modifiable_indices) == 0:
|
|
64
|
+
print("No modifiable rows available in extended mode.")
|
|
65
|
+
return noisy_df
|
|
66
|
+
number= rows_to_change
|
|
67
|
+
percentage=None
|
|
68
|
+
sampled_indices = sample_indices(distr1, modifiable_indices,percentage, number, params)
|
|
69
|
+
sampled_indices = modifiable_indices.iloc[sampled_indices].index
|
|
70
|
+
else:
|
|
71
|
+
print("No additional rows to change in extended mode.")
|
|
72
|
+
return noisy_df
|
|
73
|
+
|
|
74
|
+
else:
|
|
75
|
+
number= total_rows_to_change
|
|
76
|
+
percentage=None
|
|
77
|
+
sampled_indices = sample_indices(distr1, filtered_df,percentage, number, params)
|
|
78
|
+
sampled_indices = filtered_df.iloc[sampled_indices].index
|
|
79
|
+
|
|
80
|
+
if mode == "extended":
|
|
81
|
+
noisy_df = train1_df
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
for feature in affected_features:
|
|
85
|
+
if pd.api.types.is_string_dtype(noisy_df[feature]):
|
|
86
|
+
unique_values = train_df[feature].dropna().unique()
|
|
87
|
+
for idx in sampled_indices:
|
|
88
|
+
if selection_criteria == "fake_values":
|
|
89
|
+
|
|
90
|
+
noisy_df.loc[idx, feature] = ''.join(np.random.choice(list('abcdefghijklmnopqrstuvwxyz'), size=5))
|
|
91
|
+
|
|
92
|
+
else:
|
|
93
|
+
|
|
94
|
+
while True:
|
|
95
|
+
new_value = np.random.choice(unique_values)
|
|
96
|
+
if new_value != noisy_df.loc[idx, feature]:
|
|
97
|
+
noisy_df.loc[idx, feature] = new_value
|
|
98
|
+
break
|
|
99
|
+
|
|
100
|
+
elif pd.api.types.is_numeric_dtype(noisy_df[feature]):
|
|
101
|
+
min_val = train_df[feature].min()
|
|
102
|
+
max_val = train_df[feature].max()
|
|
103
|
+
for idx in sampled_indices:
|
|
104
|
+
if pd.api.types.is_integer_dtype(noisy_df[feature]):
|
|
105
|
+
new_value = random.randint(min_val, max_val)
|
|
106
|
+
else:
|
|
107
|
+
new_value = random.uniform(min_val, max_val)
|
|
108
|
+
noisy_df.loc[idx, feature] = new_value
|
|
109
|
+
|
|
110
|
+
elif pd.api.types.is_datetime64_any_dtype(noisy_df[feature]):
|
|
111
|
+
valid_dates = train_df[feature].dropna()
|
|
112
|
+
if valid_dates.empty:
|
|
113
|
+
continue
|
|
114
|
+
min_date = valid_dates.min()
|
|
115
|
+
max_date = valid_dates.max()
|
|
116
|
+
for idx in sampled_indices:
|
|
117
|
+
random_days = random.randint(0, (max_date - min_date).days)
|
|
118
|
+
noisy_df.loc[idx, feature] = min_date + timedelta(days=random_days)
|
|
119
|
+
|
|
120
|
+
elif pd.api.types.is_categorical_dtype(noisy_df[feature]):
|
|
121
|
+
|
|
122
|
+
unique_values = train_df[feature].cat.categories
|
|
123
|
+
for idx in sampled_indices:
|
|
124
|
+
new_value = random.choice(unique_values)
|
|
125
|
+
noisy_df.loc[idx, feature] = new_value
|
|
126
|
+
|
|
127
|
+
else:
|
|
128
|
+
raise ValueError(f"Unsupported column type for feature '{feature}'.")
|
|
129
|
+
|
|
130
|
+
return noisy_df
|
|
131
|
+
|
|
132
|
+
|
pucktrick/outliers.py
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
from pucktrick.utils import *
|
|
2
|
+
|
|
3
|
+
def is_int_categorical(series: pd.Series,
|
|
4
|
+
max_unique: int = 10,
|
|
5
|
+
max_domain_size: int = 20,
|
|
6
|
+
max_unique_ratio: float = 0.05,
|
|
7
|
+
require_nonnegative: bool = True) -> bool:
|
|
8
|
+
"""
|
|
9
|
+
Heuristic: decide if an integer-typed column is actually categorical (coded as ints).
|
|
10
|
+
"""
|
|
11
|
+
if not pd.api.types.is_integer_dtype(series):
|
|
12
|
+
return False
|
|
13
|
+
|
|
14
|
+
s = series.dropna()
|
|
15
|
+
if s.empty:
|
|
16
|
+
return False
|
|
17
|
+
|
|
18
|
+
nunq = s.nunique()
|
|
19
|
+
if nunq <= max_unique:
|
|
20
|
+
return True
|
|
21
|
+
|
|
22
|
+
if nunq <= max_domain_size and nunq / len(s) <= max_unique_ratio:
|
|
23
|
+
return True
|
|
24
|
+
|
|
25
|
+
vals = np.sort(s.unique())
|
|
26
|
+
if require_nonnegative and vals[0] < 0:
|
|
27
|
+
return False
|
|
28
|
+
|
|
29
|
+
# consecutive small domain?
|
|
30
|
+
if len(vals) <= max_domain_size and np.all(np.diff(vals) == 1):
|
|
31
|
+
return True
|
|
32
|
+
|
|
33
|
+
return False
|
|
34
|
+
|
|
35
|
+
def outlier(train_df, strategy, original_df=None):
|
|
36
|
+
|
|
37
|
+
if original_df is None:
|
|
38
|
+
original_df = train_df.copy()
|
|
39
|
+
|
|
40
|
+
affected_features = strategy.get("affected_features")
|
|
41
|
+
selection_criteria = strategy.get("selection_criteria")
|
|
42
|
+
percentage = strategy.get("percentage")
|
|
43
|
+
mode = strategy.get("mode")
|
|
44
|
+
perturbate_config = strategy.get("perturbate_data", {})
|
|
45
|
+
distr1 = perturbate_config.get("distribution")
|
|
46
|
+
values = perturbate_config.get("value", [])
|
|
47
|
+
condition_logic = perturbate_config.get("condition_logic", None)
|
|
48
|
+
params=perturbate_config.get("param", {})
|
|
49
|
+
train1_df=train_df.copy()
|
|
50
|
+
noisy_df = train_df.copy()
|
|
51
|
+
if mode == "extended":
|
|
52
|
+
train_df = original_df
|
|
53
|
+
|
|
54
|
+
if affected_features and not isinstance(affected_features, list):
|
|
55
|
+
affected_features = [affected_features]
|
|
56
|
+
if not values:
|
|
57
|
+
filtered_df = noisy_df
|
|
58
|
+
else:
|
|
59
|
+
row_filters = []
|
|
60
|
+
for feature, value in zip(affected_features, values):
|
|
61
|
+
if value is None:
|
|
62
|
+
row_filters.append(train_df[feature].notnull())
|
|
63
|
+
else:
|
|
64
|
+
row_filters.append(train_df[feature] == value)
|
|
65
|
+
|
|
66
|
+
if condition_logic == "and":
|
|
67
|
+
combined_filter = row_filters[0]
|
|
68
|
+
for f in row_filters[1:]:
|
|
69
|
+
combined_filter &= f
|
|
70
|
+
else:
|
|
71
|
+
combined_filter = row_filters[0]
|
|
72
|
+
for f in row_filters[1:]:
|
|
73
|
+
combined_filter |= f
|
|
74
|
+
|
|
75
|
+
filtered_df = noisy_df[combined_filter]
|
|
76
|
+
total_rows_to_change = int(len(filtered_df) * percentage)
|
|
77
|
+
|
|
78
|
+
if mode == "extended" and original_df is not None:
|
|
79
|
+
already_modified_mask = train1_df[affected_features].ne(original_df[affected_features]).any(axis=1)
|
|
80
|
+
already_modified_count = already_modified_mask.sum()
|
|
81
|
+
rows_to_change = total_rows_to_change - already_modified_count
|
|
82
|
+
modifiable_indices = filtered_df[~already_modified_mask.reindex(filtered_df.index, fill_value=False)]
|
|
83
|
+
if rows_to_change <= 0 or len(modifiable_indices) == 0:
|
|
84
|
+
print("⚠️ Modalità 'extended': nessuna nuova riga da sporcare. (Tutte le righe disponibili sono già modificate)")
|
|
85
|
+
return noisy_df
|
|
86
|
+
|
|
87
|
+
number=rows_to_change
|
|
88
|
+
percentage=None
|
|
89
|
+
sampled_indices = sample_indices(distr1, modifiable_indices,percentage, number, params)
|
|
90
|
+
sampled_indices = modifiable_indices.iloc[sampled_indices].index
|
|
91
|
+
else:
|
|
92
|
+
number=total_rows_to_change
|
|
93
|
+
percentage=None
|
|
94
|
+
sampled_indices = sample_indices(distr1, filtered_df,percentage, number, params)
|
|
95
|
+
sampled_indices = filtered_df.iloc[sampled_indices].index
|
|
96
|
+
|
|
97
|
+
for feature in affected_features:
|
|
98
|
+
if pd.api.types.is_string_dtype(noisy_df[feature]):
|
|
99
|
+
for i in sampled_indices:
|
|
100
|
+
noisy_df.loc[i, feature] = "puck was here"
|
|
101
|
+
|
|
102
|
+
elif pd.api.types.is_integer_dtype(noisy_df[feature]):
|
|
103
|
+
if is_int_categorical(noisy_df[feature]):
|
|
104
|
+
current_max = noisy_df[feature].max(skipna=True)
|
|
105
|
+
current_max=current_max+1
|
|
106
|
+
for i in sampled_indices:
|
|
107
|
+
noisy_df.loc[i, feature] = current_max
|
|
108
|
+
else:
|
|
109
|
+
mean = np.mean(noisy_df[feature])
|
|
110
|
+
std_dev = np.std(noisy_df[feature])
|
|
111
|
+
new_upper = round(mean + 4 * std_dev, 0)
|
|
112
|
+
new_lower = round(mean - 4 * std_dev, 0)
|
|
113
|
+
|
|
114
|
+
for i in sampled_indices:
|
|
115
|
+
if np.random.rand() > 0.5:
|
|
116
|
+
noisy_df.loc[i, feature] = random.randint(int(mean + 3 * std_dev), int(new_upper))
|
|
117
|
+
else:
|
|
118
|
+
noisy_df.loc[i, feature] = random.randint(int(new_lower), int(mean - 3 * std_dev))
|
|
119
|
+
|
|
120
|
+
elif pd.api.types.is_datetime64_any_dtype(noisy_df[feature]):
|
|
121
|
+
valid_dates = train_df[feature].dropna()
|
|
122
|
+
if valid_dates.empty:
|
|
123
|
+
continue
|
|
124
|
+
min_date = valid_dates.min()
|
|
125
|
+
max_date = valid_dates.max()
|
|
126
|
+
|
|
127
|
+
for i in sampled_indices:
|
|
128
|
+
random_days = random.randint(0, (max_date - min_date).days)
|
|
129
|
+
noisy_df.loc[i, feature] = min_date + timedelta(days=random_days)
|
|
130
|
+
|
|
131
|
+
elif pd.api.types.is_float_dtype(noisy_df[feature]):
|
|
132
|
+
mean = np.mean(noisy_df[feature])
|
|
133
|
+
std_dev = np.std(noisy_df[feature])
|
|
134
|
+
new_upper = mean + 4 * std_dev
|
|
135
|
+
new_lower = mean - 4 * std_dev
|
|
136
|
+
|
|
137
|
+
for i in sampled_indices:
|
|
138
|
+
if np.random.rand() > 0.5:
|
|
139
|
+
noisy_df.loc[i, feature] = np.random.uniform(mean + 3 * std_dev, new_upper)
|
|
140
|
+
else:
|
|
141
|
+
noisy_df.loc[i, feature] = np.random.uniform(new_lower, mean - 3 * std_dev)
|
|
142
|
+
|
|
143
|
+
else:
|
|
144
|
+
raise ValueError(f"Unsupported column type for feature '{feature}'.")
|
|
145
|
+
|
|
146
|
+
return noisy_df
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
|
pucktrick/utils.py
ADDED
|
@@ -0,0 +1,421 @@
|
|
|
1
|
+
import unittest
|
|
2
|
+
from pucktrick.utils import *
|
|
3
|
+
import pandas as pd
|
|
4
|
+
import numpy as np
|
|
5
|
+
from pandas.testing import assert_frame_equal
|
|
6
|
+
import random
|
|
7
|
+
import json
|
|
8
|
+
from datetime import timedelta
|
|
9
|
+
from dateutil import parser
|
|
10
|
+
import string
|
|
11
|
+
|
|
12
|
+
def create_fake_table(num_rows=1000):
|
|
13
|
+
# Generate data for each column
|
|
14
|
+
f1 = np.random.uniform(-100, 100, num_rows) # Continuous values between -100 and 100
|
|
15
|
+
f2 = np.random.randint(-100, 101, num_rows) # Discrete values between -100 and 100
|
|
16
|
+
f3 = np.random.choice(['apple', 'banana', 'cherry'], num_rows) # String values
|
|
17
|
+
f4 = np.random.choice(['apple', 'banana', 'cherry'], num_rows) # String values
|
|
18
|
+
f5 = np.random.choice([0, 1,2,3,4,5], num_rows) # Binary values (0 or 1)
|
|
19
|
+
delta_days = (pd.to_datetime('2030-12-31') - pd.to_datetime('1970-01-01')).days
|
|
20
|
+
random_days = np.random.randint(0, delta_days, num_rows)
|
|
21
|
+
random_dates = pd.to_datetime('1970-01-01') + pd.to_timedelta(random_days, unit='D')
|
|
22
|
+
date = random_dates # Restituisce direttamente una Series di tipo datetime.date
|
|
23
|
+
# date between 1970-01-01 and 2030-12-31
|
|
24
|
+
target = np.random.choice([0, 1], num_rows) # Binary target (0 or 1)
|
|
25
|
+
|
|
26
|
+
# Create the DataFrame
|
|
27
|
+
df = pd.DataFrame({
|
|
28
|
+
'f1': f1,
|
|
29
|
+
'f2': f2,
|
|
30
|
+
'f3': f3,
|
|
31
|
+
'f4': f4,
|
|
32
|
+
'f5': f5,
|
|
33
|
+
'date' : date,
|
|
34
|
+
'target': target
|
|
35
|
+
})
|
|
36
|
+
df['date'] = pd.to_datetime(df['date'])
|
|
37
|
+
return df
|
|
38
|
+
|
|
39
|
+
def generateSubdf(original_df, train_df,column,percentage ):
|
|
40
|
+
rowsToChange=len(original_df[column])*percentage
|
|
41
|
+
dif = original_df[column] != train_df[column]
|
|
42
|
+
diff_number = dif.sum()
|
|
43
|
+
new_rowsToChange=rowsToChange-diff_number
|
|
44
|
+
if new_rowsToChange<=0:
|
|
45
|
+
newPercentage=0
|
|
46
|
+
return train_df,newPercentage
|
|
47
|
+
noise_df= train_df.copy()
|
|
48
|
+
noise_df['id1'] = range(len(noise_df))
|
|
49
|
+
or_df=original_df.copy()
|
|
50
|
+
or_df['id1'] = range(len(or_df))
|
|
51
|
+
mask = or_df[column] == noise_df[column]
|
|
52
|
+
new_df = noise_df[mask]
|
|
53
|
+
new_df = new_df.reset_index(drop=True)
|
|
54
|
+
newPercentage=new_rowsToChange/len(new_df)
|
|
55
|
+
return new_df,newPercentage
|
|
56
|
+
|
|
57
|
+
def mergeDataframe(noise_df,modified_df):
|
|
58
|
+
merged_df = noise_df.merge(modified_df, on='id1', how='left', suffixes=('_df1', '_df2'))
|
|
59
|
+
new_array = [string for string in noise_df.columns if string != 'id1']
|
|
60
|
+
for col in new_array:
|
|
61
|
+
noise_df[col] = merged_df[col + '_df2'].fillna(merged_df[col + '_df1'])
|
|
62
|
+
noise_df = noise_df.drop('id1', axis=1)
|
|
63
|
+
return noise_df
|
|
64
|
+
|
|
65
|
+
def generate_random_value(lower, upper):
|
|
66
|
+
return np.random.uniform(lower, upper)
|
|
67
|
+
|
|
68
|
+
def generate_random_value_discrete(lower, upper):
|
|
69
|
+
return np.random.randint(lower, upper)
|
|
70
|
+
|
|
71
|
+
def sampleList(percentage, data_length):
|
|
72
|
+
num_samples = int(percentage * data_length)
|
|
73
|
+
return np.random.choice(data_length, size=num_samples, replace=False)
|
|
74
|
+
|
|
75
|
+
def sample_indices(distribution, data_length, percentage=None, number=None, params=None):
|
|
76
|
+
if percentage is None:
|
|
77
|
+
num_samples = number
|
|
78
|
+
elif number is None:
|
|
79
|
+
num_samples = int(len(data_length) * percentage) # use data_length directly
|
|
80
|
+
params = params or {}
|
|
81
|
+
#print(percentage)
|
|
82
|
+
|
|
83
|
+
if distribution == "random":
|
|
84
|
+
# Change: use len(data_length) to get the size for random sampling
|
|
85
|
+
return np.random.choice(len(data_length), num_samples, replace=False)
|
|
86
|
+
|
|
87
|
+
elif distribution == "uniform":
|
|
88
|
+
min_val = params.get("min", 0)
|
|
89
|
+
max_val = params.get("max", len(data_length) - 1) # data_length
|
|
90
|
+
return np.random.uniform(min_val, max_val, num_samples).astype(int)
|
|
91
|
+
|
|
92
|
+
elif distribution == "normal":
|
|
93
|
+
mu = params.get("mu", len(data_length) / 2) # data_length
|
|
94
|
+
sigma = params.get("sigma", len(data_length) / 6) # data_length
|
|
95
|
+
samples = np.random.normal(mu, sigma, num_samples)
|
|
96
|
+
samples = np.clip(samples, 0, len(data_length) - 1) # data_length
|
|
97
|
+
return samples.astype(int)
|
|
98
|
+
|
|
99
|
+
elif distribution == "exponential":
|
|
100
|
+
lambd = params.get("lambda", 1.0)
|
|
101
|
+
samples = np.random.exponential(1 / lambd, num_samples)
|
|
102
|
+
samples = (samples / np.max(samples)) * (len(data_length) - 1) # data_length
|
|
103
|
+
return samples.astype(int)
|
|
104
|
+
|
|
105
|
+
else:
|
|
106
|
+
raise ValueError(f"Distribuzione '{distribution}' non supportata.")
|
|
107
|
+
|
|
108
|
+
def noiseBinaryNew(train_df, target, distribution, percentage , number, params):
|
|
109
|
+
noise_df = train_df.copy()
|
|
110
|
+
#indices_to_modify = sampleList(percentage, len(train_df[target]))
|
|
111
|
+
indices_to_modify= sample_indices(distribution, train_df, percentage, number, params)
|
|
112
|
+
#print(indices_to_modify)
|
|
113
|
+
for i in indices_to_modify:
|
|
114
|
+
noise_df.at[i, target] = 1 - noise_df.at[i, target]
|
|
115
|
+
return noise_df
|
|
116
|
+
|
|
117
|
+
def noiseBinaryExt(original_df, train_df, target, distribution,percentage,number,params):
|
|
118
|
+
noise_df = train_df.copy()
|
|
119
|
+
noise_df['id1'] = range(len(noise_df))
|
|
120
|
+
new_df, newPercentage = generateSubdf(original_df, noise_df, target, percentage)
|
|
121
|
+
if newPercentage == 0:
|
|
122
|
+
return train_df
|
|
123
|
+
modified_df = noiseBinaryNew(new_df, target, distribution, newPercentage,number, params)
|
|
124
|
+
noise_df = mergeDataframe(noise_df, modified_df)
|
|
125
|
+
return noise_df
|
|
126
|
+
|
|
127
|
+
def noiseCategoricalStringNewExistingValues(train_df, column, distribution, percentage , number, params):
|
|
128
|
+
#extracted_indices = sampleList(percentage, len(train_df[column]))
|
|
129
|
+
extracted_indices = sample_indices(distribution, train_df[column], percentage=None, number=None, params=None)
|
|
130
|
+
noise_df = train_df.copy()
|
|
131
|
+
unique_values = noise_df[column].unique()
|
|
132
|
+
|
|
133
|
+
for i in extracted_indices:
|
|
134
|
+
while True:
|
|
135
|
+
new_value = np.random.choice(unique_values)
|
|
136
|
+
if new_value != noise_df.loc[i, column]:
|
|
137
|
+
noise_df.loc[i, column] = new_value
|
|
138
|
+
break
|
|
139
|
+
return noise_df
|
|
140
|
+
|
|
141
|
+
def noiseCategoricalIntNewExistingValues(train_df, target, distribution, percentage , number, params):
|
|
142
|
+
noise_df = train_df.copy()
|
|
143
|
+
#indices_to_modify = sampleList(percentage, len(train_df[target]))
|
|
144
|
+
indices_to_modify= sample_indices(distribution, train_df[target], percentage=None, number=None, params=None)
|
|
145
|
+
unique_values = train_df[target].unique()
|
|
146
|
+
for i in indices_to_modify:
|
|
147
|
+
current_value = noise_df.at[i, target]
|
|
148
|
+
new_value = np.random.choice([v for v in unique_values if v != current_value])
|
|
149
|
+
noise_df.at[i, target] = new_value
|
|
150
|
+
return noise_df
|
|
151
|
+
|
|
152
|
+
def noiseCategoricalIntExtendedExistingValues(original_df, train_df, target, distribution,percentage,number,params):
|
|
153
|
+
noise_df = train_df.copy()
|
|
154
|
+
noise_df['id1'] = range(len(noise_df)) # Aggiunta della colonna 'id1'
|
|
155
|
+
new_df, newPercentage = generateSubdf(original_df, noise_df, target, percentage)
|
|
156
|
+
if newPercentage == 0:
|
|
157
|
+
return train_df
|
|
158
|
+
modified_df = noiseCategoricalIntNewExistingValues(new_df, target, distribution, newPercentage,number, params)
|
|
159
|
+
noise_df = mergeDataframe(noise_df, modified_df)
|
|
160
|
+
return noise_df
|
|
161
|
+
|
|
162
|
+
def noiseCategoricalStringNewFakeValues(train_df, column, distribution,percentage,number,params):
|
|
163
|
+
#extracted_list = sampleList(percentage, len(train_df))
|
|
164
|
+
extracted_list= sample_indices(distribution, train_df, percentage=None, number=None, params=None) # Cambia qui per selezionare casualmente
|
|
165
|
+
noise_df = train_df.copy()
|
|
166
|
+
for i in extracted_list: # Usa extracted_list per modificare solo i campioni
|
|
167
|
+
noise_df.loc[i, column] = ''.join(np.random.choice(list('abcdefghijklmnopqrstuvwxyz'), size=5))
|
|
168
|
+
return noise_df
|
|
169
|
+
|
|
170
|
+
def noiseCategoricalStringExtendedFakeValues(original_df, train_df, column, distribution,percentage,number,params):
|
|
171
|
+
noise_df = train_df.copy()
|
|
172
|
+
noise_df['id1'] = range(len(noise_df))
|
|
173
|
+
new_df, newPercentage = generateSubdf(original_df, noise_df, column, percentage)
|
|
174
|
+
if newPercentage == 0:
|
|
175
|
+
return train_df
|
|
176
|
+
|
|
177
|
+
modified_df = noiseCategoricalStringNewFakeValues(new_df, column, distribution,newPercentage,number,params)
|
|
178
|
+
noise_df = mergeDataframe(noise_df, modified_df)
|
|
179
|
+
|
|
180
|
+
# Rimuovi la colonna 'id1' temporanea se esiste
|
|
181
|
+
if 'id1' in noise_df.columns:
|
|
182
|
+
noise_df = noise_df.drop('id1', axis=1)
|
|
183
|
+
|
|
184
|
+
return noise_df
|
|
185
|
+
|
|
186
|
+
# Funzione per aggiungere rumore discreto (normal)
|
|
187
|
+
def noiseDiscreteNew(train_df, column, distribution,percentage,number,params):
|
|
188
|
+
#extracted_indices = sampleList(percentage, len(train_df[column]))
|
|
189
|
+
extracted_indices= sample_indices(distribution, train_df[column], percentage=None, number=None, params=None)
|
|
190
|
+
noise_df = train_df.copy()
|
|
191
|
+
min_value = noise_df[column].min()
|
|
192
|
+
max_value = noise_df[column].max()
|
|
193
|
+
|
|
194
|
+
for i in extracted_indices:
|
|
195
|
+
while True:
|
|
196
|
+
new_value = random.randint(min_value, max_value)
|
|
197
|
+
if new_value != noise_df.loc[i, column]:
|
|
198
|
+
noise_df.loc[i, column] = new_value
|
|
199
|
+
break
|
|
200
|
+
return noise_df
|
|
201
|
+
|
|
202
|
+
# Funzione per aggiungere rumore continuo (normal)
|
|
203
|
+
def noiseContinueNew(train_df, column, distribution,percentage,number,params):
|
|
204
|
+
#extracted_indices = sampleList(percentage, len(train_df[column]))
|
|
205
|
+
extracted_indices= sample_indices(distribution, train_df[column], percentage=None, number=None, params=None)
|
|
206
|
+
noise_df = train_df.copy()
|
|
207
|
+
min_value = noise_df[column].min()
|
|
208
|
+
max_value = noise_df[column].max()
|
|
209
|
+
|
|
210
|
+
for i in extracted_indices:
|
|
211
|
+
while True:
|
|
212
|
+
new_value = random.uniform(min_value, max_value)
|
|
213
|
+
if new_value != noise_df.loc[i, column]:
|
|
214
|
+
noise_df.loc[i, column] = new_value
|
|
215
|
+
break
|
|
216
|
+
return noise_df
|
|
217
|
+
|
|
218
|
+
def outlierContinuosNew3Sigma(train_df, column, distribution,percentage,number,params):
|
|
219
|
+
#extracted_list = sampleList(percentage, len(train_df[column]))
|
|
220
|
+
extracted_list= sample_indices(distribution, train_df[column], percentage=None, number=None, params=None)
|
|
221
|
+
noise_df = train_df.copy()
|
|
222
|
+
mean = np.mean(noise_df[column])
|
|
223
|
+
std_dev = np.std(noise_df[column])
|
|
224
|
+
upper_bound = mean + 3 * std_dev
|
|
225
|
+
lower_bound = mean - 3 * std_dev
|
|
226
|
+
new_lower_limit = mean - 4 * std_dev
|
|
227
|
+
new_upper_limit = mean + 4 * std_dev
|
|
228
|
+
|
|
229
|
+
for i in extracted_list:
|
|
230
|
+
if np.random.rand() > 0.5:
|
|
231
|
+
noise_df.loc[i, column] = generate_random_value(upper_bound, new_upper_limit)
|
|
232
|
+
else:
|
|
233
|
+
noise_df.loc[i, column] = generate_random_value(new_lower_limit, lower_bound)
|
|
234
|
+
|
|
235
|
+
return noise_df
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def outlierDiscreteNew3Sigma(train_df,column,distribution,percentage,number,params):
|
|
239
|
+
#extracted_list=sampleList(percentage,len(train_df[column]))
|
|
240
|
+
extracted_list= sample_indices(distribution, train_df[column], percentage=None, number=None, params=None)
|
|
241
|
+
noise_df= train_df.copy()
|
|
242
|
+
mean = np.mean(noise_df[column])
|
|
243
|
+
std_dev = np.std(noise_df[column])
|
|
244
|
+
upper_bound=round(mean + 3 * std_dev,0)
|
|
245
|
+
lower_bound=round(mean -3 * std_dev,0)
|
|
246
|
+
new_upper_limit = round(mean + 4 * std_dev,0)
|
|
247
|
+
new_lower_limit = round(mean - 4 * std_dev,0)
|
|
248
|
+
if upper_bound==0:
|
|
249
|
+
upper_bound=1
|
|
250
|
+
if new_upper_limit==upper_bound:
|
|
251
|
+
new_upper_limit=5*upper_bound
|
|
252
|
+
|
|
253
|
+
if lower_bound==0:
|
|
254
|
+
lower_bound=-1
|
|
255
|
+
if new_lower_limit==lower_bound and lower_bound<0:
|
|
256
|
+
new_lower_limit=5*lower_bound
|
|
257
|
+
elif lower_bound>0:
|
|
258
|
+
new_lower_limit=-5*lower_bound
|
|
259
|
+
if upper_bound>new_upper_limit:
|
|
260
|
+
tmp=new_upper_limit
|
|
261
|
+
new_upper_limit=upper_bound
|
|
262
|
+
upper_bound=tmp
|
|
263
|
+
if new_lower_limit>lower_bound:
|
|
264
|
+
tmp=lower_bound
|
|
265
|
+
lower_bound=new_lower_limit
|
|
266
|
+
new_lower_limit=tmp
|
|
267
|
+
for i in extracted_list:
|
|
268
|
+
if np.random.rand() > 0.5:
|
|
269
|
+
noise_df.loc[i, column] = generate_random_value_discrete(upper_bound, new_upper_limit)
|
|
270
|
+
else:
|
|
271
|
+
noise_df.loc[i, column] = generate_random_value_discrete(new_lower_limit, lower_bound)
|
|
272
|
+
|
|
273
|
+
return noise_df
|
|
274
|
+
|
|
275
|
+
def outlierCategoricalIntegerNew(train_df,column,distribution,percentage,number,params):
|
|
276
|
+
#extracted_list=sampleList(percentage,len(train_df[column]))
|
|
277
|
+
extracted_list= sample_indices(distribution, train_df[column], percentage=None, number=None, params=None)
|
|
278
|
+
noise_df= train_df.copy()
|
|
279
|
+
max_value = noise_df[column].max()
|
|
280
|
+
min_value=noise_df[column].min()
|
|
281
|
+
if min_value==0:
|
|
282
|
+
min_value=-1
|
|
283
|
+
new_minValue=-5
|
|
284
|
+
elif min_value<0:
|
|
285
|
+
new_minValue=5*min_value
|
|
286
|
+
else:
|
|
287
|
+
new_minValue=-5+min_value
|
|
288
|
+
if max_value==0:
|
|
289
|
+
max_value=1
|
|
290
|
+
new_maxValue=5
|
|
291
|
+
else:
|
|
292
|
+
new_maxValue=2*max_value
|
|
293
|
+
for i, value in enumerate(extracted_list):
|
|
294
|
+
if np.random.rand() > 0.5:
|
|
295
|
+
noise_df.loc[i, column] = np.random.randint(max_value, new_maxValue)
|
|
296
|
+
else:
|
|
297
|
+
noise_df.loc[i, column] = np.random.randint(new_minValue, min_value)
|
|
298
|
+
|
|
299
|
+
return noise_df
|
|
300
|
+
|
|
301
|
+
def outlierCategoricalStringNew(train_df,column,distribution,percentage,number,params):
|
|
302
|
+
#extracted_list=sampleList(percentage,len(train_df[column]))
|
|
303
|
+
extracted_list= sample_indices(distribution, train_df[column], percentage=None, number=None, params=None)
|
|
304
|
+
noise_df= train_df.copy()
|
|
305
|
+
for i, value in enumerate(extracted_list):
|
|
306
|
+
noise_df.loc[i, column] = "puck was here"
|
|
307
|
+
return noise_df
|
|
308
|
+
|
|
309
|
+
# Funzione per identificare le date valide
|
|
310
|
+
def identify_valid_dates(df, date_column):
|
|
311
|
+
valid_dates = []
|
|
312
|
+
for date in df[date_column]:
|
|
313
|
+
try:
|
|
314
|
+
# Converte la data in stringa se necessario, prima di passarla a parser.parse
|
|
315
|
+
if isinstance(date, (pd.Timestamp, date)):
|
|
316
|
+
date = str(date) # Converte in stringa
|
|
317
|
+
parser.parse(date)
|
|
318
|
+
valid_dates.append(True)
|
|
319
|
+
except (ValueError, TypeError):
|
|
320
|
+
valid_dates.append(False)
|
|
321
|
+
|
|
322
|
+
df['is_valid_date'] = valid_dates
|
|
323
|
+
return df
|
|
324
|
+
|
|
325
|
+
# Funzione per standardizzare solo le date riconosciute in un formato coerente
|
|
326
|
+
def standardize_dates(df, date_column):
|
|
327
|
+
standardized_dates = []
|
|
328
|
+
|
|
329
|
+
for date, is_valid in zip(df[date_column], df['is_valid_date']):
|
|
330
|
+
if is_valid:
|
|
331
|
+
try:
|
|
332
|
+
# Converte la data con `dayfirst=True` e formatta come 'YYYY-MM-DD'
|
|
333
|
+
standardized_date = parser.parse(date, dayfirst=True).date() # Mantiene solo la parte della data
|
|
334
|
+
standardized_dates.append(standardized_date)
|
|
335
|
+
except (ValueError, TypeError):
|
|
336
|
+
standardized_dates.append(date) # Mantieni la data originale se c'è un errore
|
|
337
|
+
else:
|
|
338
|
+
standardized_dates.append(date) # Mantieni la stringa originale per date non valide
|
|
339
|
+
|
|
340
|
+
df[date_column] = standardized_dates
|
|
341
|
+
return df
|
|
342
|
+
|
|
343
|
+
# Funzione per generare una data outlier basata su deviazione standard con un limite massimo
|
|
344
|
+
def random_outlier_date(mean_date, std_dev_days, min_date, max_date, factor=3, max_offset_days=36500):
|
|
345
|
+
# Aumenta la variabilità generando un offset più casuale per ciascun outlier
|
|
346
|
+
days_offset = random.choice([-1, 1]) * random.randint(factor, factor * 5) * random.uniform(0.5, 3) * std_dev_days
|
|
347
|
+
|
|
348
|
+
# Limita il valore dell'offset per evitare l'errore OutOfBoundsTimedelta
|
|
349
|
+
if abs(days_offset) > max_offset_days:
|
|
350
|
+
days_offset = random.choice([-1, 1]) * random.randint(0, max_offset_days) # Limita l'offset massimo
|
|
351
|
+
|
|
352
|
+
# Calcola la nuova data outlier
|
|
353
|
+
outlier_date = (mean_date + timedelta(days=days_offset)).date()
|
|
354
|
+
|
|
355
|
+
return outlier_date
|
|
356
|
+
|
|
357
|
+
def random_upper_lower(series):
|
|
358
|
+
"""Apply random upper/lower casing to each string in the Series."""
|
|
359
|
+
return series.apply(lambda text: ''.join(
|
|
360
|
+
[char.upper() if random.random() > 0.5 else char.lower() for char in text]
|
|
361
|
+
))
|
|
362
|
+
|
|
363
|
+
def replace_punctuation(text):
|
|
364
|
+
"""Sostituisce ogni segno di punteggiatura (/, ., -) con uno degli altri due in maniera casuale, mantenendo lo stesso sostituto all'interno della stessa stringa."""
|
|
365
|
+
replacements = {
|
|
366
|
+
'/': random.choice(['-', '.']),
|
|
367
|
+
'.': random.choice([',', '/']),
|
|
368
|
+
'-': random.choice(['/', '.'])}
|
|
369
|
+
return ''.join([replacements[char] if char in replacements else char for char in text])
|
|
370
|
+
|
|
371
|
+
def remove_or_replace(text):
|
|
372
|
+
"""Rimuove o sostituisce un carattere casuale, sostituendo lettere con lettere e numeri con numeri."""
|
|
373
|
+
if len(text) < 2:
|
|
374
|
+
return text
|
|
375
|
+
pos = random.randint(0, len(text) - 1)
|
|
376
|
+
char = text[pos]
|
|
377
|
+
|
|
378
|
+
if char.isdigit():
|
|
379
|
+
if random.random() > 0.5:
|
|
380
|
+
return text[:pos] + text[pos + 1:]
|
|
381
|
+
else:
|
|
382
|
+
random_digit = str(random.randint(0, 9))
|
|
383
|
+
return text[:pos] + random_digit + text[pos + 1:]
|
|
384
|
+
elif char.isalpha():
|
|
385
|
+
if random.random() > 0.5:
|
|
386
|
+
return text[:pos] + text[pos + 1:]
|
|
387
|
+
else:
|
|
388
|
+
random_letter = random.choice(string.ascii_letters)
|
|
389
|
+
return text[:pos] + random_letter + text[pos + 1:]
|
|
390
|
+
return text
|
|
391
|
+
|
|
392
|
+
def abbreviate_text(text):
|
|
393
|
+
"""Abbrevia il testo mantenendo solo le prime lettere di ogni parola."""
|
|
394
|
+
return ''.join([word[0] for word in text.split()])
|
|
395
|
+
|
|
396
|
+
def shuffle_words(text):
|
|
397
|
+
"""Cambia l'ordine delle parole in una stringa, garantendo un ordine diverso dall'originale."""
|
|
398
|
+
words = text.split()
|
|
399
|
+
while True:
|
|
400
|
+
random.shuffle(words)
|
|
401
|
+
if words != text.split():
|
|
402
|
+
break
|
|
403
|
+
return ' '.join(words)
|
|
404
|
+
|
|
405
|
+
# Funzione per creare JSON
|
|
406
|
+
def create_json_for_feature(percentage, mode, feature_name=None, selection_criteria="all"):
|
|
407
|
+
config = {
|
|
408
|
+
"strategy": {
|
|
409
|
+
"affected_features": [feature_name] if feature_name else [],
|
|
410
|
+
"selection_criteria": selection_criteria,
|
|
411
|
+
"percentage": percentage,
|
|
412
|
+
"mode": mode,
|
|
413
|
+
"perturbate_data": {
|
|
414
|
+
"distribution": "random",
|
|
415
|
+
"param": None,
|
|
416
|
+
"value": None,
|
|
417
|
+
"condition_logic": None
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
return config
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
pucktrick/__init__.py,sha256=pVYhOkVS5PHJd_cIEx6PTaY6VggXFTC3pqWdf0I8zao,21
|
|
2
|
+
pucktrick/duplicated.py,sha256=fHp5zUZ-66Pv7j3HhVuiUTObA66YQCZvs-1R4S_EIFk,5392
|
|
3
|
+
pucktrick/labels.py,sha256=TmrSZAgy-EKFPog92nmFYUjadeyf2OuPVR8s4i__uCA,1786
|
|
4
|
+
pucktrick/missing.py,sha256=pMZJ1dxzchOFzeEnX9Suyjkth9iiwNat9x2XFocHBrU,4932
|
|
5
|
+
pucktrick/noisy.py,sha256=OdAQRE8x99j11RL8CegGLBKT-9IR5MIOhcXJ2kc2_XM,5209
|
|
6
|
+
pucktrick/outliers.py,sha256=sv7yK5BEq60aH9nm_3LDBHX50B27VBTmoPJJKc3ZJT0,5808
|
|
7
|
+
pucktrick/utils.py,sha256=LhhBfXCP4XW5QxNEfWP_NH_27Dl-87h_GyPylEWwxeo,17367
|
|
8
|
+
pucktrick-0.0.0.dist-info/licenses/LICENCE,sha256=McWU_K39dJBZBJlNoiN97R4cIn3OqiY8KgHRlDbxJdc,13294
|
|
9
|
+
pucktrick-0.0.0.dist-info/METADATA,sha256=c560__Y4CaUd-7xXVNuc5QihgEwBz7DR1dJE6EAYbj4,97
|
|
10
|
+
pucktrick-0.0.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
|
|
11
|
+
pucktrick-0.0.0.dist-info/top_level.txt,sha256=rxJAW8Pa6CPGlt95g4yCYw0ui0IQV-KbfRuqOiaEups,10
|
|
12
|
+
pucktrick-0.0.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
Attribution-NonCommercial 4.0 International
|
|
2
|
+
By exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution-NonCommercial 4.0 International Public License ("Public License"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions.
|
|
3
|
+
|
|
4
|
+
Section 1 – Definitions.
|
|
5
|
+
Adapted Material means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image.
|
|
6
|
+
Adapter's License means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License.
|
|
7
|
+
Copyright and Similar Rights means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights.
|
|
8
|
+
Effective Technological Measures means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements.
|
|
9
|
+
Exceptions and Limitations means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material.
|
|
10
|
+
Licensed Material means the artistic or literary work, database, or other material to which the Licensor applied this Public License.
|
|
11
|
+
Licensed Rights means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license.
|
|
12
|
+
Licensor means the individual(s) or entity(ies) granting rights under this Public License.
|
|
13
|
+
NonCommercial means not primarily intended for or directed towards commercial advantage or monetary compensation. For purposes of this Public License, the exchange of the Licensed Material for other material subject to Copyright and Similar Rights by digital file-sharing or similar means is NonCommercial provided there is no payment of monetary compensation in connection with the exchange.
|
|
14
|
+
Share means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them.
|
|
15
|
+
Sui Generis Database Rights means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world.
|
|
16
|
+
You means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning.
|
|
17
|
+
Section 2 – Scope.
|
|
18
|
+
License grant .
|
|
19
|
+
Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to:
|
|
20
|
+
reproduce and Share the Licensed Material, in whole or in part, for NonCommercial purposes only; and
|
|
21
|
+
produce, reproduce, and Share Adapted Material for NonCommercial purposes only.
|
|
22
|
+
Exceptions and Limitations . For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions.
|
|
23
|
+
Term . The term of this Public License is specified in Section 6(a) .
|
|
24
|
+
Media and formats; technical modifications allowed . The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a)(4) never produces Adapted Material.
|
|
25
|
+
Downstream recipients .
|
|
26
|
+
Offer from the Licensor – Licensed Material . Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License.
|
|
27
|
+
No downstream restrictions . You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material.
|
|
28
|
+
No endorsement . Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i) .
|
|
29
|
+
Other rights .
|
|
30
|
+
Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise.
|
|
31
|
+
Patent and trademark rights are not licensed under this Public License.
|
|
32
|
+
To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties, including when the Licensed Material is used other than for NonCommercial purposes.
|
|
33
|
+
Section 3 – License Conditions.
|
|
34
|
+
Your exercise of the Licensed Rights is expressly made subject to the following conditions.
|
|
35
|
+
|
|
36
|
+
Attribution .
|
|
37
|
+
If You Share the Licensed Material (including in modified form), You must:
|
|
38
|
+
|
|
39
|
+
retain the following if it is supplied by the Licensor with the Licensed Material:
|
|
40
|
+
identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated);
|
|
41
|
+
a copyright notice;
|
|
42
|
+
a notice that refers to this Public License;
|
|
43
|
+
a notice that refers to the disclaimer of warranties;
|
|
44
|
+
a URI or hyperlink to the Licensed Material to the extent reasonably practicable;
|
|
45
|
+
indicate if You modified the Licensed Material and retain an indication of any previous modifications; and
|
|
46
|
+
indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License.
|
|
47
|
+
You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information.
|
|
48
|
+
If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable.
|
|
49
|
+
If You Share Adapted Material You produce, the Adapter's License You apply must not prevent recipients of the Adapted Material from complying with this Public License.
|
|
50
|
+
Section 4 – Sui Generis Database Rights.
|
|
51
|
+
Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material:
|
|
52
|
+
|
|
53
|
+
for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database for NonCommercial purposes only;
|
|
54
|
+
if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material; and
|
|
55
|
+
You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database.
|
|
56
|
+
For the avoidance of doubt, this Section 4 supplements and does not replace Your obligations under this Public License where the Licensed Rights include other Copyright and Similar Rights.
|
|
57
|
+
|
|
58
|
+
Section 5 – Disclaimer of Warranties and Limitation of Liability.
|
|
59
|
+
Unless otherwise separately undertaken by the Licensor, to the extent possible, the Licensor offers the Licensed Material as-is and as-available, and makes no representations or warranties of any kind concerning the Licensed Material, whether express, implied, statutory, or other. This includes, without limitation, warranties of title, merchantability, fitness for a particular purpose, non-infringement, absence of latent or other defects, accuracy, or the presence or absence of errors, whether or not known or discoverable. Where disclaimers of warranties are not allowed in full or in part, this disclaimer may not apply to You.
|
|
60
|
+
To the extent possible, in no event will the Licensor be liable to You on any legal theory (including, without limitation, negligence) or otherwise for any direct, special, indirect, incidental, consequential, punitive, exemplary, or other losses, costs, expenses, or damages arising out of this Public License or use of the Licensed Material, even if the Licensor has been advised of the possibility of such losses, costs, expenses, or damages. Where a limitation of liability is not allowed in full or in part, this limitation may not apply to You.
|
|
61
|
+
The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability.
|
|
62
|
+
Section 6 – Term and Termination.
|
|
63
|
+
This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically.
|
|
64
|
+
Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates:
|
|
65
|
+
|
|
66
|
+
automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or
|
|
67
|
+
upon express reinstatement by the Licensor.
|
|
68
|
+
For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License.
|
|
69
|
+
|
|
70
|
+
For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License.
|
|
71
|
+
Sections 1 , 5 , 6 , 7 , and 8 survive termination of this Public License.
|
|
72
|
+
Section 7 – Other Terms and Conditions.
|
|
73
|
+
The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed.
|
|
74
|
+
Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License.
|
|
75
|
+
Section 8 – Interpretation.
|
|
76
|
+
For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License.
|
|
77
|
+
To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions.
|
|
78
|
+
No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor.
|
|
79
|
+
Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
pucktrick
|