pucktrick 0.0.0__tar.gz
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-0.0.0/LICENCE +79 -0
- pucktrick-0.0.0/MANIFEST.in +3 -0
- pucktrick-0.0.0/PKG-INFO +5 -0
- pucktrick-0.0.0/README.md +53 -0
- pucktrick-0.0.0/pyproject.toml +0 -0
- pucktrick-0.0.0/setup.cfg +4 -0
- pucktrick-0.0.0/src/pucktrick/__init__.py +1 -0
- pucktrick-0.0.0/src/pucktrick/duplicated.py +123 -0
- pucktrick-0.0.0/src/pucktrick/labels.py +44 -0
- pucktrick-0.0.0/src/pucktrick/missing.py +129 -0
- pucktrick-0.0.0/src/pucktrick/noisy.py +132 -0
- pucktrick-0.0.0/src/pucktrick/outliers.py +151 -0
- pucktrick-0.0.0/src/pucktrick/utils.py +421 -0
- pucktrick-0.0.0/src/pucktrick.egg-info/PKG-INFO +5 -0
- pucktrick-0.0.0/src/pucktrick.egg-info/SOURCES.txt +19 -0
- pucktrick-0.0.0/src/pucktrick.egg-info/dependency_links.txt +1 -0
- pucktrick-0.0.0/src/pucktrick.egg-info/top_level.txt +1 -0
- pucktrick-0.0.0/tests/test_duplicated.py +44 -0
- pucktrick-0.0.0/tests/test_missing.py +31 -0
- pucktrick-0.0.0/tests/test_noise.py +29 -0
- pucktrick-0.0.0/tests/test_outliers.py +31 -0
pucktrick-0.0.0/LICENCE
ADDED
|
@@ -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.
|
pucktrick-0.0.0/PKG-INFO
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
# pucktrick
|
|
2
|
+
|
|
3
|
+
Pucktrick is a Python library that provides various utility functions to introduce errors in your dataframe.
|
|
4
|
+
The name of library is based on Puck. Puck is the name of the elf in the “A midsummer Night’s dream” of William Shakespeare that is very famous to enjoys causing trouble and playing tricks on mortals and other fairies alike.
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
## Features
|
|
8
|
+
Pucktrick is organized in modules, one for error type. Each module inludes a function called with the name of module. Every function receives as parameters the dataset to modify, the strategy, and the original dataset, if mode="extended". Functions return two parameters an error (possibile 0 or 1) and the generated dataset.
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
## Version
|
|
13
|
+
version 0.5
|
|
14
|
+
- add strategy, a json file where it is possibile to create a error model by specifing the affected features (from one to many), a selection criteria, a bolean predicate that specify a subset of the rows to be corrupted, the mode, the percentage, the distribution function for injection errors.
|
|
15
|
+
|
|
16
|
+
version 0.4
|
|
17
|
+
- errortype added: missing values
|
|
18
|
+
|
|
19
|
+
version 0.3
|
|
20
|
+
-error type added: duplicated
|
|
21
|
+
|
|
22
|
+
version 0.2
|
|
23
|
+
- error type inserted: outliers
|
|
24
|
+
|
|
25
|
+
version 0.1
|
|
26
|
+
|
|
27
|
+
- error type inserted: noisy error and inconsistency labels
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
## Installation
|
|
31
|
+
|
|
32
|
+
You can install pucktrick using pip:
|
|
33
|
+
|
|
34
|
+
pip install pucktrick
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
## References
|
|
38
|
+
|
|
39
|
+
## Contributing
|
|
40
|
+
We welcome contributions from the community. To contribute:
|
|
41
|
+
|
|
42
|
+
Fork the repository
|
|
43
|
+
Create a new branch (git checkout -b feature/your-feature)
|
|
44
|
+
Commit your changes (git commit -am 'Add new feature')
|
|
45
|
+
Push to the branch (git push origin feature/your-feature)
|
|
46
|
+
Create a new Pull Request
|
|
47
|
+
Please ensure your code adheres to our coding standards and includes appropriate tests.
|
|
48
|
+
|
|
49
|
+
License
|
|
50
|
+
This project is licensed under the Creative Commons Attribution-NonCommercial 4.0 International (CC BY-NC 4.0) - see the LICENSE file for details.
|
|
51
|
+
|
|
52
|
+
Acknowledgements
|
|
53
|
+
Thanks to the contributors and open-source community for their support.
|
|
File without changes
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.5.0"
|
|
@@ -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
|
+
|
|
@@ -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
|
|
@@ -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
|
|
@@ -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
|
+
|