numpy.maximum

Here are the examples of the python api numpy.maximum taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

162 Examples 7

Example 1

Project: oq-hazardlib Source File: atkinson_boore_2006.py
    def _compute_stress_drop_adjustment(self, SC, mag, scale_fac):
        """
        Compute equation (6) p. 2200
        """
        return scale_fac * np.minimum(
            SC['delta'] + 0.05,
            0.05 + SC['delta'] * (
                np.maximum(mag - SC['M1'], 0) / (SC['Mh'] - SC['M1'])
            )
        )

Example 2

Project: hyperspy Source File: label.py
Function: validate_pos
    def _validate_pos(self, pos):
        if len(self.axes) == 1:
            pos = np.maximum(pos, self.axes[0].low_value)
            pos = np.minimum(pos, self.axes[0].high_value)
        elif len(self.axes) > 1:
            pos = np.maximum(pos, [a.low_value for a in self.axes[0:2]])
            pos = np.minimum(pos, [a.high_value for a in self.axes[0:2]])
        else:
            raise ValueError()
        return pos

Example 3

Project: facerec Source File: detector.py
Function: r1
	def _R1(self,BGR):
		# channels
		B = BGR[:,:,0]
		G = BGR[:,:,1]
		R = BGR[:,:,2]
		e1 = (R>95) & (G>40) & (B>20) & ((np.maximum(R,np.maximum(G,B)) - np.minimum(R, np.minimum(G,B)))>15) & (np.abs(R-G)>15) & (R>G) & (R>B)
		e2 = (R>220) & (G>210) & (B>170) & (abs(R-G)<=15) & (R>B) & (G>B)
		return (e1|e2)

Example 4

Project: skl-groups Source File: preprocessing.py
Function: transform
    def transform(self, X):
        """Scaling features of X according to feature_range.

        Parameters
        ----------
        X : array-like with shape [n_samples, n_features]
            Input data that will be transformed.
        """
        X = check_array(X, copy=self.copy)
        X *= self.scale_
        X += self.min_
        if self.truncate:
            np.maximum(self.feature_range[0], X, out=X)
            np.minimum(self.feature_range[1], X, out=X)
        return X

Example 5

Project: ProxImaL Source File: nonneg.py
Function: prox
    def _prox(self, rho, v, *args, **kwargs):
        """x = pos(x).
        """
        idxs = self.weight != 0.
        v[idxs] = np.maximum(self.weight[idxs] * v[idxs], 0.) / self.weight[idxs]
        return v

Example 6

Project: DQN-chainer Source File: dqn_agent_cpu.py
Function: set_state
    def set_state(self, observation):
        # Preproces
        obs_array = self.scale_image(observation)
        obs_processed = np.maximum(obs_array, self.last_observation)  # Take maximum from two frames

        """
        print(obs_processed.max())
        plt.imshow(obs_processed)
        plt.draw()
        plt.pause(0.0001)
        """

        # Updates for the next step
        self.last_observation = obs_array

        # Compose State : 4-step sequential observation
        for i in range(self.dqn.n_history - 1):
            self.state[i] = self.state[i + 1].astype(np.uint8)
        self.state[self.dqn.n_history - 1] = obs_processed.astype(np.uint8)

Example 7

Project: ROLO Source File: sort_yolo.py
Function: iou
def iou(bb_test,bb_gt):
  """
  Computes IUO between two bboxes in the form [x1,y1,x2,y2]
  """
  xx1 = np.maximum(bb_test[0], bb_gt[0])
  yy1 = np.maximum(bb_test[1], bb_gt[1])
  xx2 = np.minimum(bb_test[2], bb_gt[2])
  yy2 = np.minimum(bb_test[3], bb_gt[3])
  w = np.maximum(0., xx2 - xx1)
  h = np.maximum(0., yy2 - yy1)
  wh = w * h
  o = wh / ((bb_test[2]-bb_test[0])*(bb_test[3]-bb_test[1])
    + (bb_gt[2]-bb_gt[0])*(bb_gt[3]-bb_gt[1]) - wh)
  return(o)

Example 8

