-
Notifications
You must be signed in to change notification settings - Fork 36
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add OpReplaceAnyElements to ops_common #340
Merged
+151
−2
Merged
Changes from 6 commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
e016ff3
add OpReplaceAnyElement
998b4c6
add op_replace_any + tests
862abc9
cleanup
f6ee01d
add missing typing
f40df75
Merge branch 'master' into op_replace_any
sivanravidos 7e0dd96
Merge branch 'master' into op_replace_any
sivanravidos d8935cb
fix type documentation
e7b6de2
Merge branch 'op_replace_any' of github.com:BiomedSciAI/fuse-med-ml i…
52a6749
improve docstring
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -702,3 +702,61 @@ def __call__( | |
raise Exception(f"Unsupported object type {type(input_obj)}") | ||
|
||
return sample_dict | ||
|
||
|
||
class OpReplaceAnyElements(OpBase): | ||
""" | ||
Replace any element from a given list of elements with a requested value | ||
|
||
For example, given the tensor [0,1,2,3,4,3,2,1,0], the list [0,2,4] and new value -100 - will return [-100,1,-100,3,-100,3,-100,1,-100]. | ||
This is useful, for example, when converting a set of token IDs to -100 to make a metric ignore certain elements (e.g. all special tokens). | ||
""" | ||
|
||
def __call__( | ||
self, | ||
sample_dict: NDict, | ||
key_in: str, | ||
find_any_val: List[Any], | ||
replace_with_val: Any, | ||
key_out: str = None, | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Optional[str] There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. fixed |
||
) -> NDict: | ||
""" | ||
Args: | ||
key_in: the input numpy array, tensor, list or str | ||
find_any_val: a list of values to will be replaces | ||
replace_with_val: the value that will be used to replace "find_any_val" elements | ||
key_out: if None, the modification will be inplace in "key_in" (faster), other wise, the name of the key to write to | ||
""" | ||
assert ( | ||
key_in in sample_dict | ||
), f"Error: missing {key_in}, available keys {sample_dict.keypaths()} " | ||
|
||
input_obj = sample_dict[key_in] | ||
|
||
if key_out is not None: | ||
if torch.is_tensor(input_obj): | ||
input_obj = input_obj.clone() | ||
elif isinstance(input_obj, np.ndarray): | ||
input_obj = input_obj.copy() | ||
else: | ||
key_out = key_in | ||
|
||
find_any_set = set(find_any_val) | ||
if torch.is_tensor(input_obj) or isinstance(input_obj, np.ndarray): | ||
output_obj = input_obj | ||
output_obj[ | ||
(output_obj[..., None] == torch.tensor(find_any_val)).any(-1).nonzero() | ||
] = replace_with_val | ||
sample_dict[key_out] = output_obj | ||
elif isinstance(sample_dict[key_in], str): | ||
sample_dict[key_out] = input_obj.translate( | ||
str.maketrans({x: replace_with_val for x in find_any_val}) | ||
) | ||
elif isinstance(input_obj, (list, tuple)): | ||
sample_dict[key_out] = [ | ||
replace_with_val if x in find_any_set else x for x in input_obj | ||
] | ||
else: | ||
raise Exception(f"Unsupported object type {type(input_obj)}") | ||
|
||
return sample_dict |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
list./ numpy array or tensor
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
fixed