We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
 ValueError: Tensor conversion requested dtype float32 for Tensor with dtype uint8 when using losses.SigmoidFocalCrossEntropy
**System information**
- OS Platform and Distribution (e.g., Linux Ubuntu 16.04): Ubuntu 20.04
- TensorFlow version and how it was installed (source or binary): 2.4.0, pip
- TensorFlow-Addons version and how it was installed (source or binary): 0.11.2, pip
- Python version: 3.8
- Is GPU used? (yes/no): yes

```
ValueError: in user code:

    /home/eck/software/anaconda3/envs/hk2/lib/python3.8/site-packages/tensorflow/python/keras/engine/training.py:805 train_function  *
        return step_function(self, iterator)
    /home/eck/software/anaconda3/envs/hk2/lib/python3.8/site-packages/tensorflow_addons/utils/keras_utils.py:61 call  *
        return self.fn(y_true, y_pred, **self._fn_kwargs)
    /home/eck/software/anaconda3/envs/hk2/lib/python3.8/site-packages/tensorflow_addons/losses/focal_loss.py:122 sigmoid_focal_crossentropy  *
        y_true = tf.convert_to_tensor(y_true, dtype=y_pred.dtype)
    /home/eck/software/anaconda3/envs/hk2/lib/python3.8/site-packages/tensorflow/python/util/dispatch.py:201 wrapper  **
        return target(*args, **kwargs)
    /home/eck/software/anaconda3/envs/hk2/lib/python3.8/site-packages/tensorflow/python/framework/ops.py:1404 convert_to_tensor_v2_with_dispatch
        return convert_to_tensor_v2(
    /home/eck/software/anaconda3/envs/hk2/lib/python3.8/site-packages/tensorflow/python/framework/ops.py:1410 convert_to_tensor_v2
        return convert_to_tensor(
    /home/eck/software/anaconda3/envs/hk2/lib/python3.8/site-packages/tensorflow/python/profiler/trace.py:163 wrapped
        return func(*args, **kwargs)
    /home/eck/software/anaconda3/envs/hk2/lib/python3.8/site-packages/tensorflow/python/framework/ops.py:1507 convert_to_tensor
        raise ValueError(

    ValueError: Tensor conversion requested dtype float32 for Tensor with dtype uint8: <tf.Tensor 'y_true:0' shape=(None, None, None, 1) dtype=uint8>
```


When y_true had dtype of uint8 and y_pred had dtype float32, `tf.conver_to_tensor(y_true, y_pred.dtype)` in focal loss function failed.

Is it intended that y_true and y_pred have the same dtype when passed to the loss function? Do I need to convert y_true into float32 tensor in data processing step?