Project: scikit-learn Source File: test_gmm.py
Function: test_sample
    @ignore_warnings(category=DeprecationWarning)
    def test_sample(self, n=100):
        g = self.model(n_components=self.n_components,
                       covariance_type=self.covariance_type,
                       random_state=rng)
        # Make sure the means are far apart so responsibilities.argmax()
        # picks the actual component used to generate the observations.
        g.means_ = 20 * self.means
        g.covars_ = np.maximum(self.covars[self.covariance_type], 0.1)
        g.weights_ = self.weights

        with ignore_warnings(category=DeprecationWarning):
            samples = g.sample(n)
        self.assertEqual(samples.shape, (n, self.n_features))

Example 9

Project: Mastering-Python-for-Finance-source-codes Source File: BinomialEuropeanOption.py
    def _initialize_payoffs_tree_(self):
        # Get payoffs when the option expires at terminal nodes
        payoffs = np.maximum(
            0, (self.STs-self.K) if self.is_call
            else (self.K-self.STs))

        return payoffs

Example 10

Project: scipy Source File: _discrete_distns.py
Function: arg_check
    def _argcheck(self, M, n, N):
        cond = (M > 0) & (n >= 0) & (N >= 0)
        cond &= (n <= M) & (N <= M)
        self.a = np.maximum(N-(M-n), 0)
        self.b = np.minimum(n, N)
        return cond

Example 11

Project: py-sdm Source File: np_divs.py
Function: get_rhos
    def get_rhos(self):
        self.status_fn('\nGetting within-bag distances...')
        # need to throw away the closet neighbor, which will always be self
        # this means that K=1 corresponds to column 1 in the array
        which_Ks = slice(1, None) if self.save_all_Ks else self.Ks
        max_K = self.max_K
        min_dist = self.min_dist
        maximum = np.maximum
        pbar = progress() if self.progressbar else identity

        self.rhos = [
            maximum(min_dist,
                    np.sqrt(idx.nn_index(bag, max_K + 1)[1][:, which_Ks]))
            for bag, idx in izip(self.features.features, pbar(self.indices))]
        if self.progressbar:
            pbar.finish()

Example 12

Project: facenet Source File: detect_face.py
def rerec(bboxA):
    # convert bboxA to square
    h = bboxA[:,3]-bboxA[:,1]
    w = bboxA[:,2]-bboxA[:,0]
    l = np.maximum(w, h)
    bboxA[:,0] = bboxA[:,0]+w*0.5-l*0.5
    bboxA[:,1] = bboxA[:,1]+h*0.5-l*0.5
    bboxA[:,2:4] = bboxA[:,0:2] + np.transpose(np.tile(l,(2,1)))
    return bboxA

Example 13

Project: splocs Source File: sploc.py
def project_weight(x):
    x = np.maximum(0., x)
    max_x = x.max()
    if max_x == 0:
        return x
    else:
        return x / max_x

Example 14

Project: blockcanvas Source File: selection_context.py
Function: get_context_selection
    def _get_context_selection ( self ):
        context_mask = self.context.context_selection
        self_mask    = self._mask
        if self_mask is None:
            return context_mask

        if context_mask is None:
            return self_mask

        if sum( context_mask & self_mask ) == 0:
            return context_mask | self_mask

        return maximum( context_mask, self_mask )

Example 15

Project: mondrianforest Source File: mondrianforest_utils.py
def compute_gaussian_pdf(e_x, e_x2, x):
    variance = np.maximum(0, e_x2 - e_x ** 2)
    sd = np.sqrt(variance)
    z = (x - e_x) / sd
    # pdf = np.exp(-(z**2) / 2.) / np.sqrt(2*math.pi) / sd
    log_pdf = -0.5*(z**2) -np.log(sd) -0.5*np.log(2*math.pi)
    pdf = np.exp(log_pdf)
    return pdf

Example 16

Project: oq-hazardlib Source File: edwards_fah_2013f.py
    def _compute_term_d(self, C, mag, rrup):
        """
        Compute distance term: original implementation from Carlo Cauzzi
        if M > 5.5     rmin = 0.55;
        elseif M > 4.7 rmin = -2.067.*M +11.92;
        else           rmin = -0.291.*M + 3.48;
        end
        d = log10(max(R,rmin));
        """
        if mag > self.M1:
            rrup_min = 0.55
        elif mag > self.M2:
            rrup_min = -2.067 * mag + 11.92
        else:
            rrup_min = -0.291 * mag + 3.48

        R = np.maximum(rrup_min, rrup)

        return np.log10(R)

