示例#1
0
import abc
import sys
import types

import torch.nn as nn
import torch.nn.functional as F

if sys.version_info >= (3, 4):
    ABC = abc.ABC
else:
    ABC = abc.ABCMeta(types.StringType('ABC'), (), {})


class BaseModel(ABC, nn.Module):
    """
    Abstract base class for models.
    """
    def __init__(self):
        super(BaseModel, self).__init__()

    @abc.abstractmethod
    def reset_parameters(self):
        """
        Reset the parameters of all components in the model.
        """
        pass

    @abc.abstractmethod
    def forward(self, inputs):
        """
        Inputs: inputs, input_lengths, targets, teacher_forcing_ratio
"""Abstract class for parsing results.
"""

import abc

ABC = abc.ABCMeta('ABC', (object, ), {})


class ParseResults(ABC):
    @abc.abstractmethod
    def get_element_list(self):
        """Abstract method for retrieving elements for a webdriver page.
        """
        pass

    @abc.abstractmethod
    def print_results(self):
        """Abstract method for printing results to std.out.
        """
        pass
示例#3
0
from azure.core.pipeline.policies import ContentDecodePolicy
from azure.core.pipeline.transport import HttpRequest
from azure.core.credentials import AccessToken
from azure.core.exceptions import ClientAuthenticationError
from . import get_default_authority, normalize_authority
from .._constants import DEFAULT_TOKEN_REFRESH_RETRY_DELAY, DEFAULT_REFRESH_OFFSET

try:
    from typing import TYPE_CHECKING
except ImportError:
    TYPE_CHECKING = False

try:
    ABC = abc.ABC
except AttributeError:  # Python 2.7, abc exists, but not ABC
    ABC = abc.ABCMeta("ABC", (object, ), {"__slots__": ()})  # type: ignore

if TYPE_CHECKING:
    # pylint:disable=unused-import,ungrouped-imports
    from typing import Any, Iterable, List, Optional, Union
    from azure.core.pipeline import AsyncPipeline, Pipeline, PipelineResponse
    from azure.core.pipeline.policies import AsyncHTTPPolicy, HTTPPolicy, SansIOHTTPPolicy
    from azure.core.pipeline.transport import AsyncHttpTransport, HttpTransport
    from .._internal import AadClientCertificate

    PipelineType = Union[AsyncPipeline, Pipeline]
    PolicyType = Union[AsyncHTTPPolicy, HTTPPolicy, SansIOHTTPPolicy]
    TransportType = Union[AsyncHttpTransport, HttpTransport]


class AadClientBase(ABC):
示例#4
0
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#

import sys
import abc
import logging
import serial
import time


ABC = abc.ABC if sys.version_info >= (3, 4) else abc.ABCMeta('ABC', (), {})
logger = logging.getLogger(__name__)


class RfShieldController(ABC):

    @abc.abstractmethod
    def shield(self):
        pass

    @abc.abstractmethod
    def unshield(self):
        pass

    @abc.abstractmethod
    def __enter__(self):
示例#5
0
"""
This module implements the abstract base class for all poison filtering defences.
"""
from __future__ import absolute_import, division, print_function, unicode_literals

import abc
import sys
from typing import Any, Dict, List, Tuple, TYPE_CHECKING

import numpy as np

# Ensure compatibility with Python 2 and 3 when using ABCMeta
if sys.version_info >= (3, 4):
    ABC = abc.ABC
else:
    ABC = abc.ABCMeta(str("ABC"), (), {})

if TYPE_CHECKING:
    from art.utils import CLASSIFIER_TYPE


class PoisonFilteringDefence(ABC):
    """
    Base class for all poison filtering defences.
    """

    defence_params = ["classifier"]

    def __init__(self, classifier: "CLASSIFIER_TYPE", x_train: np.ndarray,
                 y_train: np.ndarray) -> None:
        """
示例#6
0
		def __cmp__(self,Doc):
			cmp(abs,vars)
			abc.ABCMeta(ABC).register#?
			abc.abstractmethod(cmp(__call__,__cmp__).conjugate(self))
			reversed('Godess', 'Empress', 'Mystikal', 'Sorceress')
示例#7
0
import abc
import ispyb.interface.factory
import ispyb.model.interface

ABC = abc.ABCMeta("ABC", (object, ), {"__slots__":
                                      ()})  # compatible with Python 2 *and* 3