--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `tensorflow_addons/losses/focal_loss.py`
Content:
```
1 # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 #     http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14 # ==============================================================================
15 """Implements Focal loss."""
16 
17 import tensorflow as tf
18 import tensorflow.keras.backend as K
19 from typeguard import typechecked
20 
21 from tensorflow_addons.utils.keras_utils import LossFunctionWrapper
22 from tensorflow_addons.utils.types import FloatTensorLike, TensorLike
23 
24 
25 @tf.keras.utils.register_keras_serializable(package="Addons")
26 class SigmoidFocalCrossEntropy(LossFunctionWrapper):
27     """Implements the focal loss function.
28 
29     Focal loss was first introduced in the RetinaNet paper
30     (https://arxiv.org/pdf/1708.02002.pdf). Focal loss is extremely useful for
31     classification when you have highly imbalanced classes. It down-weights
32     well-classified examples and focuses on hard examples. The loss value is
33     much high for a sample which is misclassified by the classifier as compared
34     to the loss value corresponding to a well-classified example. One of the
35     best use-cases of focal loss is its usage in object detection where the
36     imbalance between the background class and other classes is extremely high.
37 
38     Usage:
39 
40     >>> fl = tfa.losses.SigmoidFocalCrossEntropy()
41     >>> loss = fl(
42     ...     y_true = [[1.0], [1.0], [0.0]],y_pred = [[0.97], [0.91], [0.03]])
43     >>> loss
44     <tf.Tensor: shape=(3,), dtype=float32, numpy=array([6.8532745e-06, 1.9097870e-04, 2.0559824e-05],
45     dtype=float32)>
46 
47     Usage with `tf.keras` API:
48 
49     >>> model = tf.keras.Model()
50     >>> model.compile('sgd', loss=tfa.losses.SigmoidFocalCrossEntropy())
51 
52     Args:
53       alpha: balancing factor, default value is 0.25.
54       gamma: modulating factor, default value is 2.0.
55 
56     Returns:
57       Weighted loss float `Tensor`. If `reduction` is `NONE`, this has the same
58           shape as `y_true`; otherwise, it is scalar.
59 
60     Raises:
61         ValueError: If the shape of `sample_weight` is invalid or value of
62           `gamma` is less than zero.
63     """
64 
65     @typechecked
66     def __init__(
67         self,
68         from_logits: bool = False,
69         alpha: FloatTensorLike = 0.25,
70         gamma: FloatTensorLike = 2.0,
71         reduction: str = tf.keras.losses.Reduction.NONE,
72         name: str = "sigmoid_focal_crossentropy",
73     ):
74         super().__init__(
75             sigmoid_focal_crossentropy,
76             name=name,
77             reduction=reduction,
78             from_logits=from_logits,
79             alpha=alpha,
80             gamma=gamma,
81         )
82 
83 
84 @tf.keras.utils.register_keras_serializable(package="Addons")
85 @tf.function
86 def sigmoid_focal_crossentropy(
87     y_true: TensorLike,
88     y_pred: TensorLike,
89     alpha: FloatTensorLike = 0.25,
90     gamma: FloatTensorLike = 2.0,
91     from_logits: bool = False,
92 ) -> tf.Tensor:
93     """Implements the focal loss function.
94 
95     Focal loss was first introduced in the RetinaNet paper
96     (https://arxiv.org/pdf/1708.02002.pdf). Focal loss is extremely useful for
97     classification when you have highly imbalanced classes. It down-weights
98     well-classified examples and focuses on hard examples. The loss value is
99     much high for a sample which is misclassified by the classifier as compared
100     to the loss value corresponding to a well-classified example. One of the
101     best use-cases of focal loss is its usage in object detection where the
102     imbalance between the background class and other classes is extremely high.
103 
104     Args:
105         y_true: true targets tensor.
106         y_pred: predictions tensor.
107         alpha: balancing factor.
108         gamma: modulating factor.
109 
110     Returns:
111         Weighted loss float `Tensor`. If `reduction` is `NONE`,this has the
112         same shape as `y_true`; otherwise, it is scalar.
113     """
114     if gamma and gamma < 0:
115         raise ValueError("Value of gamma should be greater than or equal to zero")
116 
117     y_pred = tf.convert_to_tensor(y_pred)
118     y_true = tf.convert_to_tensor(y_true, dtype=y_pred.dtype)
119 
120     # Get the cross_entropy for each entry
121     ce = K.binary_crossentropy(y_true, y_pred, from_logits=from_logits)
122 
123     # If logits are provided then convert the predictions into probabilities
124     if from_logits:
125         pred_prob = tf.sigmoid(y_pred)
126     else:
127         pred_prob = y_pred
128 
129     p_t = (y_true * pred_prob) + ((1 - y_true) * (1 - pred_prob))
130     alpha_factor = 1.0
131     modulating_factor = 1.0
132 
133     if alpha:
134         alpha = tf.convert_to_tensor(alpha, dtype=K.floatx())
135         alpha_factor = y_true * alpha + (1 - y_true) * (1 - alpha)
136 
137     if gamma:
138         gamma = tf.convert_to_tensor(gamma, dtype=K.floatx())
139         modulating_factor = tf.pow((1.0 - p_t), gamma)
140 
141     # compute the final loss and return
142     return tf.reduce_sum(alpha_factor * modulating_factor * ce, axis=-1)
143
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/tensorflow_addons/losses/focal_loss.py b/tensorflow_addons/losses/focal_loss.py
--- a/tensorflow_addons/losses/focal_loss.py
+++ b/tensorflow_addons/losses/focal_loss.py
@@ -112,10 +112,10 @@
         same shape as `y_true`; otherwise, it is scalar.
     """
     if gamma and gamma < 0:
-        raise ValueError("Value of gamma should be greater than or equal to zero")
+        raise ValueError("Value of gamma should be greater than or equal to zero.")
 
     y_pred = tf.convert_to_tensor(y_pred)
-    y_true = tf.convert_to_tensor(y_true, dtype=y_pred.dtype)
+    y_true = tf.cast(y_true, dtype=y_pred.dtype)
 
     # Get the cross_entropy for each entry
     ce = K.binary_crossentropy(y_true, y_pred, from_logits=from_logits)
@@ -131,11 +131,11 @@
     modulating_factor = 1.0
 
     if alpha:
-        alpha = tf.convert_to_tensor(alpha, dtype=K.floatx())
+        alpha = tf.cast(alpha, dtype=y_true.dtype)
         alpha_factor = y_true * alpha + (1 - y_true) * (1 - alpha)
 
     if gamma:
-        gamma = tf.convert_to_tensor(gamma, dtype=K.floatx())
+        gamma = tf.cast(gamma, dtype=y_true.dtype)
         modulating_factor = tf.pow((1.0 - p_t), gamma)
 
     # compute the final loss and return

{"golden_diff": "diff --git a/tensorflow_addons/losses/focal_loss.py b/tensorflow_addons/losses/focal_loss.py\n--- a/tensorflow_addons/losses/focal_loss.py\n+++ b/tensorflow_addons/losses/focal_loss.py\n@@ -112,10 +112,10 @@\n         same shape as `y_true`; otherwise, it is scalar.\n     \"\"\"\n     if gamma and gamma < 0:\n-        raise ValueError(\"Value of gamma should be greater than or equal to zero\")\n+        raise ValueError(\"Value of gamma should be greater than or equal to zero.\")\n \n     y_pred = tf.convert_to_tensor(y_pred)\n-    y_true = tf.convert_to_tensor(y_true, dtype=y_pred.dtype)\n+    y_true = tf.cast(y_true, dtype=y_pred.dtype)\n \n     # Get the cross_entropy for each entry\n     ce = K.binary_crossentropy(y_true, y_pred, from_logits=from_logits)\n@@ -131,11 +131,11 @@\n     modulating_factor = 1.0\n \n     if alpha:\n-        alpha = tf.convert_to_tensor(alpha, dtype=K.floatx())\n+        alpha = tf.cast(alpha, dtype=y_true.dtype)\n         alpha_factor = y_true * alpha + (1 - y_true) * (1 - alpha)\n \n     if gamma:\n-        gamma = tf.convert_to_tensor(gamma, dtype=K.floatx())\n+        gamma = tf.cast(gamma, dtype=y_true.dtype)\n         modulating_factor = tf.pow((1.0 - p_t), gamma)\n \n     # compute the final loss and return\n", "issue": " ValueError: Tensor conversion requested dtype float32 for Tensor with dtype uint8 when using losses.SigmoidFocalCrossEntropy\n**System information**\r\n- OS Platform and Distribution (e.g., Linux Ubuntu 16.04): Ubuntu 20.04\r\n- TensorFlow version and how it was installed (source or binary): 2.4.0, pip\r\n- TensorFlow-Addons version and how it was installed (source or binary): 0.11.2, pip\r\n- Python version: 3.8\r\n- Is GPU used? (yes/no): yes\r\n\r\n```\r\nValueError: in user code:\r\n\r\n    /home/eck/software/anaconda3/envs/hk2/lib/python3.8/site-packages/tensorflow/python/keras/engine/training.py:805 train_function  *\r\n        return step_function(self, iterator)\r\n    /home/eck/software/anaconda3/envs/hk2/lib/python3.8/site-packages/tensorflow_addons/utils/keras_utils.py:61 call  *\r\n        return self.fn(y_true, y_pred, **self._fn_kwargs)\r\n    /home/eck/software/anaconda3/envs/hk2/lib/python3.8/site-packages/tensorflow_addons/losses/focal_loss.py:122 sigmoid_focal_crossentropy  *\r\n        y_true = tf.convert_to_tensor(y_true, dtype=y_pred.dtype)\r\n    /home/eck/software/anaconda3/envs/hk2/lib/python3.8/site-packages/tensorflow/python/util/dispatch.py:201 wrapper  **\r\n        return target(*args, **kwargs)\r\n    /home/eck/software/anaconda3/envs/hk2/lib/python3.8/site-packages/tensorflow/python/framework/ops.py:1404 convert_to_tensor_v2_with_dispatch\r\n        return convert_to_tensor_v2(\r\n    /home/eck/software/anaconda3/envs/hk2/lib/python3.8/site-packages/tensorflow/python/framework/ops.py:1410 convert_to_tensor_v2\r\n        return convert_to_tensor(\r\n    /home/eck/software/anaconda3/envs/hk2/lib/python3.8/site-packages/tensorflow/python/profiler/trace.py:163 wrapped\r\n        return func(*args, **kwargs)\r\n    /home/eck/software/anaconda3/envs/hk2/lib/python3.8/site-packages/tensorflow/python/framework/ops.py:1507 convert_to_tensor\r\n        raise ValueError(\r\n\r\n    ValueError: Tensor conversion requested dtype float32 for Tensor with dtype uint8: <tf.Tensor 'y_true:0' shape=(None, None, None, 1) dtype=uint8>\r\n```\r\n\r\n\r\nWhen y_true had dtype of uint8 and y_pred had dtype float32, `tf.conver_to_tensor(y_true, y_pred.dtype)` in focal loss function failed.\r\n\r\nIs it intended that y_true and y_pred have the same dtype when passed to the loss function? Do I need to convert y_true into float32 tensor in data processing step?\r\n\r\n\r\n\r\n\r\n\n", "before_files": [{"content": "# Copyright 2019 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Implements Focal loss.\"\"\"\n\nimport tensorflow as tf\nimport tensorflow.keras.backend as K\nfrom typeguard import typechecked\n\nfrom tensorflow_addons.utils.keras_utils import LossFunctionWrapper\nfrom tensorflow_addons.utils.types import FloatTensorLike, TensorLike\n\n\n@tf.keras.utils.register_keras_serializable(package=\"Addons\")\nclass SigmoidFocalCrossEntropy(LossFunctionWrapper):\n    \"\"\"Implements the focal loss function.\n\n    Focal loss was first introduced in the RetinaNet paper\n    (https://arxiv.org/pdf/1708.02002.pdf). Focal loss is extremely useful for\n    classification when you have highly imbalanced classes. It down-weights\n    well-classified examples and focuses on hard examples. The loss value is\n    much high for a sample which is misclassified by the classifier as compared\n    to the loss value corresponding to a well-classified example. One of the\n    best use-cases of focal loss is its usage in object detection where the\n    imbalance between the background class and other classes is extremely high.\n\n    Usage:\n\n    >>> fl = tfa.losses.SigmoidFocalCrossEntropy()\n    >>> loss = fl(\n    ...     y_true = [[1.0], [1.0], [0.0]],y_pred = [[0.97], [0.91], [0.03]])\n    >>> loss\n    <tf.Tensor: shape=(3,), dtype=float32, numpy=array([6.8532745e-06, 1.9097870e-04, 2.0559824e-05],\n    dtype=float32)>\n\n    Usage with `tf.keras` API:\n\n    >>> model = tf.keras.Model()\n    >>> model.compile('sgd', loss=tfa.losses.SigmoidFocalCrossEntropy())\n\n    Args:\n      alpha: balancing factor, default value is 0.25.\n      gamma: modulating factor, default value is 2.0.\n\n    Returns:\n      Weighted loss float `Tensor`. If `reduction` is `NONE`, this has the same\n          shape as `y_true`; otherwise, it is scalar.\n\n    Raises:\n        ValueError: If the shape of `sample_weight` is invalid or value of\n          `gamma` is less than zero.\n    \"\"\"\n\n    @typechecked\n    def __init__(\n        self,\n        from_logits: bool = False,\n        alpha: FloatTensorLike = 0.25,\n        gamma: FloatTensorLike = 2.0,\n        reduction: str = tf.keras.losses.Reduction.NONE,\n        name: str = \"sigmoid_focal_crossentropy\",\n    ):\n        super().__init__(\n            sigmoid_focal_crossentropy,\n            name=name,\n            reduction=reduction,\n            from_logits=from_logits,\n            alpha=alpha,\n            gamma=gamma,\n        )\n\n\n@tf.keras.utils.register_keras_serializable(package=\"Addons\")\n@tf.function\ndef sigmoid_focal_crossentropy(\n    y_true: TensorLike,\n    y_pred: TensorLike,\n    alpha: FloatTensorLike = 0.25,\n    gamma: FloatTensorLike = 2.0,\n    from_logits: bool = False,\n) -> tf.Tensor:\n    \"\"\"Implements the focal loss function.\n\n    Focal loss was first introduced in the RetinaNet paper\n    (https://arxiv.org/pdf/1708.02002.pdf). Focal loss is extremely useful for\n    classification when you have highly imbalanced classes. It down-weights\n    well-classified examples and focuses on hard examples. The loss value is\n    much high for a sample which is misclassified by the classifier as compared\n    to the loss value corresponding to a well-classified example. One of the\n    best use-cases of focal loss is its usage in object detection where the\n    imbalance between the background class and other classes is extremely high.\n\n    Args:\n        y_true: true targets tensor.\n        y_pred: predictions tensor.\n        alpha: balancing factor.\n        gamma: modulating factor.\n\n    Returns:\n        Weighted loss float `Tensor`. If `reduction` is `NONE`,this has the\n        same shape as `y_true`; otherwise, it is scalar.\n    \"\"\"\n    if gamma and gamma < 0:\n        raise ValueError(\"Value of gamma should be greater than or equal to zero\")\n\n    y_pred = tf.convert_to_tensor(y_pred)\n    y_true = tf.convert_to_tensor(y_true, dtype=y_pred.dtype)\n\n    # Get the cross_entropy for each entry\n    ce = K.binary_crossentropy(y_true, y_pred, from_logits=from_logits)\n\n    # If logits are provided then convert the predictions into probabilities\n    if from_logits:\n        pred_prob = tf.sigmoid(y_pred)\n    else:\n        pred_prob = y_pred\n\n    p_t = (y_true * pred_prob) + ((1 - y_true) * (1 - pred_prob))\n    alpha_factor = 1.0\n    modulating_factor = 1.0\n\n    if alpha:\n        alpha = tf.convert_to_tensor(alpha, dtype=K.floatx())\n        alpha_factor = y_true * alpha + (1 - y_true) * (1 - alpha)\n\n    if gamma:\n        gamma = tf.convert_to_tensor(gamma, dtype=K.floatx())\n        modulating_factor = tf.pow((1.0 - p_t), gamma)\n\n    # compute the final loss and return\n    return tf.reduce_sum(alpha_factor * modulating_factor * ce, axis=-1)\n", "path": "tensorflow_addons/losses/focal_loss.py"}], "after_files": [{"content": "# Copyright 2019 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Implements Focal loss.\"\"\"\n\nimport tensorflow as tf\nimport tensorflow.keras.backend as K\nfrom typeguard import typechecked\n\nfrom tensorflow_addons.utils.keras_utils import LossFunctionWrapper\nfrom tensorflow_addons.utils.types import FloatTensorLike, TensorLike\n\n\n@tf.keras.utils.register_keras_serializable(package=\"Addons\")\nclass SigmoidFocalCrossEntropy(LossFunctionWrapper):\n    \"\"\"Implements the focal loss function.\n\n    Focal loss was first introduced in the RetinaNet paper\n    (https://arxiv.org/pdf/1708.02002.pdf). Focal loss is extremely useful for\n    classification when you have highly imbalanced classes. It down-weights\n    well-classified examples and focuses on hard examples. The loss value is\n    much high for a sample which is misclassified by the classifier as compared\n    to the loss value corresponding to a well-classified example. One of the\n    best use-cases of focal loss is its usage in object detection where the\n    imbalance between the background class and other classes is extremely high.\n\n    Usage:\n\n    >>> fl = tfa.losses.SigmoidFocalCrossEntropy()\n    >>> loss = fl(\n    ...     y_true = [[1.0], [1.0], [0.0]],y_pred = [[0.97], [0.91], [0.03]])\n    >>> loss\n    <tf.Tensor: shape=(3,), dtype=float32, numpy=array([6.8532745e-06, 1.9097870e-04, 2.0559824e-05],\n    dtype=float32)>\n\n    Usage with `tf.keras` API:\n\n    >>> model = tf.keras.Model()\n    >>> model.compile('sgd', loss=tfa.losses.SigmoidFocalCrossEntropy())\n\n    Args:\n      alpha: balancing factor, default value is 0.25.\n      gamma: modulating factor, default value is 2.0.\n\n    Returns:\n      Weighted loss float `Tensor`. If `reduction` is `NONE`, this has the same\n          shape as `y_true`; otherwise, it is scalar.\n\n    Raises:\n        ValueError: If the shape of `sample_weight` is invalid or value of\n          `gamma` is less than zero.\n    \"\"\"\n\n    @typechecked\n    def __init__(\n        self,\n        from_logits: bool = False,\n        alpha: FloatTensorLike = 0.25,\n        gamma: FloatTensorLike = 2.0,\n        reduction: str = tf.keras.losses.Reduction.NONE,\n        name: str = \"sigmoid_focal_crossentropy\",\n    ):\n        super().__init__(\n            sigmoid_focal_crossentropy,\n            name=name,\n            reduction=reduction,\n            from_logits=from_logits,\n            alpha=alpha,\n            gamma=gamma,\n        )\n\n\n@tf.keras.utils.register_keras_serializable(package=\"Addons\")\n@tf.function\ndef sigmoid_focal_crossentropy(\n    y_true: TensorLike,\n    y_pred: TensorLike,\n    alpha: FloatTensorLike = 0.25,\n    gamma: FloatTensorLike = 2.0,\n    from_logits: bool = False,\n) -> tf.Tensor:\n    \"\"\"Implements the focal loss function.\n\n    Focal loss was first introduced in the RetinaNet paper\n    (https://arxiv.org/pdf/1708.02002.pdf). Focal loss is extremely useful for\n    classification when you have highly imbalanced classes. It down-weights\n    well-classified examples and focuses on hard examples. The loss value is\n    much high for a sample which is misclassified by the classifier as compared\n    to the loss value corresponding to a well-classified example. One of the\n    best use-cases of focal loss is its usage in object detection where the\n    imbalance between the background class and other classes is extremely high.\n\n    Args:\n        y_true: true targets tensor.\n        y_pred: predictions tensor.\n        alpha: balancing factor.\n        gamma: modulating factor.\n\n    Returns:\n        Weighted loss float `Tensor`. If `reduction` is `NONE`,this has the\n        same shape as `y_true`; otherwise, it is scalar.\n    \"\"\"\n    if gamma and gamma < 0:\n        raise ValueError(\"Value of gamma should be greater than or equal to zero.\")\n\n    y_pred = tf.convert_to_tensor(y_pred)\n    y_true = tf.cast(y_true, dtype=y_pred.dtype)\n\n    # Get the cross_entropy for each entry\n    ce = K.binary_crossentropy(y_true, y_pred, from_logits=from_logits)\n\n    # If logits are provided then convert the predictions into probabilities\n    if from_logits:\n        pred_prob = tf.sigmoid(y_pred)\n    else:\n        pred_prob = y_pred\n\n    p_t = (y_true * pred_prob) + ((1 - y_true) * (1 - pred_prob))\n    alpha_factor = 1.0\n    modulating_factor = 1.0\n\n    if alpha:\n        alpha = tf.cast(alpha, dtype=y_true.dtype)\n        alpha_factor = y_true * alpha + (1 - y_true) * (1 - alpha)\n\n    if gamma:\n        gamma = tf.cast(gamma, dtype=y_true.dtype)\n        modulating_factor = tf.pow((1.0 - p_t), gamma)\n\n    # compute the final loss and return\n    return tf.reduce_sum(alpha_factor * modulating_factor * ce, axis=-1)\n", "path": "tensorflow_addons/losses/focal_loss.py"}]}