Example 17

Project: horus Source File: current_video.py
Function: combine_images
    def _combine_images(self, images):
        if images[0] is not None and images[1] is not None:
            return np.maximum(images[0], images[1])

        if images[0] is not None:
            return images[0]

        if images[1] is not None:
            return images[1]

Example 18

Project: hyperopt Source File: criteria.py
def EI_empirical(samples, thresh):
    """Expected Improvement over threshold from samples

    (See example usage in EI_gaussian_empirical)
    """
    improvement = np.maximum(samples - thresh, 0)
    return improvement.mean()

Example 19

Project: pystruct Source File: inference.py
def objective_primal(model, w, X, Y, C, variant='n_slack', n_jobs=1):
    objective = 0
    constraints = Parallel(
        n_jobs=n_jobs)(delayed(find_constraint)(
            model, x, y, w)
            for x, y in zip(X, Y))
    slacks = list(zip(*constraints))[2]

    if variant == 'n_slack':
        slacks = np.maximum(slacks, 0)

    objective = max(np.sum(slacks), 0) * C + np.sum(w ** 2) / 2.
    return objective

Example 20

Project: pyNCS Source File: mapping.py
    def __resize_matrix_resample(self, groupsrc, groupdst, M):
        from scipy.signal import resample
        x_resampled = resample(M, len(groupsrc), window='blk')
        xy_resampled = resample(
            x_resampled.transpose(), len(groupdst), window='blk').transpose()
        return np.minimum(np.maximum(xy_resampled, 0), 1)

Example 21

Project: CyLP Source File: DualDantzigPivot.py
Function: pivot_row
    def pivotRow(self):
        model = self.clpModel
        nConstraints = model.nConstraints
        basicVarInds = model.basicVariables

        u = model.upper[basicVarInds]
        l = model.lower[basicVarInds]
        s = model.solution[basicVarInds]
        infeasibilities = np.maximum(s - u, l - s)

        m = max(infeasibilities)

        if m > model.primalTolerance:
            return np.argmax(infeasibilities)
        return -1

Example 22

Project: conceptdb Source File: belief_network.py
    def adjusted_conductances(self, equiv_conductances):
        assert len(equiv_conductances) == len(self.nodes)
        
        equiv_resistances = 1.0/np.maximum(0, equiv_conductances)
        edge_resistances = 1.0/self._edge_conductance
        combined_resistances = self._conjunction_matrix.dot(equiv_resistances)
        new_resistances = (edge_resistances + combined_resistances)
        adjusted_conductances = 1.0/new_resistances
        print adjusted_conductances
        return adjusted_conductances

Example 23

Project: fast-rcnn Source File: test.py
Function: clip_boxes
def _clip_boxes(boxes, im_shape):
    """Clip boxes to image boundaries."""
    # x1 >= 0
    boxes[:, 0::4] = np.maximum(boxes[:, 0::4], 0)
    # y1 >= 0
    boxes[:, 1::4] = np.maximum(boxes[:, 1::4], 0)
    # x2 < im_shape[1]
    boxes[:, 2::4] = np.minimum(boxes[:, 2::4], im_shape[1] - 1)
    # y2 < im_shape[0]
    boxes[:, 3::4] = np.minimum(boxes[:, 3::4], im_shape[0] - 1)
    return boxes

Example 24

Project: ProxImaL Source File: nonneg.py
Function: prox
    def _prox(self, rho, v, *args, **kwargs):
        """x = pos(x).
        """
        np.maximum(v, 0, v)
        v *= self.mask
        return v

Example 25

Project: deep_q_rl Source File: ale_experiment.py
Function: get_observation
    def get_observation(self):
        """ Resize and merge the previous two screen images """

        assert self.buffer_count >= 2
        index = self.buffer_count % self.buffer_length - 1
        max_image = np.maximum(self.screen_buffer[index, ...],
                               self.screen_buffer[index - 1, ...])
        return self.resize_image(max_image)

Example 26