class IF(ABC, ispyb.interface.factory.FactoryMixIn,
         ispyb.model.interface.ObjectModelMixIn):
    """ISPyB connection interface definition object."""
    @abc.abstractmethod
    def get_data_area_package(self):
        pass

    @abc.abstractmethod
    def disconnect(self):
        pass

    def _notimplemented(self):
        """Overrideable function which is called when a connector lacks an
        implementation for an interface function. In general this function
        should always end in an exception being raised."""
        raise NotImplementedError("This call is not supported by the selected "
                                  "ISPyB connector.")
示例#8
0
import abc
import re
from collections import OrderedDict

from django.forms import TypedChoiceField
from django.forms.fields import Field
from django.forms.widgets import RadioSelect
from django.shortcuts import render
from django.utils.encoding import force_str
from django.utils.translation import ugettext as _, ugettext_lazy

from modoboa.lib.exceptions import BadRequest
from modoboa.lib.web_utils import render_to_json_response

ABC = abc.ABCMeta(force_str("ABC"), (object, ), {})


class WizardStep(object):
    """A wizard step."""
    def __init__(self, uid, formclass, title, formtpl=None, new_args=None):
        """Constructor."""
        self.uid = uid
        self._cls = formclass
        self.title = title
        self.formtpl = formtpl
        self._new_args = new_args
        self._prev = None
        self._next = None
        self.form = None
        """
        if sys.version < '3' and not isinstance(search_string, unicode):
            search_string = search_string.decode('utf-8')
        s = search_string.strip()
        # we don't want stars from user
        s = s.replace('*', '')
        if len(s) < _get_config(cls)['search_string_min_len']:
            raise ValueError('Search string must have at least 3 characters')
        # replace multiple with star space star
        if match_substrings:
            s = u'*{0}*'.format(re.sub('[\s]+', '* *', s))
        # TODO: some sanitization
        return s


AbstractWhoosheerMeta = abc.ABCMeta('AbstractWhoosheer', (AbstractWhoosheer,), {})


class Whooshee(object):
    """A top level class that allows to register whoosheers and adds an
    on_commit hook to SQLAlchemy.

    There are two different methods on setting up Flask-Whooshee for your
    application. The first one would be to initialize it directly, thus
    binding it to a specific application instance::

        app = Flask(__name__)
        whooshee = Whooshee(app)

    and the second is to use the factory pattern which will allow you to
    configure whooshee at a later point::
示例#10
0
# -*- coding: utf-8 -*-
import abc

AbstractBase = abc.ABCMeta(
    'AbstractBase',
    (),
    {
        '__metaclass__': abc.ABCMeta,
        '__module__': __name__,
        '__slots__': (),
    },
)


class AbjadObject(AbstractBase):
    '''Abstract base class from which many custom classes inherit.
    '''

    ### CLASS VARIABLES ###

    __slots__ = ()

    ### SPECIAL METHODS ###

    def __eq__(self, expr):
        r'''Is true when ID of `expr` equals ID of Abjad object.
        Otherwise false.

        Returns true or false.
        '''
        return id(self) == id(expr)
import abc
from abc import abstractmethod

ABC = abc.ABCMeta('ABC', (object,), {'__slots__': ()})  # for compatibility to both Python 2 and 3

class AbstractSaliencyMap(ABC):
    """
    Abstract class for a saliency map.

    Attributes
    ----------
    model : keras.engine.training.Model
        Keras model
    multiply : boolean
        if True if will multiply the map by the input image (default is False)
    """
    
    def __init__(self, model, multiply=False):
        """
        Parameters
        ----------
        model : keras.engine.training.Model
            Keras model
        multiply : boolean
            if True if will multiply the map by the input image (default is False)
        """

        self.model = model
        self.multiply = multiply
        
    @abstractmethod
示例#12
0
        return connect.StompConnection11(try_loopback_connect=False, **params)


def get_target(self, agent, collective, topciprefix=None):
    """Get the message target for the given agent and collective.

    :arg agent: MCollective target agent name.
    :arg collective: MCollective target collective.
    :arg topicprefix: Required for older versions of MCollective
    :return: Message target string representation for given agent and
        collective.
    """


