Best Python code snippet using locust
joint_cost.py
Source:joint_cost.py  
1#!/usr/bin/env python2# -*- coding: utf-8 -*-3"""Define the costs used on joint states / actions.4"""5from abc import ABCMeta6import numpy as np7import pyrobolearn as prl8from pyrobolearn.rewards.cost import Cost9from pyrobolearn.utils.transformation import min_angle_difference10__author__ = "Brian Delhaisse"11__copyright__ = "Copyright 2018, PyRoboLearn"12__credits__ = ["Brian Delhaisse"]13__license__ = "GNU GPLv3"14__version__ = "1.0.0"15__maintainer__ = "Brian Delhaisse"16__email__ = "briandelhaisse@gmail.com"17__status__ = "Development"18class JointCost(Cost):19    r"""(Abstract) Joint Cost."""20    __metaclass__ = ABCMeta21    def __init__(self, update_state=False):22        """23        Initialize the abstract joint cost.24        Args:25            update_state (bool): if True it will update the given states before computing the cost.26        """27        super(JointCost, self).__init__()28        self.update_state = update_state29    @staticmethod30    def _check_state(state, cls, update_state=False, **kwargs):31        """32        Check that the given state is an instance of the given class. If not, check if it can be constructed.33        Args:34            state (Robot, State, list/tuple[State]): the state or robot instance that we have to check.35            cls (State class): the state class that the state should belong to.36            update_state (bool): if the state should be updated or not by default.37            **kwargs (dict): dictionary of arguments passed to the `cls` class  if the state is a `Robot` instance.38        Returns:39            State: an instance of the specified class `cls`.40            bool: if the state should be updated or not.41        """42        # check given state43        if isinstance(state, prl.robots.Robot):  # if robot, instantiate state class with robot as param.44            state = cls(robot=state, **kwargs)45            update_state = True46        if not isinstance(state, cls):  # if not an instance of the given state class, look for it (the first instance)47            if isinstance(state, prl.states.State):48                state = state.lookfor(cls)49            elif isinstance(state, (tuple, list)):50                for s in state:51                    if isinstance(s, cls):52                        state = s53                    elif isinstance(s, prl.states.State):54                        state = s.lookfor(cls)55                    if state is not None:56                        break57            else:58                raise TypeError("Expecting the given 'state' to be an instance of `Robot`, `{}`, `State` or a list of "59                                "`State`, but instead got: {}".format(cls.__name__, type(state)))60            if state is None:61                raise ValueError("Couldn't find the specified state class `{}` in the given "62                                 "state.".format(cls.__name__))63        return state, update_state64    @staticmethod65    def _check_target_state(state, target_state, cls, update_state=False, **kwargs):66        """67        Check that the given target state is an instance of the given target state class. If not, check if it can be68        constructed from it.69        Args:70            state (Robot, State, list/tuple[State]): the state associated to the given target state. This is used if71                the target state is an int, float, or np.ndarray.72            target_state (None, int, float, np.array, Robot, State, list/tuple[State]): the target state or robot73                instance that we have to check.74            cls (State class): the state class that the state should belong to.75            update_state (bool): if the state should be updated or not by default.76            **kwargs (dict): dictionary of arguments passed to the `cls` class  if the target state is a `Robot`77                instance.78        Returns:79            State: an instance of the specified class `cls`.80            bool: if the state should be updated or not.81        """82        # check given target state83        if target_state is None:  # if the target is None, initialize it zero84            target_state = np.zeros(state.total_size())85        if isinstance(target_state, (int, float, np.ndarray)):  # if target is a np.array/float/int, create FixedState86            # TODO: check shape87            target_state = prl.states.FixedState(value=target_state)88            update_state = True89        elif isinstance(target_state, prl.robots.Robot):  # if robot, instantiate state class with robot as param.90            target_state = cls(robot=target_state, **kwargs)91            update_state = True92        elif not isinstance(target_state, cls):  # if not an instance of the given state class, look for it93            if isinstance(target_state, prl.states.State):94                target_state = target_state.lookfor(cls)95            elif isinstance(target_state, (tuple, list)):96                for s in target_state:97                    if isinstance(s, cls):98                        target_state = s99                    elif isinstance(s, prl.states.State):100                        target_state = s.lookfor(cls)101                    if target_state is not None:102                        break103            else:104                raise TypeError("Expecting the given 'target_state' to be None, a np.array, an instance of `Robot`, "105                                "`{}`, `State`, or a list of `State`, but instead got: "106                                "{}".format(cls.__name__, type(target_state)))107            if target_state is None:108                raise ValueError("Couldn't find the specified target state class `{}` in the given "109                                 "target_state.".format(cls.__name__))110        return target_state, update_state111class JointAngleDifferenceCost(JointCost):112    r"""Joint Angle Difference Cost113    Return the cost such that measures the L2 norm between the current joint positions and the target joint positions:114    .. math:: ||d(q_{target},q)||^2,115    where :math:`d(\cdot, \cdot) \in [-\pi, \pi]` is the minimum distance between two angles as described in [1,2].116    References:117        - [1] OpenAI Gym118        - [2] "Robust Recovery Controller for a Quadrupedal Robot using Deep Reinforcement Learning", Lee et al., 2019119    """120    def __init__(self, state, target_state, joint_ids=None, update_state=False):121        r"""122        Initialize the joint position cost.123        Args:124            state (JointPositionState, Robot): joint position state, or robot instance.125            target_state (JointPositionState, np.array[float[N]], None): target joint position state. If None, it will126                be set to 0.127            joint_ids (None, int, list[int]): joint ids. This used if `state` is a `Robot` instance.128            update_state (bool): if True, it will update the given states before computing the cost.129        """130        super(JointAngleDifferenceCost, self).__init__(update_state)131        # check given joint position state132        self.q, self.update_state = self._check_state(state, prl.states.JointPositionState,133                                                      update_state=self.update_state, joint_ids=joint_ids)134        # check target joint position state135        self.q_target, self.update_target_state = self._check_target_state(self.q, target_state,136                                                                           prl.states.JointPositionState,137                                                                           self.update_state)138        if self.q.total_size() != self.q_target.total_size():139            raise ValueError("The given state and target_state do not have the same size: "140                             "{} != {}".format(self.q.total_size(), self.q_target.total_size()))141    def _compute(self):142        """Compute and return the cost value."""143        if self.update_state:144            self.q()145        if self.update_target_state:146            self.q_target()147        return - np.sum(min_angle_difference(self.q.data[0], self.q_target.data[0])**2)148class JointPositionCost(JointCost):149    r"""Joint Position Cost150    Return the cost such that measures the L2 norm between the current joint positions and the target joint positions:151    .. math:: ||q_{target} - q||^2`.152    """153    def __init__(self, state, target_state, joint_ids=None, update_state=False):154        r"""155        Initialize the joint position cost.156        Args:157            state (JointPositionState, Robot): joint position state, or robot instance.158            target_state (JointPositionState, np.array[float[N]], None): target joint position state. If None, it will159                be set to 0.160            joint_ids (None, int, list[int]): joint ids. This used if `state` is a `Robot` instance.161            update_state (bool): if True, it will update the given states before computing the cost.162        """163        super(JointPositionCost, self).__init__(update_state)164        # check given joint position state165        self.q, self.update_state = self._check_state(state, prl.states.JointPositionState,166                                                      update_state=self.update_state, joint_ids=joint_ids)167        # check target joint position state168        self.q_target, self.update_target_state = self._check_target_state(self.q, target_state,169                                                                           prl.states.JointPositionState,170                                                                           self.update_state)171        if self.q.total_size() != self.q_target.total_size():172            raise ValueError("The given state and target_state do not have the same size: "173                             "{} != {}".format(self.q.total_size(), self.q_target.total_size()))174    def _compute(self):175        """Compute and return the cost value."""176        if self.update_state:177            self.q()178        if self.update_target_state:179            self.q_target()180        return - np.sum(min_angle_difference(self.q.data[0], self.q_target.data[0])**2)181class JointVelocityCost(JointCost):182    r"""Joint Velocity Cost183    Return the cost due to the joint velocities given by:184    .. math:: c = || \dot{q}_{target} - \dot{q} ||^2185    where :math:`\dot{q}_{target}` can be set to zero if wished.186    """187    def __init__(self, state, target_state=None, joint_ids=None, update_state=False):188        """189        Initialize the joint velocity cost.190        Args:191            state (JointVelocityState, Robot): joint velocity state, or robot instance.192            target_state (JointVelocityState, np.array[float[N]], Robot, None): target joint velocity state. If None,193                it will be set to 0.194            joint_ids (None, int, list[int]): joint ids. This used if `state` is a `Robot` instance.195            update_state (bool): if True, it will update the given states before computing the cost.196        """197        super(JointVelocityCost, self).__init__(update_state)198        # check given joint velocity state199        self.dq, self.update_state = self._check_state(state, prl.states.JointVelocityState,200                                                       update_state=self.update_state, joint_ids=joint_ids)201        # check target joint velocity state202        self.dq_target, self.update_target_state = self._check_target_state(self.dq, target_state,203                                                                            prl.states.JointVelocityState,204                                                                            self.update_state)205    def _compute(self):206        """Compute and return the cost value."""207        if self.update_state:208            self.dq()209        if self.update_target_state:210            self.dq_target()211        return - np.sum((self.dq_target.data[0] - self.dq.data[0])**2)212class JointAccelerationCost(JointCost):213    r"""Joint Acceleration Cost214    Return the joint acceleration cost defined as:215    .. math:: c = || \ddot{q}_{target} - \ddot{q} ||^2216    where :math:`\ddot{q}_{target}` can be set to zero if wished.217    """218    def __init__(self, state, target_state=None, joint_ids=None, update_state=False):219        """220        Initialize the joint acceleration cost.221        Args:222            state (JointAccelerationState, Robot): joint acceleration state.223            target_state (JointAccelerationState, np.array[float[N]], Robot, None): target joint acceleration state.224                If None, it will be set to 0.225            joint_ids (None, int, list[int]): joint ids. This used if `state` is a `Robot` instance.226            update_state (bool): if True, it will update the given states before computing the cost.227        """228        super(JointAccelerationCost, self).__init__(update_state=update_state)229        # check given joint acceleration state230        self.ddq, self.update_state = self._check_state(state, prl.states.JointAccelerationState,231                                                        update_state=self.update_state, joint_ids=joint_ids)232        # check target joint acceleration state233        self.ddq_target, self.update_target_state = self._check_target_state(self.ddq, target_state,234                                                                             prl.states.JointAccelerationState,235                                                                             self.update_state)236    def _compute(self):237        """Compute and return the cost value."""238        if self.update_state:239            self.ddq()240        if self.update_target_state:241            self.ddq_target()242        return - np.sum((self.ddq_target.data[0] - self.ddq.data[0])**2)243class JointTorqueCost(JointCost):244    r"""Torque Cost245    Return the cost due to the joint torques given by:246    .. math:: c = || \tau_{target} - \tau ||^2247    where :math:`\tau_{target}` can be set to zero if wished.248    """249    def __init__(self, state, target_state=None, joint_ids=None, update_state=False):250        """251        Initialize the joint torque cost.252        Args:253            state (JointForceTorqueState, Robot): joint torque state.254            target_state (JointForceTorqueState, np.array[float[N]], Robot, None): target joint torque state. If None,255                it will be set to 0.256            joint_ids (None, int, list[int]): joint ids. This used if `state` is a `Robot` instance.257            update_state (bool): if True, it will update the given states before computing the cost.258        """259        super(JointTorqueCost, self).__init__(update_state)260        # check given joint torque state261        self.tau, self.update_state = self._check_state(state, prl.states.JointForceTorqueState,262                                                        update_state=self.update_state, joint_ids=joint_ids)263        # check target joint torque state264        self.tau_target, self.update_target_state = self._check_target_state(self.tau, target_state,265                                                                             prl.states.JointForceTorqueState,266                                                                             self.update_state)267    def _compute(self):268        """Compute and return the cost value."""269        if self.update_state:270            self.tau()271        if self.update_target_state:272            self.tau_target()273        return - np.sum((self.tau_target.data[0] - self.tau.data[0])**2)274class JointPowerCost(JointCost):275    r"""Joint Power Cost276    Return the joint power cost given by:277    .. math:: c = ||\tau \cdot \dot{q}||^2278    where :math:`\tau \in \mathcal{R}^N` are the torques, and :math:`\dot{q} \in \mathcal{R}^N` are the joint279    velocities.280    """281    def __init__(self, state, joint_ids=None, update_state=False):282        """283        Initialize the Joint Power Consumption cost.284        Args:285            state (Robot, State): robot instance, or the state. The state must contains the `JointForceTorqueState`286                and the `JointVelocityState`. Note that if they are multiple torque or velocity states, it will look287                for the first instance.288            joint_ids (None, int, list[int]): joint ids. This used if `state` is a `Robot` instance.289            update_state (bool): if True, it will update the given states before computing the cost.290        """291        super(JointPowerCost, self).__init__(update_state)292        # check given joint torque and velocity state293        self.tau, self.update_torque_state = self._check_state(state, prl.states.JointForceTorqueState,294                                                               update_state=self.update_state, joint_ids=joint_ids)295        self.vel, self.update_velocity_state = self._check_state(state, prl.states.JointVelocityState,296                                                                 update_state=self.update_state, joint_ids=joint_ids)297    def _compute(self):298        """Compute and return the cost value."""299        if self.update_torque_state:300            self.tau()301        if self.update_velocity_state:302            self.vel()303        return - np.sum((self.tau.data[0] * self.vel.data[0])**2)304class JointPowerConsumptionCost(JointCost):305    r"""Joint Power Consumption Cost306    Return the joint power consumption cost given by [1]:307    .. math:: c = \sum_i^N max(\tau_i \dot{q}_i, 0)308    where :math:`\tau \in \mathcal{R}^N` are the torques, and :math:`\dot{q} \in \mathcal{R}^N` are the joint309    velocities.310    References:311        - [1] "Robust Recovery Controller for a Quadrupedal Robot using Deep Reinforcement Learning", Lee et al., 2019312    """313    def __init__(self, state, joint_ids=None, update_state=False):314        """315        Initialize the Joint Power Consumption cost.316        Args:317            state (Robot, State): robot instance, or the state. The state must contains the `JointForceTorqueState`318                and the `JointVelocityState`. Note that if they are multiple torque or velocity states, it will look319                for the first instance.320            joint_ids (None, int, list[int]): joint ids. This used if `state` is a `Robot` instance.321            update_state (bool): if True, it will update the given states before computing the cost.322        """323        super(JointPowerConsumptionCost, self).__init__(update_state)324        # check given joint torque and velocity state325        self.tau, self.update_torque_state = self._check_state(state, prl.states.JointForceTorqueState,326                                                               update_state=self.update_state, joint_ids=joint_ids)327        self.vel, self.update_velocity_state = self._check_state(state, prl.states.JointVelocityState,328                                                                 update_state=self.update_state, joint_ids=joint_ids)329    def _compute(self):330        """Compute and return the cost value."""331        if self.update_torque_state:332            self.tau()333        if self.update_velocity_state:334            self.vel()335        return - np.sum(np.maximum(self.tau.data[0] * self.vel.data[0], 0))336class JointSpeedLimitCost(JointCost):337    r"""Joint Speed Limit Cost338    Return the joint speed cost as computed in [1].339    .. math:: c = || \max(\dot{q}_{max} - |\dot{q}|, 0) ||^2340    where :math:``341    References:342        - [1] "Robust Recovery Controller for a Quadrupedal Robot using Deep Reinforcement Learning", Lee et al., 2019343    """344    def __init__(self, state, max_joint_speed=None, joint_ids=None, update_state=False):345        """346        Initialize the joint speed state.347        Args:348            state (JointVelocityState, Robot): joint velocity state, or robot instance.349            max_joint_speed (int, float, np.array[float[N]], None):350            joint_ids (None, int, list[int]): joint ids. This used if `state` is a `Robot` instance.351            update_state (bool): if True, it will update the given states before computing the cost.352        """353        super(JointSpeedLimitCost, self).__init__(update_state)354        self.dq = state355        self.dq_max = max_joint_speed356        if max_joint_speed is None:357            self.dq_max = state.max358    def _compute(self):359        """Compute and return the cost value."""360        return - np.sum(np.maximum(self.dq_max - np.abs(self.dq.data[0]), 0)**2)361class JointEnergyCost(JointCost):362    r"""Joint Energy Cost363    Return the joint energy cost given by:364    .. math:: c = | \tau \cdot \dot{q}| * dt365    where :math:`\tau \in \mathcal{R}^N` are the torques, :math:`\dot{q} \in \mathcal{R}^N` are the joint velocities,366    and :math:`dt` is the simulation time step.367    """368    def __init__(self, state, dt, joint_ids=None, update_state=False):369        """370        Initialize the joint energy cost.371        Args:372            state (Robot, State): robot instance, or the state. The state must contains the `JointForceTorqueState`373                and the `JointVelocityState`. Note that if they are multiple torque or velocity states, it will look374                for the first instance.375            dt (float): simulation time.376            joint_ids (None, int, list[int]): joint ids. This used if `state` is a `Robot` instance.377            update_state (bool): if True, it will update the given states before computing the cost.378        """379        super(JointEnergyCost, self).__init__(update_state)380        # check given joint torque and velocity state381        self.tau, self.update_torque_state = self._check_state(state, prl.states.JointForceTorqueState,382                                                               update_state=self.update_state, joint_ids=joint_ids)383        self.vel, self.update_velocity_state = self._check_state(state, prl.states.JointVelocityState,384                                                                 update_state=self.update_state, joint_ids=joint_ids)385        self.dt = dt386    def _compute(self):387        """Compute and return the cost value."""388        if self.update_torque_state:389            self.tau()390        if self.update_velocity_state:391            self.vel()...tasks.py
Source:tasks.py  
...17class IngestException(Exception):18    """Ingest class exception."""19def ingest_check_tarfile(job_id, filepath):20    """Check the ingest tarfile and return state or set it properly."""21    update_state(job_id, 'OK', 'open tar', 0)22    tar = open_tar(filepath)23    if tar is None:24        update_state(job_id, 'FAILED', 'open tar',25                     0, 'Failed to open tarfile.')26        raise IngestException()27    update_state(job_id, 'OK', 'open tar', 100)28    return tar29def move_metadata_parser(job_id, metafile):30    """Ingest the metadata and set the state appropriately."""31    update_state(job_id, 'OK', 'load metadata', 0)32    meta = MetaParser()33    meta.read_meta(metafile, job_id)34    update_state(job_id, 'OK', 'load metadata', 100)35    return meta36def ingest_metadata_parser(job_id, tar):37    """Ingest the metadata and set the state appropriately."""38    update_state(job_id, 'OK', 'load metadata', 0)39    meta = MetaParser()40    try:41        meta.load_meta(tar, job_id)42    # pylint: disable=broad-except43    except Exception as ex:44        update_state(job_id, 'FAILED', 'load metadata', 0, str(ex))45        raise IngestException()46    update_state(job_id, 'OK', 'load metadata', 100)47    return meta48def ingest_policy_check(job_id, meta_str, authed_user):49    """Ingest check to validate metadata at policy."""50    success, exception = validate_meta(meta_str, authed_user)51    if not success:52        update_state(job_id, 'FAILED', 'Policy Validation', 0, exception)53        raise IngestException()54    update_state(job_id, 'OK', 'Policy Validation', 100)55def move_files(job_id, meta_obj):56    """Move the files to the archive interface."""57    update_state(job_id, 'OK', 'move files', 0)58    try:59        patch_files(meta_obj)60    # pylint: disable=broad-except61    except Exception as ex:62        # rollback files63        stack_dump = traceback.format_exc()64        update_state(job_id, 'FAILED', 'move files', 0,65                     u'{}\n{}'.format(stack_dump, str(ex)))66        raise IngestException()67    update_state(job_id, 'OK', 'move files', 100)68def ingest_files(job_id, ingest_obj):69    """Ingest the files to the archive interface."""70    update_state(job_id, 'OK', 'ingest files', 0)71    try:72        ingest_obj.ingest()73    # pylint: disable=broad-except74    except Exception as ex:75        # rollback files76        stack_dump = traceback.format_exc()77        update_state(job_id, 'FAILED', 'ingest files', 0,78                     u'{}\n{}'.format(stack_dump, str(ex)))79        raise IngestException()80    update_state(job_id, 'OK', 'ingest files', 100)81def ingest_metadata(job_id, meta):82    """Ingest metadata to the metadata service."""83    update_state(job_id, 'OK', 'ingest metadata', 0)84    success, exception = meta.post_metadata()85    if not success:86        # rollback files87        update_state(job_id, 'FAILED', 'ingest metadata', 0, str(exception))88        raise IngestException()89    update_state(job_id, 'OK', 'ingest metadata', 100)90@INGEST_APP.task(ignore_result=False)91def move(job_id, filepath, authed_user):92    """Move a MD bundle into the archive."""93    try:94        meta = move_metadata_parser(job_id, filepath)95        ingest_policy_check(job_id, meta.meta_str, authed_user)96        move_files(job_id, meta)97        ingest_metadata(job_id, meta)98        os.unlink(filepath)99    except IngestException:100        return101@INGEST_APP.task(ignore_result=False)102def ingest(job_id, filepath, authed_user):103    """Ingest a tar bundle into the archive."""...keras_metrics.py
Source:keras_metrics.py  
...8class AUC(tfm.AUC):9    def __init__(self, from_logits=False, *args, **kwargs):10        super().__init__(*args, **kwargs)11        self._from_logits = from_logits12    def update_state(self, y_true, y_pred, sample_weight=None):13        if self._from_logits:14            super(AUC, self).update_state(y_true, tf.nn.sigmoid(y_pred), sample_weight)15        else:16            super(AUC, self).update_state(y_true, y_pred, sample_weight)17class BinaryAccuracy(tfm.BinaryAccuracy):18    def __init__(self, from_logits=False, *args, **kwargs):19        super().__init__(*args, **kwargs)20        self._from_logits = from_logits21    def update_state(self, y_true, y_pred, sample_weight=None):22        if self._from_logits:23            super(BinaryAccuracy, self).update_state(24                y_true, tf.nn.sigmoid(y_pred), sample_weight25            )26        else:27            super(BinaryAccuracy, self).update_state(y_true, y_pred, sample_weight)28class TruePositives(tfm.TruePositives):29    def __init__(self, from_logits=False, *args, **kwargs):30        super().__init__(*args, **kwargs)31        self._from_logits = from_logits32    def update_state(self, y_true, y_pred, sample_weight=None):33        if self._from_logits:34            super(TruePositives, self).update_state(35                y_true, tf.nn.sigmoid(y_pred), sample_weight36            )37        else:38            super(TruePositives, self).update_state(y_true, y_pred, sample_weight)39class FalsePositives(tfm.FalsePositives):40    def __init__(self, from_logits=False, *args, **kwargs):41        super().__init__(*args, **kwargs)42        self._from_logits = from_logits43    def update_state(self, y_true, y_pred, sample_weight=None):44        if self._from_logits:45            super(FalsePositives, self).update_state(46                y_true, tf.nn.sigmoid(y_pred), sample_weight47            )48        else:49            super(FalsePositives, self).update_state(y_true, y_pred, sample_weight)50class TrueNegatives(tfm.TrueNegatives):51    def __init__(self, from_logits=False, *args, **kwargs):52        super().__init__(*args, **kwargs)53        self._from_logits = from_logits54    def update_state(self, y_true, y_pred, sample_weight=None):55        if self._from_logits:56            super(TrueNegatives, self).update_state(57                y_true, tf.nn.sigmoid(y_pred), sample_weight58            )59        else:60            super(TrueNegatives, self).update_state(y_true, y_pred, sample_weight)61class FalseNegatives(tfm.FalseNegatives):62    def __init__(self, from_logits=False, *args, **kwargs):63        super().__init__(*args, **kwargs)64        self._from_logits = from_logits65    def update_state(self, y_true, y_pred, sample_weight=None):66        if self._from_logits:67            super(FalseNegatives, self).update_state(68                y_true, tf.nn.sigmoid(y_pred), sample_weight69            )70        else:71            super(FalseNegatives, self).update_state(y_true, y_pred, sample_weight)72class Precision(tfm.Precision):73    def __init__(self, from_logits=False, *args, **kwargs):74        super().__init__(*args, **kwargs)75        self._from_logits = from_logits76    def update_state(self, y_true, y_pred, sample_weight=None):77        if self._from_logits:78            super(Precision, self).update_state(79                y_true, tf.nn.sigmoid(y_pred), sample_weight80            )81        else:82            super(Precision, self).update_state(y_true, y_pred, sample_weight)83class Recall(tfm.Recall):84    def __init__(self, from_logits=False, *args, **kwargs):85        super().__init__(*args, **kwargs)86        self._from_logits = from_logits87    def update_state(self, y_true, y_pred, sample_weight=None):88        if self._from_logits:89            super(Recall, self).update_state(y_true, tf.nn.sigmoid(y_pred), sample_weight)90        else:91            super(Recall, self).update_state(y_true, y_pred, sample_weight)92class F1Score(tf.keras.metrics.Metric):93    def __init__(self, name="f1", from_logits=False, **kwargs):94        super(F1Score, self).__init__(name=name, **kwargs)95        self.precision = Precision(from_logits)96        self.recall = Recall(from_logits)97    def update_state(self, y_true, y_pred, sample_weight=None):98        self.precision.update_state(y_true, y_pred, sample_weight)99        self.recall.update_state(y_true, y_pred, sample_weight)100    def result(self):101        p = self.precision.result()102        r = self.recall.result()103        return (2 * p * r) / (p + r + tf.keras.backend.epsilon())104    def reset_states(self):105        self.precision.reset_states()...metrics.py
Source:metrics.py  
1import tensorflow as tf2from deepkt import data_util3class BinaryAccuracy(tf.keras.metrics.BinaryAccuracy):4    def update_state(self, y_true, y_pred, sample_weight=None):5        true, pred = data_util.get_target(y_true, y_pred)6        super(BinaryAccuracy, self).update_state(y_true=true,7                                                 y_pred=pred,8                                                 sample_weight=sample_weight)9class AUC(tf.keras.metrics.AUC):10    def update_state(self, y_true, y_pred, sample_weight=None):11        true, pred = data_util.get_target(y_true, y_pred)12        super(AUC, self).update_state(y_true=true,13                                                 y_pred=pred,14                                                 sample_weight=sample_weight)15class Precision(tf.keras.metrics.Precision):16    def update_state(self, y_true, y_pred, sample_weight=None):17        true, pred = data_util.get_target(y_true, y_pred)18        super(Precision, self).update_state(y_true=true,19                                            y_pred=pred,20                                            sample_weight=sample_weight)21class Recall(tf.keras.metrics.Recall):22    def update_state(self, y_true, y_pred, sample_weight=None):23        true, pred = data_util.get_target(y_true, y_pred)24        super(Recall, self).update_state(y_true=true,25                                         y_pred=pred,26                                         sample_weight=sample_weight)27class SensitivityAtSpecificity(tf.keras.metrics.SensitivityAtSpecificity):28    def update_state(self, y_true, y_pred, sample_weight=None):29        true, pred = data_util.get_target(y_true, y_pred)30        super(SensitivityAtSpecificity, self).update_state(y_true=true,31                                                           y_pred=pred,32                                                           sample_weight=sample_weight)33class SpecificityAtSensitivity(tf.keras.metrics.SpecificityAtSensitivity):34    def update_state(self, y_true, y_pred, sample_weight=None):35        true, pred = data_util.get_target(y_true, y_pred)36        super(SpecificityAtSensitivity, self).update_state(y_true=true,37                                                           y_pred=pred,38                                                           sample_weight=sample_weight)39class FalseNegatives(tf.keras.metrics.FalseNegatives):40    def update_state(self, y_true, y_pred, sample_weight=None):41        true, pred = data_util.get_target(y_true, y_pred)42        super(FalseNegatives, self).update_state(y_true=true,43                                                 y_pred=pred,44                                                 sample_weight=sample_weight)45class FalsePositives(tf.keras.metrics.FalsePositives):46    def update_state(self, y_true, y_pred, sample_weight=None):47        true, pred = data_util.get_target(y_true, y_pred)48        super(FalsePositives, self).update_state(y_true=true,49                                                 y_pred=pred,50                                                 sample_weight=sample_weight)51class TrueNegatives(tf.keras.metrics.TrueNegatives):52    def update_state(self, y_true, y_pred, sample_weight=None):53        true, pred = data_util.get_target(y_true, y_pred)54        super(TrueNegatives, self).update_state(y_true=true,55                                                y_pred=pred,56                                                sample_weight=sample_weight)57class TruePositives(tf.keras.metrics.TruePositives):58    def update_state(self, y_true, y_pred, sample_weight=None):59        true, pred = data_util.get_target(y_true, y_pred)60        super(TruePositives, self).update_state(y_true=true,61                                                y_pred=pred,...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