Project: py-sdm Source File: np_divs.py
def js_clamp(Ks, dim, rhos, required):
    # TODO: less hacky solution to this problem
    js, = required
    est = np.maximum(0, js)
    np.minimum(np.log(2), est, out=est)
    return est

Example 27

Project: treeano Source File: utils.py
def maximum(a, b):
    """
    polymorphic version of max or theano.tensor.maximum
    """
    if is_variable(a) or is_variable(b):
        return T.maximum(a, b)
    else:
        return np.maximum(a, b)

Example 28

Project: pysparkling Source File: stat_counter.py
Function: merge
    def merge(self, value):
        delta = value - self.mu
        self.n += 1
        self.mu += delta / self.n
        self.m2 += delta * (value - self.mu)
        self.maxValue = maximum(self.maxValue, value)
        self.minValue = minimum(self.minValue, value)

        return self

Example 29

Project: skl-groups Source File: knn.py
Function: hellinger
def hellinger(Ks, dim, required, clamp=True, to_self=False):
    r'''
    Estimate the Hellinger distance between distributions, based on kNN
    distances:  \sqrt{1 - \int \sqrt{p q}}

    Always enforces 0 <= H, to be able to sqrt; if clamp, also enforces
    H <= 1.

    Returns a vector: one element for each K.
    '''
    bc = required
    est = 1 - bc
    np.maximum(est, 0, out=est)
    if clamp:
        np.minimum(est, 1, out=est)
    np.sqrt(est, out=est)
    return est

Example 30

Project: tfdeploy Source File: tfdeploy.py
Function: relu
@Operation.factory
def Relu(a):
    """
    Relu op.
    """
    return np.maximum(a, 0),

Example 31

Project: datasketch Source File: hyperloglog.py
Function: merge
    def merge(self, other):
        '''
        Merge the other HyperLogLog with this one, making this the union of the
        two.
        '''
        if self.m != other.m or self.p != other.p:
            raise ValueError("Cannot merge HyperLogLog with different\
                    precisions.")
        self.reg = np.maximum(self.reg, other.reg)

Example 32

Project: DQN-chainer Source File: dqn_agent.py
Function: set_state
    def set_state(self, observation):
        # Preproces
        obs_array = self.scale_image(observation)
        obs_processed = np.maximum(obs_array, self.last_observation)  # Take maximum from two frames

        # Updates for the next step
        self.last_observation = obs_array

        # Compose State : 4-step sequential observation
        for i in range(self.dqn.n_history - 1):
            self.state[i] = self.state[i + 1].astype(np.uint8)
        self.state[self.dqn.n_history - 1] = obs_processed.astype(np.uint8)

Example 33

Project: PyCV-time Source File: watershed.py
Function: watershed
    def watershed(self):
        m = self.markers.copy()
        cv2.watershed(self.img, m)
        overlay = self.colors[np.maximum(m, 0)]
        vis = cv2.addWeighted(self.img, 0.5, overlay, 0.5, 0.0, dtype=cv2.CV_8UC3)
        cv2.imshow('watershed', vis)

Example 34

Project: pystruct Source File: subgradient_latent_ssvm.py
Function: objective
    def _objective(self, X, Y):
        constraints = Parallel(
            n_jobs=self.n_jobs,
            verbose=self.verbose - 1)(delayed(find_constraint_latent)(
                self.model, x, y, self.w)
                for x, y in zip(X, Y))
        slacks = list(zip(*constraints))[2]
        slacks = np.maximum(slacks, 0)

        objective = np.sum(slacks) * self.C + np.sum(self.w ** 2) / 2.
        return objective

Example 35

Project: oq-hazardlib Source File: edwards_fah_2013a.py
    def _compute_term_r(self, C, mag, rrup):
        """
        Compute distance term
        d = log10(max(R,rmin));
        """
        if mag > self.M1:
            rrup_min = 0.55

        elif mag > self.M2:
            rrup_min = -2.80 * mag + 14.55

        else:
            rrup_min = -0.295 * mag + 2.65

        R = np.maximum(rrup, rrup_min)

        return np.log10(R)

Example 36