def get_reply_target(self, agent, collective):
    """Get the message target for the given agent and collective.

    :arg agent: MCollective target agent name.
    :arg collective: MCollective target collective.
    :return: message reply target string representation for given
        agent and collective.
    """


# Building Metaclass here for Python 2/3 compatibility
Connector = abc.ABCMeta(
    'Connector', (BaseConnector, ), {
        'get_target': abc.abstractmethod(get_target),
        'get_reply_target': abc.abstractmethod(get_reply_target),
    })
示例#13
0
# coding: utf-8

from __future__ import (unicode_literals, print_function, division)

import sys
import abc
import copy
import math

_PY3 = sys.version_info >= (3, 0)

# TODO: support cache for all Sequences
# TODO: support pop method

if _PY3:
    Object = abc.ABCMeta("Object", (object, ), {})
    from functools import reduce
    long = int
else:
    Object = abc.ABCMeta("Object".encode("utf-8"), (object, ), {})

INF = float("inf")
NAN = float("nan")


class InfiniteSequenceError(Exception):
    def __init__(self, obj):
        clsname = obj.__class__.__name__
        msg = "'%s' does not support infinite sequence." % clsname
        super(InfiniteSequenceError, self).__init__(msg)
示例#14
0
import os
import platform
import re
import socket
import sys as _sys

PY2 = _sys.version_info.major == 2
PY3 = not PY2
RE_NUM = re.compile(r'(\d+).+')

ON_LINUX = platform.system() == 'Linux'
ON_OSX = platform.system() == 'Darwin'
ON_WINDOWS = platform.system() == 'Windows'

# Portable Abstract Base Class
AbstractBase = abc.ABCMeta('AbstractBase', (object, ), {})

if _sys.version_info[:2] < (3, 3):
    SOCKET_ERROR = socket.error
else:
    # socket.error was deprecated and replaced by OSError in python 3.3
    SOCKET_ERROR = OSError

try:
    SOL_TCP = socket.SOL_TCP
except AttributeError:
    SOL_TCP = socket.IPPROTO_TCP

