-
Notifications
You must be signed in to change notification settings - Fork 613
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
Snake layer and activation to learn periodic functions #1967
Changes from all commits
be8cf1a
6d5e260
25e3d84
add059f
179c8ef
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,37 @@ | ||
# Copyright 2020 The TensorFlow Authors. All Rights Reserved. | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
# ============================================================================== | ||
|
||
import tensorflow as tf | ||
|
||
from tensorflow_addons.utils import types | ||
|
||
|
||
@tf.keras.utils.register_keras_serializable(package="Addons") | ||
def snake(logits: types.TensorLike, frequency: types.Number = 1) -> tf.Tensor: | ||
"""Snake activation to learn periodic functions. | ||
|
||
https://arxiv.org/abs/2006.08195 | ||
|
||
Args: | ||
logits: Input tensor. | ||
frequency: A scalar, frequency of the periodic part. | ||
Returns: | ||
Tensor of the same type and shape as `logits`. | ||
""" | ||
|
||
logits = tf.convert_to_tensor(logits) | ||
frequency = tf.cast(frequency, logits.dtype) | ||
|
||
return logits + (1 - tf.cos(2 * frequency * logits)) / (2 * frequency) |
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -27,6 +27,7 @@ | |
"softshrink", | ||
"sparsemax", | ||
"tanhshrink", | ||
"snake", | ||
] | ||
|
||
|
||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
# Copyright 2020 The TensorFlow Authors. All Rights Reserved. | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
# ============================================================================== | ||
|
||
import pytest | ||
|
||
import numpy as np | ||
from tensorflow_addons.activations import snake | ||
from tensorflow_addons.utils import test_utils | ||
|
||
|
||
@pytest.mark.usefixtures("maybe_run_functions_eagerly") | ||
@pytest.mark.parametrize("dtype", [np.float16, np.float32, np.float64]) | ||
def test_activation(dtype): | ||
x = dtype(np.random.rand(2, 5)) | ||
a = dtype(np.random.randn()) | ||
expected_result = x + np.power(np.sin(a * x), 2) / a | ||
test_utils.assert_allclose_according_to_type(snake(x, a), expected_result) |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,53 @@ | ||
# Copyright 2020 The TensorFlow Authors. All Rights Reserved. | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
# ============================================================================== | ||
"""Implements Snake layer.""" | ||
|
||
import tensorflow as tf | ||
from typeguard import typechecked | ||
|
||
from tensorflow_addons.activations.snake import snake | ||
|
||
from tensorflow_addons.utils import types | ||
|
||
|
||
@tf.keras.utils.register_keras_serializable(package="Addons") | ||
class Snake(tf.keras.layers.Layer): | ||
"""Snake layer to learn periodic functions with the trainable `frequency` scalar. | ||
|
||
https://arxiv.org/abs/2006.08195 | ||
|
||
Arguments: | ||
frequency_initializer: Initializer for the `frequency` scalar. | ||
""" | ||
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. could we add the arguments doc here? 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. I put them near the init for an IDE autocomplete. |
||
|
||
@typechecked | ||
def __init__(self, frequency_initializer: types.Initializer = "ones", **kwargs): | ||
super().__init__(**kwargs) | ||
self.frequency_initializer = tf.keras.initializers.get(frequency_initializer) | ||
self.frequency = self.add_weight( | ||
initializer=frequency_initializer, trainable=True | ||
) | ||
|
||
def call(self, inputs): | ||
return snake(inputs, self.frequency) | ||
|
||
def get_config(self): | ||
config = { | ||
"frequency_initializer": tf.keras.initializers.serialize( | ||
self.frequency_initializer | ||
), | ||
} | ||
base_config = super().get_config() | ||
return {**base_config, **config} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
# Copyright 2020 The TensorFlow Authors. All Rights Reserved. | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
# ============================================================================== | ||
"""Tests for Snake layer.""" | ||
|
||
import pytest | ||
|
||
import numpy as np | ||
import tensorflow as tf | ||
|
||
from tensorflow_addons.layers.snake import Snake | ||
from tensorflow_addons.activations.snake import snake | ||
|
||
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. ditto |
||
from tensorflow_addons.utils import test_utils | ||
|
||
|
||
@pytest.mark.usefixtures("maybe_run_functions_eagerly") | ||
@pytest.mark.parametrize("dtype", [np.float16, np.float32, np.float64]) | ||
def test_layer(dtype): | ||
x = np.random.rand(2, 5).astype(dtype) | ||
a = np.random.randn() | ||
val = snake(x, a) | ||
test_utils.layer_test( | ||
Snake, | ||
kwargs={"frequency_initializer": tf.constant_initializer(a), "dtype": dtype}, | ||
input_data=x, | ||
expected_output=val, | ||
) |
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.
could we add the arguments doc here?
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.
I was trying, but the original academic paper is quite obscure about explanations. So it could has end-up with words like 'frequency is a frequency' and other obvious things such as 'input is an input'. If it is OK anyway, no problems, I'll add.
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.
Got it. Maybe we can have something like