Project: qspectrumanalyzer Source File: data.py
    def update_peak_hold_max(self, data):
        """Update max. peak hold data"""
        if self.peak_hold_max is None:
            self.peak_hold_max = data["y"].copy()
        else:
            self.peak_hold_max = np.maximum(self.peak_hold_max, data["y"])
            self.peak_hold_max_updated.emit(self)

Example 37

Project: glumpy Source File: snippet-cubes.py
Function: on_mouse_scroll
@window.event
def on_mouse_scroll(x, y, dx, dy):
    global fovy
    fovy = np.minimum(np.maximum(fovy*(1+dy/100), 10.0), 179.0)
    program['projection'] = glm.perspective(fovy,
                                            window.width/float(window.height),
                                            1.0, 100.0)

Example 38

Project: scikit-learn Source File: test_spectral.py
def test_spectral_clustering_sparse():
    X, y = make_blobs(n_samples=20, random_state=0,
                      centers=[[1, 1], [-1, -1]], cluster_std=0.01)

    S = rbf_kernel(X, gamma=1)
    S = np.maximum(S - 1e-4, 0)
    S = sparse.coo_matrix(S)

    labels = SpectralClustering(random_state=0, n_clusters=2,
                                affinity='precomputed').fit(S).labels_
    assert_equal(adjusted_rand_score(y, labels), 1)

Example 39

Project: hmmlearn Source File: test_gaussian_hmm.py
    def test_sample(self, n=1000):
        h = hmm.GaussianHMM(self.n_components, self.covariance_type)
        h.startprob_ = self.startprob
        h.transmat_ = self.transmat
        # Make sure the means are far apart so posteriors.argmax()
        # picks the actual component used to generate the observations.
        h.means_ = 20 * self.means
        h.covars_ = np.maximum(self.covars[self.covariance_type], 0.1)

        X, state_sequence = h.sample(n, random_state=self.prng)
        self.assertEqual(X.shape, (n, self.n_features))
        self.assertEqual(len(state_sequence), n)

Example 40

Project: bx-python Source File: pwm.py
    def to_logodds_scoring_matrix( self, background=None, correction=DEFAULT_CORRECTION ):
        """
        Create a standard logodds scoring matrix.
        """
        alphabet_size = len( self.alphabet )
        if background is None:
            background = ones( alphabet_size, float32 ) / alphabet_size
        # Row totals as a one column array
        totals = numpy.sum( self.values, 1 )[:,newaxis]
        values = log2( maximum( self.values, correction ) ) \
               - log2( totals ) \
               - log2( maximum( background, correction ) )
        return ScoringMatrix.create_from_other( self, values.astype( float32 ) )

Example 41

Project: hyperspy Source File: widget.py
Function: validate_pos
    def _validate_pos(self, pos):
        """Validates the passed position. Depending on the position and the
        implementation, this can either fire a ValueError, or return a modified
        position that has valid values. Or simply return the unmodified
        position if everything is ok.

        This default implementation bounds the position within the axes limits.
        """
        if len(pos) != len(self.axes):
            raise ValueError()
        pos = np.maximum(pos, [ax.low_value for ax in self.axes])
        pos = np.minimum(pos, [ax.high_value for ax in self.axes])
        if self.snap_position:
            pos = self._do_snap_position(pos)
        return pos

Example 42

Project: tensorpack Source File: atari.py
Function: current_state
    def current_state(self):
        """
        :returns: a gray-scale (h, w, 1) uint8 image
        """
        ret = self._grab_raw_image()
        # max-pooled over the last screen
        ret = np.maximum(ret, self.last_raw_screen)
        if self.viz:
            if isinstance(self.viz, float):
                cv2.imshow(self.windowname, ret)
                time.sleep(self.viz)
        ret = ret[self.height_range[0]:self.height_range[1],:].astype('float32')
        # 0.299,0.587.0.114. same as rgb2y in torch/image
        ret = cv2.cvtColor(ret, cv2.COLOR_RGB2GRAY)
        ret = cv2.resize(ret, self.image_shape)
        ret = np.expand_dims(ret, axis=2)
        return ret.astype('uint8')  # to save some memory

Example 43