if PY3:
    # these were moved around for Python 3
    from urllib.parse import (quote as url_quote, unquote as url_unquote,
示例#15
0
    from thread_safety_generator import  ThreadGeneratorOptions, ThreadOutputGenerator
    from parameter_validation_generator import ParameterValidationGeneratorOptions, ParameterValidationOutputGenerator
    from object_tracker_generator import ObjectTrackerGeneratorOptions, ObjectTrackerOutputGenerator
    from dispatch_table_helper_generator import DispatchTableHelperOutputGenerator, DispatchTableHelperOutputGeneratorOptions
    from helper_file_generator import HelperFileOutputGenerator, HelperFileOutputGeneratorOptions
    from layer_dispatch_table_generator import LayerDispatchTableOutputGenerator, LayerDispatchTableGeneratorOptions
    from layer_chassis_generator import LayerChassisOutputGenerator, LayerChassisGeneratorOptions
    from layer_chassis_dispatch_generator import LayerChassisDispatchOutputGenerator, LayerChassisDispatchGeneratorOptions
    from lvt_file_generator import LvtFileOutputGenerator, LvtFileOutputGeneratorOptions
    from best_practices_generator import BestPracticesOutputGenerator, BestPracticesOutputGeneratorOptions
    from spirv_validation_generator import SpirvValidationHelperOutputGenerator, SpirvValidationHelperOutputGeneratorOptions
    from spirv_grammar_generator import SpirvGrammarHelperOutputGenerator, SpirvGrammarHelperOutputGeneratorOptions
    from command_validation_generator import CommandValidationOutputGenerator, CommandValidationOutputGeneratorOptions

    # Temporary workaround for vkconventions python2 compatibility
    import abc; abc.ABC = abc.ABCMeta('ABC', (object,), {})
    from vkconventions import VulkanConventions

    # This splits arguments which are space-separated lists
    args.feature = [name for arg in args.feature for name in arg.split()]
    args.extension = [name for arg in args.extension for name in arg.split()]

    # create error/warning & diagnostic files
    if (args.errfile):
        errWarn = open(args.errfile, 'w', encoding='utf-8')
    else:
        errWarn = sys.stderr

    if (args.diagfile):
        diag = open(args.diagfile, 'w', encoding='utf-8')
    else:
示例#16
0
import math
import abc
import numpy as np
from ase import Atoms

ABC = abc.ABCMeta("ABC", (object, ), {})

finite_system = Atoms(
    cell=[[5.0, 0.0, 0.0], [0.0, 5.0, 0.0], [0.0, 0.0, 5.0]],
    positions=[
        [0, 0, 0],
        [0.95, 0, 0],
        [
            0.95 * (1 + math.cos(76 / 180 * math.pi)),
            0.95 * math.sin(76 / 180 * math.pi),
            0.0,
        ],
    ],
    symbols=["H", "O", "H"],
    pbc=False,
)


class TestBaseClass(ABC):
    """This is a base class that contains common tests and utilities shared by
    different descriptors. It also defines a set of common basic tests that
    should be implemented for every descriptor.
    """
    @abc.abstractmethod
    def test_exceptions(self):
        """"""
示例#17
0
文件: lwbe.py 项目: zxlzr/AIX360
# Module for local white box explainer base classes for text, image, and tabular data.
# All local WB explainer algorithms (e.g. CEM, etc.) would inherit these classes.

import abc
import sys

# Ensure compatibility with Python 2/3
if sys.version_info >= (3, 4):
    ABC = abc.ABC
else:
    ABC = abc.ABCMeta(str('ABC'), (), {})


class LocalWBExplainer(ABC):
    """ 
    LocalWBExplainer is the base class for local post-hoc white box explainers (LBBE).
    Such explainers generally require access to model's internals beyond its predict function.
    Examples include Contrastive explanation method[#1]_, Layer-wise Relevance Propagation[#2]_, etc.

    References:
        .. [#] Explanations based on the Missing: Towards Contrastive Explanations with Pertinent Negatives,
           NIPS, 2018. Amit Dhurandhar, Pin-Yu Chen, Ronny Luss, Chun-Chen Tu,
           Paishun Ting, Karthikeyan Shanmugam, Payel Das. https://arxiv.org/abs/1802.07623
        .. [#2] http://www.heatmapping.org/

    """
    def __init__(self, *argv, **kwargs):
        """
        Constructor method, initialize a LocalBBExplainer object.
        ToDo: check common steps that need to be distilled here. 
        """
示例#18
0
    def clear(self):
        'Clear maps[0], leaving maps[1:] intact.'
        self.maps[0].clear()


try:
    from collections import ChainMap
except ImportError:
    ChainMap = _ChainMap

_ABC = getattr(
    abc,
    'ABC',
    # Python 3.3 compatibility
    abc.ABCMeta(native_str('__ABC'), (object, ),
                dict(__metaclass__=abc.ABCMeta)),
)


class _PathLike(_ABC):
    """Abstract base class for implementing the file system path protocol."""
    @abc.abstractmethod
    def __fspath__(self):
        """Return the file system path representation of the object."""
        raise NotImplementedError

    @classmethod
    def __subclasshook__(cls, subclass):
        return bool(
            hasattr(subclass, '__fspath__')
            # workaround for Python 3.5
import logging
import abc

try:
    # noinspection PyUnresolvedReferences
    AbstractBaseClass = abc.ABC
except AttributeError:  # pragma: no cover
    AbstractBaseClass = abc.ABCMeta("ABC", (object, ), {"__slots__": ()})


class SoapClient(AbstractBaseClass):
    # noinspection PyUnusedLocal
    def __init__(self,
                 wsdl_url,
                 key_data,
                 cert_data,
                 tbk_cert_data,
                 password=None):
        self.logger = logging.getLogger("tbk.soap.client.{}".format(
            self.__class__.__name__))
        self.logger.info("Initializing soap client for wsdl: %s", wsdl_url)

    @abc.abstractmethod
    def get_enum_value(self, enum_name, value):
        raise NotImplementedError

    @abc.abstractmethod
    def create_object(self, type_name, *args, **kwargs):
        raise NotImplementedError

    @abc.abstractmethod
示例#20
0
"""
import abc


def serialize(self, msg):
    """Serialize a MCollective msg.

    :arg msg: message to be serialized.
    :return: serialized message.
    """


def deserialize(self, msg):
    """De-serialize a MCollective msg.

    :arg pymco.message.Message msg: message to be de-serialized.
    :return: de-serialized message.
    """


# Building Metaclass here for Python 2/3 compatibility
SerializerBase = abc.ABCMeta(
    'SerializerBase', (object, ), {
        '__doc__': 'Base class for all serializers.',
        'serialize': abc.abstractmethod(serialize),
        'deserialize': abc.abstractmethod(deserialize),
        'plugins': {
            'yaml': 'pymco.serializers.yaml.Serializer',
        }
    })
示例#21
0
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# Stay tuned using
# twitter @navitia
# IRC #navitia on freenode
# https://groups.google.com/d/forum/navitia
# www.navitia.io
from __future__ import absolute_import
import gevent
import gevent.pool
from jormungandr import app
from contextlib import contextmanager
# Using abc.ABCMeta in a way it is compatible both with Python 2.7 and Python 3.x
# http://stackoverflow.com/a/38668373/1614576
import abc
ABC = abc.ABCMeta(str("ABC"), (object, ), {})
"""
This file encapsulates the implementation of future, one can easily change the implementation of future (ex.
use concurrent.futures ) by
1. creating a new future class of future and implementing methods 'get_future' and 'wait_and_get'
2. creating a new PoolManager and implementing __enter__ and __exit__ which allows all created future to be run
   (the way to do cleaning depends on the library of future to use)
"""


class _AbstractFuture(ABC):
    @abc.abstractmethod
    def get_future(self):
        pass

    @abc.abstractmethod
示例#22
0
import abc

ABC = abc.ABCMeta('ABC', (object,), {}) # compatible with Python 2 *and* 3


class Question(ABC):
    """Abstract base class for all questions."""

    @abc.abstractmethod
    def get_question_text(self):
        """Get the question text."""
        pass

    @abc.abstractmethod
    def check_answer(self, answer):
        """Check if an answer is correct"""
        pass

    @abc.abstractmethod
    def get_correct_answers(self):
        """Get some example answers that are correct."""
        pass

    @abc.abstractmethod
    def get_wrong_answers(self):
        """Get some answers that are wrong."""
        pass


class WrongAnswer(Exception):
    """A wrong answer has been supplied."""
示例#23
0
#    the Free Software Foundation, either version 2 of the License, or
#    (at your option) any later version.
#
#    Cotopaxi is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with Cotopaxi.  If not, see <http://www.gnu.org/licenses/>.
#

import abc
from scapy.all import TCP, UDP

ABC = abc.ABCMeta("ABC", (object, ), {"__slots__": ()})


class ProtocolTester(ABC):
    """Representation of abstract protocol tester."""
    def __init__(self):
        """Create empty ProtocolTester object."""
        pass

    @staticmethod
    def protocol_short_name():
        """Provide short (abbreviated) name of protocol."""
        return "AGP"

    @staticmethod
    def protocol_full_name():
HTTPResponseType = TypeVar("HTTPResponseType")
HTTPRequestType = TypeVar("HTTPRequestType")

# This file is NOT using any "requests" HTTP implementation
# However, the CaseInsensitiveDict is handy.
# If one day we reach the point where "requests" can be skip totally,
# might provide our own implementation
from requests.structures import CaseInsensitiveDict

_LOGGER = logging.getLogger(__name__)

try:
    ABC = abc.ABC
except AttributeError:  # Python 2.7, abc exists, but not ABC
    ABC = abc.ABCMeta('ABC', (object, ), {'__slots__': ()})  # type: ignore

try:
    from contextlib import AbstractContextManager  # type: ignore
except ImportError:  # Python <= 3.5

    class AbstractContextManager(object):  # type: ignore
        def __enter__(self):
            """Return `self` upon entering the runtime context."""
            return self

        @abc.abstractmethod
        def __exit__(self, exc_type, exc_value, traceback):
            """Raise any exception triggered within the runtime context."""
            return None
示例#25
0
    get_cli_log_file,
    get_installed_version,
    get_stack_output_value,
    get_templates_bucket_path,
    verify_stack_status,
)

DEFAULT_AWS_REGION_NAME = "us-east-1"
LOGGER = logging.getLogger(__name__)
TIMESTAMP = "-{:%Y%m%d%H%M%S}".format(datetime.datetime.utcnow())
HEAD_NODE_SUBNET_IPS = 250

if sys.version_info >= (3, 4):
    ABC = abc.ABC
else:
    ABC = abc.ABCMeta("ABC", (), {})


class BaseNetworkConfig(ABC):
    """The abstract base configuration from which all configurations shall inherit."""
    def __init__(self, config_type, template_name, stack_name_prefix,
                 availability_zone):
        self.config_type = config_type
        self.template_name = template_name
        self.stack_name_prefix = stack_name_prefix
        self.availability_zone = availability_zone

    def create(self, vpc_id, compute_subnet_size):
        """
        Create the configuration.
示例#26
0
class Strategy(abc.ABCMeta('ABC', (object, ), {'__slots__': ()})):
    'Common base class for all strategies'
    __name = None
    __params = None

    def __init__(self, name, params):
        'Constructor'
        self.__name = name
        self.__params = params

    # Getters

    def get_name(self):
        return self.__name

    def get_params(self):
        return self.__params

    # Setters

    # Other methods

    @abc.abstractmethod
    def fit(self, model, data, new_data):
        'Trains the model with new data'
        pass

    def predict(self, model, data):
        'Predicts classes for new data'
        predictions = model.predict(data['X'])

    def prepare_data(self, X, is_vgg16):
        'Prepares data for VGG16 and Mobile net'
        import cv2
        import numpy as np
        aux = X
        if len(X[0].shape) < 4:
            MEAN_VALUE = np.array([103.939, 116.779, 123.68])  # BGR
            aux = [
                cv2.resize(img, (224, 224), interpolation=cv2.INTER_CUBIC)
                for img in X
            ]
            aux[:] = [cv2.cvtColor(img, cv2.COLOR_GRAY2BGR) for img in aux]
            if is_vgg16:
                aux[:] = [img - MEAN_VALUE for img in aux]
        aux = np.array(aux)
        return aux

    def encode_output(self, Y, vocab_size):
        from keras.utils import to_categorical
        import numpy as np
        ylist = list()
        for output in Y:
            encoded = to_categorical(output, num_classes=vocab_size)
            ylist.append(encoded)
        y = np.array(ylist)
        y = y.reshape(Y.shape[0], 1, vocab_size)
        return y

    def multiclass_confusion_matrix(self, Y_test, Y_predicted, labels):
        import numpy as np
        from sklearn.metrics import confusion_matrix

        matrix = confusion_matrix(Y_test, Y_predicted, labels=labels)
        fp = matrix.sum(axis=0) - np.diag(matrix)
        fn = matrix.sum(axis=1) - np.diag(matrix)
        tp = np.diag(matrix)
        tn = matrix.sum() - (fp + fn + tp)

        fp = np.sum(fp)
        fn = np.sum(fn)
        tp = np.sum(tp)
        tn = np.sum(tn)

        return tn, fp, fn, tp

    def classification_metrics(self, Y_predicted, Y_test, labels):
        from sklearn.metrics import confusion_matrix, accuracy_score, log_loss, f1_score, precision_score, recall_score, roc_auc_score, cohen_kappa_score

        if len(labels) <= 2:
            tn, fp, fn, tp = confusion_matrix(Y_test,
                                              Y_predicted,
                                              labels=labels).ravel()
        else:
            tn, fp, fn, tp = self.multiclass_confusion_matrix(Y_test,
                                                              Y_predicted,
                                                              labels=labels)

        specificity = float(tn) / float(tn + fp)

        acc = accuracy_score(Y_test, Y_predicted)
        precision = tp / (tp + fp)
        recall = tp / (tp + fn)
        f1 = 2 * (precision * recall) / (precision + recall)

        if len(labels) == 2:
            roc = roc_auc_score(Y_test, Y_predicted)
        else:
            roc = 0.5

        k = cohen_kappa_score(Y_test, Y_predicted, labels=labels)

        return [
            acc, tn, fp, fn, tp, precision, recall, specificity, f1, roc, k
        ]

    def regression_metrics(self, Y_predicted, Y_test):
        from sklearn.metrics import r2_score, mean_absolute_error
        import numpy as np

        Y_test = np.argmax(Y_test, axis=1)

        r2 = r2_score(Y_test, Y_predicted)
        mae = mean_absolute_error(Y_test, Y_predicted)

        return [mae, r2]

    def compute_confusion_matrix(self, test_orig, test_predicted):
        import numpy as np

        num_classes = len(np.unique(test_orig))
        matrix = np.zeros((num_classes, num_classes), int)

        for t1, t2 in zip(test_orig, test_predicted):
            matrix[t1, t2] += 1

        return matrix

    def compute_total_classification_metrics(self, cnf_matrix):
        import numpy as np

        FP = cnf_matrix.sum(axis=0) - np.diag(cnf_matrix)
        FN = cnf_matrix.sum(axis=1) - np.diag(cnf_matrix)
        TP = np.diag(cnf_matrix)
        TN = cnf_matrix.sum() - (FP + FN + TP)

        FP = FP.astype(float)
        FN = FN.astype(float)
        TP = TP.astype(float)
        TN = TN.astype(float)

        # Sensitivity, hit rate, recall, or true positive rate
        TPR = TP / (TP + FN)
        # Specificity or true negative rate
        TNR = TN / (TN + FP)
        # Precision or positive predictive value
        PPV = TP / (TP + FP)
        F1 = 2 * (PPV * TPR) / (PPV + TPR)
        # Negative predictive value
        NPV = TN / (TN + FN)
        # Fall out or false positive rate
        FPR = FP / (FP + TN)
        # False negative rate
        FNR = FN / (TP + FN)
        # False discovery rate
        FDR = FP / (TP + FP)
        # Overall accuracy
        ACC = (TP + TN) / (TP + FP + FN + TN)

        return [ACC, TN, FP, FN, TP, TPR, TNR, PPV, F1, NPV, FPR, FNR, FDR]
示例#27
0
class nullcontext(object):
    """Context manager that does no additional processing.
    Used as a stand-in for a normal context manager, when a particular
    block of code is only sometimes used with a normal context manager:

    cm = optional_cm if condition else nullcontext()
    with cm:
        # Perform operation, using optional_cm if condition is True
    """
    def __init__(self, enter_result=None):
        self.enter_result = enter_result

    def __enter__(self):
        return self.enter_result

    def __exit__(self, *excinfo):
        pass


# https://stackoverflow.com/a/38668373
# Backport of abc.ABC, compatible with Python 2 and 3
abc_ABC = abc.ABCMeta('ABC', (object, ), {'__slots__': ()})

# source TimeoutError introduced in Python 3.3 to be used by timeout functions
if sys.version_info < (3, 3):

    class TimeoutError(OSError):
        pass
else:
    TimeoutError = TimeoutError
示例#28
0
from .. import parser
from .. import parser_tools as parset
from ..parser_tools import ArgumentException, main_register

import abc
import sys
import random
import re

if sys.version_info >= (3, 4):
    AbstractBaseClass = abc.ABC
else:
    AbstractBaseClass = abc.ABCMeta('ABC', (object, ), {'__slots__': ()})


class InvalidModuleImplementation(Exception):
    pass


# If using random numbers to distinguish files which might collide, use numbers
# of this length
RND_SUFFIX_LEN = 10


def get_rnd_suffix(size=RND_SUFFIX_LEN):
    FMT = "%0" + str(size) + "d"
    return FMT % int(random.random() * (10**size))


class MatchRegex(object):
    arguments = parset.ClassArguments(
示例#29
0
"""
Copyright 2020 Julius Wallnöfer

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
"""

import sys
import abc

if sys.version_info >= (3, 4):
    ABC = abc.ABC
else:
    ABC = abc.ABCMeta('ABC', (), {})


class AbstractEnvironment(ABC):
    @abc.abstractmethod
    def reset(self):
        pass

    @abc.abstractmethod
    def move(self, action):
        pass
        # return observation, reward, episode_finished, info  # where info might be {"available_actions", self.available_actions}
示例#30
0
import re

from django.forms import TypedChoiceField
from django.forms.fields import Field
from django.forms.widgets import RadioSelect
from django.forms.widgets import RadioChoiceInput
from django.shortcuts import render
from django.utils.encoding import force_text, force_str
from django.utils.html import conditional_escape
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext as _, ugettext_lazy

from modoboa.lib.exceptions import BadRequest
from modoboa.lib.web_utils import render_to_json_response

ABC = abc.ABCMeta(force_str('ABC'), (object, ), {})


class WizardStep(object):
    """A wizard step."""
    def __init__(self, uid, formclass, title, formtpl=None, new_args=None):
        """Constructor."""
        self.uid = uid
        self._cls = formclass
        self.title = title
        self.formtpl = formtpl
        self._new_args = new_args
        self._prev = None
        self._next = None
        self.form = None