Пример #1
0
def distance(x: NpArrayLike,
             y: NpArrayLike,
             name: str = 'euclid',
             axes: NpAxes = 0,
             **kwds: Any) -> NpArray:
    """Calculate distance of two arrays along given axes.

    A vector distance function, also known as metric, is a function d(x, y),
    which quantifies the proximity of vectors in a vector space as non-negative
    real numbers. If the distance is zero, then the vectors are equivalent with
    respect to the distance function. Distance functions are often used as
    error, loss or risk functions, to evaluate statistical estimations.

    Args:
        x: Any sequence that can be interpreted as a numpy ndarray of arbitrary
            dimension. This includes nested lists, tuples, scalars and existing
            arrays.
        y: Any sequence that can be interpreted as a numpy ndarray with the same
            dimension, shape and datatypes as 'x'.
        name: Name of distance. Accepted values are:
            'minkowski': :term:`Minkowski distance`
                Remark: requires additional parameter 'p'
            'manhattan': :term:`Manhattan distance`
            'euclid': :term:`Euclidean distance` (default)
            'chebyshev': :term:`Chebyshev distance`
            'pmean': :term:`Power mean difference`
                Remark: requires additional parameter 'p'
            'amean': :term:`Mean absolute difference`
            'qmean': :term:`Quadratic mean difference`
        axes: Integer or tuple of integers, that identify the array axes, along
            which the function is evaluated. In a one-dimensional array the
            single axis has ID 0. In a two-dimensional array the axis with ID 0
            is running across the rows and the axis with ID 1 is running across
            the columns. For the value None, the function is evaluated with
            respect to all axes of the array. The default value is 0, which
            is an evaluation with respect to the first axis in the array.
        **kwds: Parameters of the given distance or class of distances.
            The Parameters are documented within the respective 'dist'
            functions.

    Returns:
        :class:`numpy.ndarray` of dimension dim(*x*) - len(*axes*).

    """
    # Try to cast 'x' and 'y' as arrays
    x = array.cast(x)
    y = array.cast(y)

    # Check type of 'axes'
    check.has_type("'axes'", axes, (int, tuple))

    # Check dimensions of 'x' and 'y'
    if x.shape != y.shape:
        raise ValueError("arrays 'x' and 'y' can not be broadcasted together")

    # Get function from catalog
    f = catalog.pick(Distance, name=name)

    # Evaluate function
    return call.safe_call(f, x, y, axes=axes, **kwds)
Пример #2
0
def distance(x: NpArrayLike,
             y: NpArrayLike,
             name: str = 'frobenius',
             axes: IntPair = (0, 1),
             **kwds: Any) -> NpArray:
    """Calculate matrix distances of two arrays along given axes.

    A matrix distance function, is a function d(x, y), which quantifies the
    proximity of matrices in a vector space as non-negative
    real numbers. If the distance is zero, then the matrices are equivalent with
    respect to the distance function. Distance functions are often used as
    error, loss or risk functions, to evaluate statistical estimations.

    Args:
        x: Any sequence that can be interpreted as a numpy ndarray of two or
            more dimensions. This includes nested lists, tuples, scalars and
            existing arrays.
        y: Any sequence that can be interpreted as a numpy ndarray with the same
            dimension, shape and datatypes as 'x'.
        name: Name of used matrix distance. Accepted values are:
            'frobenius': :term:`Frobenius distance` (default)
        axes: Pair (2-tuple) of integers, that identify the array axes, along
            which the function is evaluated. In a two-dimensional array the axis
            with ID 0 is running across the rows and the axis with ID 1 is
            running across the columns. The default value is (0, 1), which is an
            evaluation with respect to the first two axis in the array.
        **kwds: Parameters of the given distance or class of distances.
            The Parameters are documented within the respective 'dist'
            functions.

    Returns:
        :class:`numpy.ndarray` of dimension dim(*x*) - 2.

    """
    # Try to cast 'x' and 'y' as arrays
    x = array.cast(x)
    y = array.cast(y)

    # Check type of 'axes'
    check.has_type("'axes'", axes, tuple)

    # Check dimensions of 'x' and 'y'
    if x.shape != y.shape:
        raise ValueError("arrays 'x' and 'y' can not be broadcasted together")

    # Check value of 'axes'
    check.has_size("argument 'axes'", axes, size=2)
    if axes[0] == axes[1]:
        raise np.AxisError("first and second axis have to be different")

    # Get function from catalog
    f = catalog.pick(Distance, name=name)

    # Evaluate function
    return call.safe_call(f, x=x, y=y, axes=axes, **kwds)