Project: volumina Source File: datasources.py
Function: request
        @translate_lf_exceptions
        def request( self, slicing ):
            if cfg.getboolean('pixelpipeline', 'verbose'):
                volumina.printLock.acquire()
                print "  LazyflowSource '%s' requests %s" % (self.objectName(), volumina.strSlicing(slicing))
                volumina.printLock.release()
            if not is_pure_slicing(slicing):
                raise Exception('LazyflowSource: slicing is not pure')
            assert self._op5 is not None, "Underlying operator is None.  Are you requesting from a datasource that has been cleaned up already?"

            start, stop = sliceToRoi(slicing, self._op5.Output.meta.shape)
            clipped_roi = np.maximum(start, (0,0,0,0,0)), np.minimum(stop, self._op5.Output.meta.shape)
            clipped_slicing = roiToSlice(*clipped_roi)
            return LazyflowRequest( self._op5, clipped_slicing, self._priority, objectName=self.objectName() )

Example 44

Project: tfr Source File: spectrogram.py
def db_scale(magnitude_spectrum, normalized=False):
    """
    Transform linear magnitude to dbFS (full-scale) [-120, 0] (for input range
    [0.0, 1.0]) which can be optionally normalized to [0.0, 1.0].
    """
    scaled = 20 * np.log10(np.maximum(1e-6, magnitude_spectrum))

    # map from raw dB [-120.0, 0] to [0.0, 1.0]
    if normalized:
        scaled = (scaled / 120) + 1
    return scaled

Example 45

Project: scipy Source File: kdtree.py
    def min_distance_rectangle(self, other, p=2.):
        """
        Compute the minimum distance between points in the two hyperrectangles.

        Parameters
        ----------
        other : hyperrectangle
            Input.
        p : float
            Input.

        """
        return minkowski_distance(0, np.maximum(0,np.maximum(self.mins-other.maxes,other.mins-self.maxes)),p)

Example 46

Project: chainer Source File: test_hard_sigmoid.py
    def check_forward(self, x_data):
        x = chainer.Variable(x_data)
        y = functions.hard_sigmoid(x)
        self.assertIs(y.data.dtype, x_data.dtype)
        expect = numpy.minimum(1.0, numpy.maximum(0.0, self.x * 0.2 + 0.5))
        testing.assert_allclose(
            y.data, expect, **self.check_forward_option)

Example 47

Project: xarray Source File: test_dask.py
    @unittest.skip('currently broken in dask, see GH1090')
    def test_bivariate_ufunc(self):
        u = self.eager_var
        v = self.lazy_var
        self.assertLazyAndAllClose(np.maximum(u, 0), xu.maximum(v, 0))
        self.assertLazyAndAllClose(np.maximum(u, 0), xu.maximum(0, v))

Example 48

Project: tfdeploy Source File: tfdeploy.py
Function: maximum
@Operation.factory
def Maximum(a, b):
    """
    Maximum op.
    """
    return np.maximum(a, b),

Example 49

Project: sort Source File: sort.py
Function: iou
@jit
def iou(bb_test,bb_gt):
  """
  Computes IUO between two bboxes in the form [x1,y1,x2,y2]
  """
  xx1 = np.maximum(bb_test[0], bb_gt[0])
  yy1 = np.maximum(bb_test[1], bb_gt[1])
  xx2 = np.minimum(bb_test[2], bb_gt[2])
  yy2 = np.minimum(bb_test[3], bb_gt[3])
  w = np.maximum(0., xx2 - xx1)
  h = np.maximum(0., yy2 - yy1)
  wh = w * h
  o = wh / ((bb_test[2]-bb_test[0])*(bb_test[3]-bb_test[1])
    + (bb_gt[2]-bb_gt[0])*(bb_gt[3]-bb_gt[1]) - wh)
  return(o)

Example 50

Project: py-sdm Source File: np_divs.py
Function: hellinger
def hellinger(Ks, dim, rhos, required):
    r'''
    Estimate the Hellinger distance between distributions, based on kNN
    distances:  \sqrt{1 - \int \sqrt{p q}}

    Always clamps 0 <= H <= 1.

    Returns a vector: one element for each K.
    '''
    bc, = required
    est = 1 - bc
    np.maximum(est, 0, out=est)
    np.sqrt(est, out=est)
    return est
See More Examples - Go to Next Page
Page 1 Selected Page 2 Page 3 Page 4