Python numpy.reciprocal() Examples

The following are 30 code examples of numpy.reciprocal(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module numpy , or try the search function .
Example #1
Source File: _osqp.py    From osqp-python with Apache License 2.0 7 votes vote down vote up
def update_rho(self, rho_new):
        """
        Update set-size parameter rho
        """
        if rho_new <= 0:
            raise ValueError("rho must be positive")

        # Update rho
        self.work.settings.rho = np.minimum(np.maximum(rho_new,
                                            RHO_MIN), RHO_MAX)

        # Update rho_vec and rho_inv_vec
        ineq_ind = np.where(self.work.constr_type == 0)
        eq_ind = np.where(self.work.constr_type == 1)
        self.work.rho_vec[ineq_ind] = self.work.settings.rho
        self.work.rho_vec[eq_ind] = RHO_EQ_OVER_RHO_INEQ * self.work.settings.rho
        self.work.rho_inv_vec = np.reciprocal(self.work.rho_vec)

        # Factorize KKT
        self.work.linsys_solver = linsys_solver(self.work) 
Example #2
Source File: batch_normalization.py    From chainer with MIT License 6 votes vote down vote up
def forward(self, inputs):
        self.retain_inputs((0, 1, 2, 4))
        x, gamma, mean, var, gy = inputs
        expander = self.expander
        xp = backend.get_array_module(x)

        if self.inv_std is None or self.inv_var is None:
            self.inv_var = xp.reciprocal(var + self.eps)
            self.inv_std = xp.sqrt(self.inv_var, dtype=self.inv_var.dtype)

        self.gamma_over_std = gamma * self.inv_std
        x_hat = _x_hat(x, mean[expander], self.inv_std[expander])

        gx = self.gamma_over_std[expander] * gy
        gbeta = gy.sum(axis=self.axis, dtype=gamma.dtype)
        ggamma = (x_hat * gy).sum(axis=self.axis)
        gmean = -self.gamma_over_std * gbeta
        gvar = - 0.5 * self.inv_var * (
            gamma * ggamma).astype(var.dtype, copy=False)

        gx = gx.astype(dtype=x.dtype)

        self.retain_outputs((0, 1, 2, 3, 4))
        return gx, ggamma, gbeta, gmean, gvar 
Example #3
Source File: utility.py    From gxpy with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def vector_normalize(v):
    """
    Normalise (Euclidean) the last axis of a numpy array

    :param v: numpy vector array, any dimension
    :return:  array normalized, 0 vectors will be np.nan

    .. versionadded:: 9.3.1
    """
    if v.ndim < 2:
        return np.array((1.,))
    vs = v.shape
    v = v.reshape((-1, v.shape[-1]))
    mag = np.linalg.norm(v, axis=1)
    mag[mag == 0.] = np.nan
    return (v.T * np.reciprocal(mag)).T.reshape(vs) 
Example #4
Source File: geoname_classifier.py    From EpiTator with Apache License 2.0 6 votes vote down vote up
def predict_proba(X, classifier):
    """Probability estimation for OvR logistic regression.
    Positive class probabilities are computed as
    1. / (1. + np.exp(-classifier.decision_function(X)));
    multiclass is handled by normalizing that over all classes.
    """
    prob = np.dot(X, classifier['coef_'].T) + classifier['intercept_']
    prob = prob.ravel() if prob.shape[1] == 1 else prob
    prob *= -1
    np.exp(prob, prob)
    prob += 1
    np.reciprocal(prob, prob)
    if prob.ndim == 1:
        return np.vstack([1 - prob, prob]).T
    else:
        # OvR normalization, like LibLinear's predict_probability
        prob /= prob.sum(axis=1).reshape((prob.shape[0], -1))
        return prob 
Example #5
Source File: StructuralDynamicIntegrator.py    From florence with MIT License 6 votes vote down vote up
def ComputeMassMatrixInfo(self, M, formulation, fem_solver):
        """Computes the inverse of lumped mass matrix and so on
        """

        invM = None
        if formulation.fields == "electro_mechanics":
            if fem_solver.mass_type == "lumped":
                M = M.ravel()
                invM = np.zeros_like(M)
                invM[self.mechanical_dofs] = np.reciprocal(M[self.mechanical_dofs])
                M_mech = M[self.mechanical_dofs]
            else:
                M_mech = M[self.mechanical_dofs,:][:,self.mechanical_dofs]
        else:
            if fem_solver.mass_type == "lumped":
                M = M.ravel()
                M_mech = M
                invM = np.reciprocal(M)
            else:
                M_mech = M

        return M_mech, invM 
Example #6
Source File: metrics.py    From demon with GNU General Public License v3.0 6 votes vote down vote up
def l1_inverse(depth1,depth2):
    """
    Computes the l1 errors between inverses of two depth maps.
    Takes preprocessed depths (no nans, infs and non-positive values)

    depth1:  one depth map
    depth2:  another depth map

    Returns: 
        L1(log)

    """
    assert(np.all(np.isfinite(depth1) & np.isfinite(depth2) & (depth1 > 0) & (depth2 > 0)))
    diff = np.reciprocal(depth1) - np.reciprocal(depth2)
    num_pixels = float(diff.size)
    
    if num_pixels == 0:
        return np.nan
    else:
        return np.sum(np.absolute(diff)) / num_pixels 
Example #7
Source File: transform.py    From DeepLearning_Wavelet-LSTM with MIT License 5 votes vote down vote up
def fourier_frequencies(self):
        """
        Return the equivalent frequencies .
        This is equivalent to 1.0 / self.fourier_periods
        """
        return np.reciprocal(self.fourier_periods) 
Example #8
Source File: sigmoid.py    From MyGrad with MIT License 5 votes vote down vote up
def __call__(self, a):
        self.variables = (a,)
        x = np.asarray(-1.0 * a.data)
        np.exp(x, out=x)
        x += 1
        np.reciprocal(x, out=x)
        self.sigmoid = x
        return self.sigmoid 
Example #9
Source File: test_layers.py    From onnx-mxnet with Apache License 2.0 5 votes vote down vote up
def test_reciprocal(self):
        """Test for reciprocal operator"""
        node_def = helper.make_node("Reciprocal", ["input1"], ["output"])
        input1 = self._random_array([1, 1000])
        output = mxnet_backend.run_node(node_def, [input1])[0]
        npt.assert_almost_equal(output, np.reciprocal(input1)) 
Example #10
Source File: log_reg_classifier.py    From snips-nlu with Apache License 2.0 5 votes vote down vote up
def _predict_proba(self, X):  # pylint: disable=C0103
        import numpy as np

        self.classifier._check_proba()  # pylint: disable=W0212

        prob = self.classifier.decision_function(X)
        prob *= -1
        np.exp(prob, prob)
        prob += 1
        np.reciprocal(prob, prob)
        if prob.ndim == 1:
            return np.vstack([1 - prob, prob]).T
        return prob 
Example #11
Source File: interface.py    From scikit-umfpack with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _compute_lu(self):
        if self._L is None:
            self._L, self._U, self._P, self._Q, self._R, do_recip = self.umf.lu(self._A)
            if do_recip:
                with np.errstate(divide='ignore'):
                    np.reciprocal(self._R, out=self._R)

            # Conform to scipy.sparse.splu convention on permutation matrices
            self._P = self._P[self._P] 
Example #12
Source File: test_scalarmath.py    From mxnet-lambda with Apache License 2.0 5 votes vote down vote up
def test_blocked(self):
        # test alignments offsets for simd instructions
        # alignments for vz + 2 * (vs - 1) + 1
        for dt, sz in [(np.float32, 11), (np.float64, 7), (np.int32, 11)]:
            for out, inp1, inp2, msg in _gen_alignment_data(dtype=dt,
                                                            type='binary',
                                                            max_size=sz):
                exp1 = np.ones_like(inp1)
                inp1[...] = np.ones_like(inp1)
                inp2[...] = np.zeros_like(inp2)
                assert_almost_equal(np.add(inp1, inp2), exp1, err_msg=msg)
                assert_almost_equal(np.add(inp1, 2), exp1 + 2, err_msg=msg)
                assert_almost_equal(np.add(1, inp2), exp1, err_msg=msg)

                np.add(inp1, inp2, out=out)
                assert_almost_equal(out, exp1, err_msg=msg)

                inp2[...] += np.arange(inp2.size, dtype=dt) + 1
                assert_almost_equal(np.square(inp2),
                                    np.multiply(inp2, inp2),  err_msg=msg)
                # skip true divide for ints
                if dt != np.int32 or (sys.version_info.major < 3 and not sys.py3kwarning):
                    assert_almost_equal(np.reciprocal(inp2),
                                        np.divide(1, inp2),  err_msg=msg)

                inp1[...] = np.ones_like(inp1)
                np.add(inp1, 2, out=out)
                assert_almost_equal(out, exp1 + 2, err_msg=msg)
                inp2[...] = np.ones_like(inp2)
                np.add(2, inp2, out=out)
                assert_almost_equal(out, exp1 + 2, err_msg=msg) 
Example #13
Source File: trigonometric.py    From chainer with MIT License 5 votes vote down vote up
def forward_cpu(self, inputs):
        self.retain_inputs((0, 1))
        x, gy = inputs
        gx = utils.force_array(numpy.square(x))
        numpy.negative(gx, out=gx)
        gx += 1
        numpy.sqrt(gx, out=gx)
        numpy.reciprocal(gx, out=gx)
        numpy.negative(gx, out=gx)
        gx *= gy
        return gx, 
Example #14
Source File: transform.py    From DeepLearning_Wavelet-LSTM with MIT License 5 votes vote down vote up
def fourier_frequencies(self, frequencies):
        """
        Set the scales based on a list of fourier periods.
        This is equivalent to self.fourier_periods = 1.0 / frequencies
        """
        self.fourier_periods = np.reciprocal(frequencies) 
Example #15
Source File: SPEC.py    From fsfc with MIT License 5 votes vote down vote up
def _calc_scores(self, x):
        similarity = rbf_kernel(x)
        adjacency = similarity
        degree_vector = np.sum(adjacency, 1)
        degree = np.diag(degree_vector)
        laplacian = degree - adjacency
        normaliser_vector = np.reciprocal(np.sqrt(degree_vector))
        normaliser = np.diag(normaliser_vector)

        normalised_laplacian = normaliser.dot(laplacian).dot(normaliser)

        weighted_features = np.matmul(normaliser, x)

        normalised_features = weighted_features / np.linalg.norm(weighted_features, axis=0)
        return self._calc_spec_scores(degree, normalised_laplacian, normalised_features, normaliser) 
Example #16
Source File: tfdeploy.py    From tfdeploy with MIT License 5 votes vote down vote up
def Sigmoid(a):
    """
    Sogmoid (logistic) op.
    """
    return np.reciprocal(np.add(1, np.exp(-a))), 
Example #17
Source File: test_scalarmath.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 5 votes vote down vote up
def test_blocked(self):
        # test alignments offsets for simd instructions
        # alignments for vz + 2 * (vs - 1) + 1
        for dt, sz in [(np.float32, 11), (np.float64, 7), (np.int32, 11)]:
            for out, inp1, inp2, msg in _gen_alignment_data(dtype=dt,
                                                            type='binary',
                                                            max_size=sz):
                exp1 = np.ones_like(inp1)
                inp1[...] = np.ones_like(inp1)
                inp2[...] = np.zeros_like(inp2)
                assert_almost_equal(np.add(inp1, inp2), exp1, err_msg=msg)
                assert_almost_equal(np.add(inp1, 2), exp1 + 2, err_msg=msg)
                assert_almost_equal(np.add(1, inp2), exp1, err_msg=msg)

                np.add(inp1, inp2, out=out)
                assert_almost_equal(out, exp1, err_msg=msg)

                inp2[...] += np.arange(inp2.size, dtype=dt) + 1
                assert_almost_equal(np.square(inp2),
                                    np.multiply(inp2, inp2),  err_msg=msg)
                # skip true divide for ints
                if dt != np.int32 or (sys.version_info.major < 3 and not sys.py3kwarning):
                    assert_almost_equal(np.reciprocal(inp2),
                                        np.divide(1, inp2),  err_msg=msg)

                inp1[...] = np.ones_like(inp1)
                np.add(inp1, 2, out=out)
                assert_almost_equal(out, exp1 + 2, err_msg=msg)
                inp2[...] = np.ones_like(inp2)
                np.add(2, inp2, out=out)
                assert_almost_equal(out, exp1 + 2, err_msg=msg) 
Example #18
Source File: transform.py    From DeepLearning_Wavelet-LSTM with MIT License 5 votes vote down vote up
def fourier_frequencies(self):
        """
        Return the equivalent frequencies .
        This is equivalent to 1.0 / self.fourier_periods
        """
        return np.reciprocal(self.fourier_periods) 
Example #19
Source File: transform.py    From DeepLearning_Wavelet-LSTM with MIT License 5 votes vote down vote up
def fourier_frequencies(self):
        """
        Return the equivalent frequencies .
        This is equivalent to 1.0 / self.fourier_periods
        """
        return np.reciprocal(self.fourier_periods) 
Example #20
Source File: trigonometric.py    From chainer with MIT License 5 votes vote down vote up
def forward_cpu(self, inputs):
        self.retain_inputs((0, 1))
        x, gy = inputs
        gx = utils.force_array(numpy.square(x))
        gx += 1
        numpy.reciprocal(gx, out=gx)
        gx *= gy
        return gx, 
Example #21
Source File: test_lobpcg.py    From GraphicDesignPatternByPython with MIT License 5 votes vote down vote up
def test_diagonal():
    # This test was moved from '__main__' in lobpcg.py.
    # Coincidentally or not, this is the same eigensystem
    # required to reproduce arpack bug
    # http://forge.scilab.org/index.php/p/arpack-ng/issues/1397/
    # even using the same n=100.

    np.random.seed(1234)

    # The system of interest is of size n x n.
    n = 100

    # We care about only m eigenpairs.
    m = 4

    # Define the generalized eigenvalue problem Av = cBv
    # where (c, v) is a generalized eigenpair,
    # and where we choose A to be the diagonal matrix whose entries are 1..n
    # and where B is chosen to be the identity matrix.
    vals = np.arange(1, n+1, dtype=float)
    A = scipy.sparse.diags([vals], [0], (n, n))
    B = scipy.sparse.eye(n)

    # Let the preconditioner M be the inverse of A.
    M = scipy.sparse.diags([np.reciprocal(vals)], [0], (n, n))

    # Pick random initial vectors.
    X = np.random.rand(n, m)

    # Require that the returned eigenvectors be in the orthogonal complement
    # of the first few standard basis vectors.
    m_excluded = 3
    Y = np.eye(n, m_excluded)

    eigs, vecs = lobpcg(A, X, B, M=M, Y=Y, tol=1e-4, maxiter=40, largest=False)

    assert_allclose(eigs, np.arange(1+m_excluded, 1+m_excluded+m))
    _check_eigen(A, eigs, vecs, rtol=1e-3, atol=1e-3) 
Example #22
Source File: trigonometric.py    From chainer with MIT License 5 votes vote down vote up
def forward_cpu(self, inputs):
        self.retain_inputs((0, 1))
        x, gy = inputs
        gx = utils.force_array(numpy.square(x))
        numpy.negative(gx, out=gx)
        gx += 1
        numpy.sqrt(gx, out=gx)
        numpy.reciprocal(gx, out=gx)
        gx *= gy
        return gx, 
Example #23
Source File: test_activation.py    From chainer with MIT License 5 votes vote down vote up
def func(self, xp, a):
        if xp is numpy:
            return numpy.asarray(
                numpy.reciprocal(1 + numpy.exp(-a))).astype(a.dtype)
        return xp.sigmoid(a) 
Example #24
Source File: test_sqrt.py    From chainer with MIT License 5 votes vote down vote up
def rsqrt(x, dtype):
    return numpy.reciprocal(numpy.sqrt(x, dtype=dtype), dtype=dtype) 
Example #25
Source File: nettack.py    From nettack with MIT License 5 votes vote down vote up
def compute_cooccurrence_constraint(self, nodes):
        """
        Co-occurrence constraint as described in the paper.

        Parameters
        ----------
        nodes: np.array
            Nodes whose features are considered for change

        Returns
        -------
        np.array [len(nodes), D], dtype bool
            Binary matrix of dimension len(nodes) x D. A 1 in entry n,d indicates that
            we are allowed to add feature d to the features of node n.

        """

        words_graph = self.cooc_matrix.copy()
        D = self.X_obs.shape[1]
        words_graph.setdiag(0)
        words_graph = (words_graph > 0)
        word_degrees = np.sum(words_graph, axis=0).A1

        inv_word_degrees = np.reciprocal(word_degrees.astype(float) + 1e-8)

        sd = np.zeros([self.N])
        for n in range(self.N):
            n_idx = self.X_obs[n, :].nonzero()[1]
            sd[n] = np.sum(inv_word_degrees[n_idx.tolist()])

        scores_matrix = sp.lil_matrix((self.N, D))

        for n in nodes:
            common_words = words_graph.multiply(self.X_obs[n])
            idegs = inv_word_degrees[common_words.nonzero()[1]]
            nnz = common_words.nonzero()[0]
            scores = np.array([idegs[nnz == ix].sum() for ix in range(D)])
            scores_matrix[n] = scores
        self.cooc_constraint = sp.csr_matrix(scores_matrix - 0.5 * sd[:, None] > 0) 
Example #26
Source File: transform.py    From DeepLearning_Wavelet-LSTM with MIT License 5 votes vote down vote up
def fourier_frequencies(self):
        """
        Return the equivalent frequencies .
        This is equivalent to 1.0 / self.fourier_periods
        """
        return np.reciprocal(self.fourier_periods) 
Example #27
Source File: math_ops.py    From trax with Apache License 2.0 5 votes vote down vote up
def reciprocal(x):
  return _scalar(tf.math.reciprocal, x) 
Example #28
Source File: script_smk.py    From ibeis with Apache License 2.0 5 votes vote down vote up
def gamma(smk, X):
        """ gamma(X) = (M(X, X)) ** (-1/2) """
        score = smk.match_score(X, X)
        sccw = np.reciprocal(np.sqrt(score))
        return sccw 
Example #29
Source File: smk_funcs.py    From ibeis with Apache License 2.0 5 votes vote down vote up
def sccw_normalize(scores, weight_list):
    scores *= weight_list
    score = scores.sum()
    sccw = np.reciprocal(np.sqrt(score))
    return sccw 
Example #30
Source File: transform.py    From DeepLearning_Wavelet-LSTM with MIT License 5 votes vote down vote up
def fourier_frequencies(self, frequencies):
        """
        Set the scales based on a list of fourier periods.
        This is equivalent to self.fourier_periods = 1.0 / frequencies
        """
        self.fourier_periods = np.reciprocal(frequencies)