Пример #3
0
    def test_pick(self) -> None:

        @catalog.category
        class P:
            name: str

        @catalog.register(P, name='p')
        def p() -> int:
            pass

        @catalog.register(P, name='q')
        def q() -> int:
            pass

        with self.subTest(path='*.p'):
            card = catalog.pick(path='*.p')
            self.assertEqual(card, p)

        with self.subTest(cat=P, name='p'):
            card = catalog.pick(P, name='p')
            self.assertEqual(card, p)
Пример #4
0
def length(x: NpArrayLike,
           norm: str = 'euclid',
           axes: NpAxes = 0,
           **kwds: Any) -> NpArray:
    r"""Calculate the length of a vector with respect to a given norm.

    Args:
        x: Any sequence that can be interpreted as a numpy ndarray of arbitrary
            dimension. This includes nested lists, tuples, scalars and existing
            arrays.
        norm: String, which identifies the used vector norm:

            :p-norm: The :term:`p-norm` requires an additional parameter *p* and
                induces the :term:`Minkowski distance`.
            :1-norm: The :term:`1-norm` induces the :term:`Manhattan distance`.
            :euclid: The :term:`Euclidean norm` is the default norm and induces
                the :term:`Euclidean distance`.
            :max: The :term:`Maximum norm` induces the
                :term:`Chebyshev distance`.
            :pmean: The :term:`Hölder mean` requires an additional parameter
                *p* and induces the :term:`power mean difference`.
            :amean: The :term:`mean absolute` induces the
                :term:`mean absolute difference`
            :qmean: The :term:`quadratic mean` induces the
                :term:`quadratic mean difference`
        axes: Integer or tuple of integers, that identify the array axes, along
            which the function is evaluated. In a one-dimensional array the
            single axis has ID 0. In a two-dimensional array the axis with ID 0
            is running across the rows and the axis with ID 1 is running across
            the columns. For the value None, the function is evaluated with
            respect to all axes of the array. The default value is 0, which
            is an evaluation with respect to the first axis in the array.
        **kwds: Additional parameters of the given norm. These norm parameters
            are documented within the respective 'norm' functions.

    Returns:
        :class:`numpy.ndarray` of dimension dim(*x*) - len(*axes*).

    """
    # Try to cast 'x' as array
    x = array.cast(x)

    # Check type of 'axes'
    check.has_type("'axes'", axes, (int, tuple))

    # Get function from catalog
    f = catalog.pick(Norm, name=norm)

    # Evaluate function
    return call.safe_call(f, x, axes=axes, **kwds)
Пример #5
0
def norm(x: NpArrayLike,
         name: str = 'frobenius',
         axes: IntPair = (0, 1),
         **kwds: Any) -> NpArray:
    """Calculate magnitude of matrix with respect to given norm.

    Args:
        x: Any sequence that can be interpreted as a numpy ndarray of two or
            more dimensions. This includes nested lists, tuples, scalars and
            existing arrays.
        name: Name of matrix norm. Accepted values are:

            :pq: :term:`pq-Norm`. Remark: requires additional parameters *p* and
                *q*
            :frobenius: The default norm is the :term:`Frobenius Norm`

        axes: Pair (2-tuple) of integers, that identify the array axes, along
            which the function is evaluated. In a two-dimensional array the axis
            with ID 0 is running across the rows and the axis with ID 1 is
            running across the columns. The default value is (0, 1), which is an
            evaluation with respect to the first two axis in the array.
        **kwds: Parameters of the given norm / class of norms.
            The norm Parameters are documented within the respective 'norm'
            functions.

    Returns:
        :class:`numpy.ndarray` of dimension dim(*x*) - 2.

    """
    # Try to cast 'x' as array
    x = array.cast(x)

    # Check type of 'axes'
    check.has_type("'axes'", axes, tuple)

    # Check dimension of 'x'
    if x.ndim < 2:
        raise ValueError("'x' is required to have dimension > 1")

    # Check value of 'axes'
    check.has_size("argument 'axes'", axes, size=2)
    if axes[0] == axes[1]:
        raise np.AxisError("first and second axis have to be different")

    # Get function from catalog
    f = catalog.pick(Norm, name=name)

    # Evaluate function
    return call.safe_call(f, x=x, axes=axes, **kwds)
