示例#1
0
#
#    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.
# ============================================================================
"""Tensorflow op performing correlation cost operation."""

import tensorflow as tf
from typeguard import typechecked
from tensorflow_addons.utils.resource_loader import LazySO

_correlation_cost_so = LazySO("custom_ops/layers/_correlation_cost_ops.so")


def _correlation_cost(
    input_a,
    input_b,
    kernel_size,
    max_displacement,
    stride_1,
    stride_2,
    pad,
    data_format="channels_last",
    name=None,
):
    """Correlation Cost Volume computation.
示例#2
0
# 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.
# ==============================================================================
"""Python layer for distort_image_ops."""

import tensorflow as tf
from tensorflow_addons.utils.resource_loader import LazySO

_distort_image_so = LazySO("custom_ops/image/_distort_image_ops.so")


# pylint: disable=invalid-name
def random_hsv_in_yiq(image,
                      max_delta_hue=0,
                      lower_saturation=1,
                      upper_saturation=1,
                      lower_value=1,
                      upper_value=1,
                      seed=None,
                      name=None):
    """Adjust hue, saturation, value of an RGB image randomly in YIQ color
    space.

    Equivalent to `adjust_yiq_hsv()` but uses a `delta_h` randomly
示例#3
0
#
#     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.
# ==============================================================================
"""Parse time ops."""

import tensorflow as tf

from tensorflow_addons.utils.resource_loader import LazySO

_parse_time_so = LazySO("custom_ops/text/_parse_time_op.so")

tf.no_gradient("Addons>ParseTime")


def parse_time(time_string: str, time_format: str, output_unit: str) -> str:
    """Parse an input string according to the provided format string into a
    Unix time.

    Parse an input string according to the provided format string into a Unix
    time, the number of seconds / milliseconds / microseconds / nanoseconds
    elapsed since January 1, 1970 UTC.

    Uses strftime()-like formatting options, with the same extensions as
    FormatTime(), but with the exceptions that %E#S is interpreted as %E*S, and
    %E#f as %E*f.  %Ez and %E*z also accept the same inputs.
示例#4
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 warnings
import tensorflow as tf
from tensorflow_addons.utils.types import Number

from tensorflow_addons.utils import types
from tensorflow_addons.utils.resource_loader import LazySO
from tensorflow_addons import options

_activation_so = LazySO("custom_ops/activations/_activation_ops.so")


@tf.keras.utils.register_keras_serializable(package="Addons")
def hardshrink(
    x: types.TensorLike, lower: Number = -0.5, upper: Number = 0.5
) -> tf.Tensor:
    """Hard shrink function.

    Computes hard shrink function:
    `x if x < lower or x > upper else 0`.

    Args:
        x: A `Tensor`. Must be one of the following types:
            `float16`, `float32`, `float64`.
        lower: `float`, lower bound for setting values to zeros.
示例#5
0
#     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 typeguard import typechecked

from tensorflow_addons.utils.types import Constraint, Initializer, Regularizer
from tensorflow_addons.utils.resource_loader import LazySO

_embedding_bag_so = LazySO("custom_ops/layers/_embedding_bag_ops.so")


def _embedding_bag(
    indices,
    params,
    weights=None,
    combiner="sum",
    name=None,
):
    """EmbeddingBag computation.

    See [PyTorch op](https://pytorch.org/docs/stable/generated/torch.nn.EmbeddingBag.html).

    Equivalent to tf.gather() followed by tf.reduce_{sum,mean}() across the last dimension, with optional
    weights. Fusing these into a single op has massive benefits for execution speed and particularly
示例#6
0
from datetime import datetime
from malaya import home, _delete_folder, gpu_available, __gpu__

URL = 'https://f000.backblazeb2.com/file/malaya-model/'


def check_tf_version():
    version = tf.__version__
    return int(version.split('.')[0])


if check_tf_version() > 1:
    try:
        from tensorflow_addons.utils.resource_loader import LazySO

        _beam_search_so = LazySO('custom_ops/seq2seq/_beam_search_ops.so')
        gather_tree = _beam_search_so.ops.addons_gather_tree
    except:
        import warnings

        warnings.warn(
            'Cannot import beam_search_ops from Tensorflow Addons, `deep_model` for stemmer will not available to use, make sure Tensorflow Addons version >= 0.12.0'
        )

else:
    try:
        from tensorflow.contrib.seq2seq.python.ops import beam_search_ops
    except:
        import warnings

        warnings.warn(
示例#7
0
# 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.
# ==============================================================================
"""Skip-gram sampling ops from https://arxiv.org/abs/1301.3781."""

import csv
import tensorflow as tf

from tensorflow_addons.utils.resource_loader import LazySO

from tensorflow_addons.utils.types import AcceptableDTypes, FloatTensorLike, TensorLike
from typing import Optional

_skip_gram_so = LazySO("custom_ops/text/_skip_gram_ops.so")

tf.no_gradient("Addons>SkipGramGenerateCandidates")


def skip_gram_sample(
    input_tensor: TensorLike,
    min_skips: FloatTensorLike = 1,
    max_skips: FloatTensorLike = 5,
    start: FloatTensorLike = 0,
    limit: FloatTensorLike = -1,
    emit_self_as_target: bool = False,
    vocab_freq_table: tf.lookup.KeyValueTensorInitializer = None,
    vocab_min_count: Optional[FloatTensorLike] = None,
    vocab_subsampling: Optional[FloatTensorLike] = None,
    corpus_size: Optional[FloatTensorLike] = None,
示例#8
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.
# ============================================================================
"""Python layer for Resampler."""

import tensorflow as tf

from tensorflow_addons.utils import types
from tensorflow_addons.utils.resource_loader import LazySO

from typing import Optional

_resampler_so = LazySO("custom_ops/image/_resampler_ops.so")


@tf.function
def resampler(data: types.TensorLike,
              warp: types.TensorLike,
              name: Optional[str] = None) -> tf.Tensor:
    """Resamples input data at user defined coordinates.

    The resampler currently only supports bilinear interpolation of 2D data.

    Args:
      data: Tensor of shape `[batch_size, data_height, data_width,
        data_num_channels]` containing 2D data that will be resampled.
      warp: Tensor of minimum rank 2 containing the coordinates at
      which resampling will be performed. Since only bilinear