Пример #6
0
def error(x: NpArrayLike,
          y: NpArrayLike,
          name: str,
          axes: NpAxes = 0,
          **kwds: Any) -> NpArray:
    """Calculate the regression error of a prediction.

    Args:
        x: Any sequence that can be interpreted as a numpy ndarray of arbitrary
            dimension. This includes nested lists, tuples, scalars and existing
            arrays.
        y: Any sequence that can be interpreted as a numpy ndarray with the same
            dimension, shape and datatypes as 'x'.
        name: Name of discrepancy function:
            'sad': :term:`Sum of Absolute Differences`
            'rss': :term:`Residual Sum of Squares`
            'mse': :term:`Mean Squared Error`
            'mae': :term:`Mean Absolute Error`
            'rmse': :term:`Root-Mean-Square Error`
        axes: Integer or tuple of integers, that identify the array axes, along
            which the function is evaluated. In a one-dimensional array the
            single axis has ID 0. In a two-dimensional array the axis with ID 0
            is running across the rows and the axis with ID 1 is running across
            the columns. For the value None, the function is evaluated with
            respect to all axes of the array. The default value is 0, which
            is an evaluation with respect to the first axis in the array.
        **kwds: Additional parameters for the given discrepancy function. The
            function specific parameters are documented within the respective
            functions.

    Returns:
        :class:`numpy.ndarray` of dimension dim(*x*) - len(*axes*).

    """
    # Try to cast 'x' and 'y' as arrays
    x = array.cast(x)
    y = array.cast(y)

    # Check shapes and dtypes of 'x' and 'y'
    if x.shape != y.shape:
        raise ValueError("arrays 'x' and 'y' can not be broadcasted together")

    # Evaluate function
    f = catalog.pick(Error, name=name)
    return call.safe_call(f, x=x, y=y, axes=axes, **kwds)
Пример #7
0
def sigmoid(x: NpArrayLike, name: str = 'logistic', **kwds: Any) -> NpArray:
    """Evaluate sigmoidal shaped function.

    Args:
        x: Any sequence that can be interpreted as a numpy ndarray of arbitrary
            dimension. This includes nested lists, tuples, scalars and existing
            arrays.
        name: Name of sigmoid function. Default: 'logistic'

    Returns:
        Numpy ndarray which contains the evaluation of the sigmoid
        function to the given data.

    """
    # Try to cast 'x' as array and get function from catalog
    x = array.cast(x)
    f = catalog.pick(Sigmoid, name=name)

    # Evaluate function
    return call.safe_call(f, x=x, **kwds)
Пример #8
0
def bell(x: NpArrayLike, name: str = 'gauss', **kwds: Any) -> NpArray:
    """Evaluate bell shaped function.

    Args:
        x: Any sequence that can be interpreted as a numpy ndarray of arbitrary
            dimension. This includes nested lists, tuples, scalars and existing
            arrays.
        name: Name of bell shaped function. By default the Gauss function is
            used.

    Returns:
        Evaluation of the bell shaped function at given data.

    """
    # Try to cast 'x' as array and get function from catalog
    x = array.cast(x)
    f = catalog.pick(Bell, name=name)

    # Evaluate function
    return call.safe_call(f, x=x, **kwds)