Here are the examples of the python api numpy.clip taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
163 Examples
3
Example 1
Project: kaggle-heart Source File: postprocess.py
def make_monotone_distribution(distribution):
if distribution.ndim==1:
for j in xrange(len(distribution)-1):
if not distribution[j] <= distribution[j+1]:
distribution[j+1] = distribution[j]
distribution = np.clip(distribution, 0.0, 1.0)
return distribution
else:
return np.apply_along_axis(make_monotone_distribution, axis=-1, arr=distribution)
3
Example 2
Project: lhcb_trigger_ml Source File: losses.py
def update_tree_leaf(self, leaf, indices_in_leaf, X, y, y_pred, sample_weight, update_mask, residual):
leaf_y = y[indices_in_leaf]
y_signed = 2 * leaf_y - 1
leaf_weights = sample_weight[indices_in_leaf]
residual_abs = expit(numpy.clip(-y_signed * y_pred[indices_in_leaf], -10, 10))
nominator = numpy.sum(y_signed * residual_abs * leaf_weights)
denominator = numpy.sum(residual_abs * (1 - residual_abs) * leaf_weights)
return nominator / (denominator + self.adjusted_regularization)
3
Example 3
def log_losses(y, t, eps=1e-15):
if t.ndim == 1:
t = one_hot(t)
y = np.clip(y, eps, 1 - eps)
losses = -np.sum(t * np.log(y), axis=1)
return losses
3
Example 4
Project: polar2grid Source File: rescale.py
def ctt_scale(img, min_out, max_out, min_in, max_in, flip=True, **kwargs):
"""cloud top temperature scaling.
The original was for unsigned 8-bit files from 10 to 250.
"""
img = linear_flexible_scale(img, min_out+10, max_out-5, min_in, max_in, flip=flip, **kwargs)
numpy.clip(img, min_out+10, max_out-5, img)
return img
3
Example 5
def __getitem__(self, item):
if isinstance(item, tuple):
raise ValueError('ColorArray indexing is only allowed along '
'the first dimension.')
# Ensure item is either a scalar or a column vector.
item = _vector(item, type='column')
# Clip the values in [0, 1].
item = np.clip(item, 0., 1.)
colors = self.map(item)
return ColorArray(colors)
3
Example 6
def orbit(self, azim, elev):
"""Orbits the camera around the center position. *azim* and *elev* are given in degrees."""
self.opts['azimuth'] += azim
#self.opts['elevation'] += elev
self.opts['elevation'] = np.clip(self.opts['elevation'] + elev, -90, 90)
self.update()
3
Example 7
Project: binary_net Source File: weight_clip.py
def __call__(self, opt):
if cuda.available:
kernel = cuda.elementwise(
'T low, T high',
'T p',
'p = (p < low) ? low : (p > high) ? high : p',
'weight_clip')
for param in opt.target.params():
p = param.data
with cuda.get_device(p) as dev:
if int(dev) == -1:
numpy.clip(p, self.low, self.high)
else:
kernel(self.low, self.high, p)
3
Example 8
Project: director Source File: testAtlasCommand.py
def _computeNextPose(self, previousPose, currentPose, goalPose, elapsed, elapsedPrevious, maxSpeed):
v = 1.0/elapsedPrevious * (currentPose - previousPose)
u = -self._Kp*(currentPose - goalPose) - self._Kd*v # u = -K*x
v_next = v + elapsed*u
v_next = np.clip(v_next,-maxSpeed,maxSpeed) # velocity clamp
nextPose = currentPose + v_next*elapsed
nextPose = self.clipPoseToJointLimits(nextPose)
return nextPose
3
Example 9
def loss(self, Y, Y_pred):
# Assumes one-hot encoding.
eps = 1e-15
Y_pred = np.clip(Y_pred, eps, 1 - eps)
Y_pred /= Y_pred.sum(axis=1, keepdims=True)
loss = -np.sum(Y * np.log(Y_pred))
return loss / Y.shape[0]
3
Example 10
Project: galry Source File: navigation_processor.py
def activate_navigation_constrain(self):
"""Constrain the navigation to a bounding box."""
if self.constrain_navigation:
# constrain scaling
self.sx = np.clip(self.sx, self.sxmin, self.sxmax)
self.sy = np.clip(self.sy, self.symin, self.symax)
# constrain translation
self.tx = np.clip(self.tx, 1./self.sx - self.xmax,
-1./self.sx - self.xmin)
self.ty = np.clip(self.ty, 1./self.sy + self.ymin,
-1./self.sy + self.ymax)
else:
# constrain maximum zoom anyway
self.sx = min(self.sx, self.sxmax)
self.sy = min(self.sy, self.symax)
3
Example 11
Project: polar2grid Source File: dtype.py
def clip_to_data_type(data, data_type):
if not isinstance(data_type, (str, unicode)):
data_type = dtype_to_str(data_type)
if data_type not in str2dtype:
log.error("Unknown data_type '%s', don't know how to convert data" % (data_type,))
raise ValueError("Unknown data_type '%s', don't know how to convert data" % (data_type,))
rmin, rmax = dtype2range[data_type]
log.debug("Clipping data to a %d - %d data range" % (rmin, rmax))
numpy.clip(data, rmin, rmax, out=data)
return convert_to_data_type(data, data_type)
3
Example 12
Project: orange3-text Source File: owduplicates.py
def recalculate_linkage(self):
if self.distances is not None:
self.linkage = dist_matrix_linkage(self.distances,
self.LINKAGE[self.linkage_method].lower())
# Magnitude of the spinbox's step is data-dependent
vals = sorted(self.linkage[:, 2])
low, up = vals[0], vals[-1]
step = (up - low) / 20
self.threshold_spin.setSingleStep(step)
self.threshold = np.clip(self.threshold, low, up)
self.histogram.setValues([]) # without this range breaks when changing linkages
self.histogram.setValues(vals)
self.histogram.setRegion(0, self.threshold)
self.detect_duplicates()
3
Example 13
Project: Chimp Source File: dqn_learner.py
def pre_process_reward(self, r):
"""
Clips and re-scales the rewards
"""
if self.clip_reward:
r = np.clip(r,-self.clip_reward,self.clip_reward)
if self.reward_rescale:
self.r_max = max(np.amax(np.absolute(r)),self.r_max)
r = r / self.r_max
return r
3
Example 14
def encode_images(self, images):
"""
Encode images x => z
images is an n x 3 x s x s numpy array where:
n = number of images
3 = R G B channels
s = size of image (eg: 64, 128, etc)
pixels values for each channel are encoded [0,1]
returns an n x z numpy array where:
n = len(images)
z = dimension of latent space
"""
images2 = np.clip((2.0 * images - 1.0), -1, 1)
return self.Z_hat_fn(images2)
3
Example 15
Project: director Source File: perception.py
def applyNeckPitchDelta(self, delta):
if delta == 0:
return
neckPitch = self.getNeckPitchDegrees() + delta
neckPitch = np.clip(neckPitch, -90, 90)
self.setNeckPitch(neckPitch)
3
Example 16
def find_closest(A, target):
# A must be sorted
idx = A.searchsorted(target)
idx = np.clip(idx, 1, len(A) - 1)
left = A[idx - 1]
right = A[idx]
idx -= target - left < right - target
return idx
3
Example 17
def rvs(self, size=1):
mrvs = self.mixing_dist.rvs(size)
#TODO: check strange cases ? this assumes continous integers
mrvs_idx = (np.clip(mrvs, self.ma, self.mb) - self.ma).astype(int)
bd_args = tuple(md[mrvs_idx] for md in self.bd_args)
bd_kwds = dict((k, self.bd_kwds[k][mrvs_idx]) for k in self.bd_kwds)
kwds = {'size':size}
kwds.update(bd_kwds)
rvs = self.base_dist.rvs(*self.bd_args, **kwds)
return rvs, mrvs_idx
3
Example 18
def sample_softmax(self, state):
Q = self.net.sim([state]).flatten()
Q = numpy.exp(numpy.clip(Q/self.epsilon, -500, 500))
Q /= Q.sum()
# Would like to use numpy, but haven't upgraded enough (need 1.7)
# numpy.random.choice(self.numActions, 1, p=Q)
Q = Q.cuemsum()
return numpy.where(Q >= numpy.random.random())[0][0]
3
Example 19
Project: zipline Source File: technical.py
def compute(self, today, assets, out, closes):
diffs = diff(closes, axis=0)
ups = nanmean(clip(diffs, 0, inf), axis=0)
downs = abs(nanmean(clip(diffs, -inf, 0), axis=0))
return evaluate(
"100 - (100 / (1 + (ups / downs)))",
local_dict={'ups': ups, 'downs': downs},
global_dict={},
out=out,
)
3
Example 20
def categorical_cross_entropy(y_pred, y_true, eps=1e-15):
# Assumes one-hot encoding.
y_pred = np.clip(y_pred, eps, 1 - eps)
# XXX: do we need to normalize?
y_pred /= y_pred.sum(axis=1, keepdims=True)
loss = -np.sum(y_true * np.log(y_pred), axis=1)
return loss
3
Example 21
Project: mystic Source File: crypta.py
def constraint(x):
# x[0:10] in range(0,10); x[10:] in range(0,2)
x = round(x).astype(int) # force round and convert type to int
x0,x1 = x[:-2],x[-2:]
x0 = clip(x0, 0,9) #XXX: hack to impose bounds
x1 = clip(x1, 0,1) #XXX: hack to impose bounds
x0 = unique(x0, range(0,10))
return hstack([x0, x1])
3
Example 22
def smoothstep(edge0, edge1, x):
""" performs smooth Hermite interpolation
between 0 and 1 when edge0 < x < edge1. """
# Scale, bias and saturate x to 0..1 range
x = np.clip((x - edge0)/(edge1 - edge0), 0.0, 1.0)
# Evaluate polynomial
return x*x*(3 - 2*x)
3
Example 23
def lookup(texarr,uvarrin): #uvarrin is an array of uv coordinates
uvarr = np.clip(uvarrin,0.0,0.999)
uvarr[:,0] *= float(texarr.shape[1])
uvarr[:,1] *= float(texarr.shape[0])
uvarr = uvarr.astype(int)
return texarr[ uvarr[:,1], uvarr[:,0] ]
3
Example 24
def orbit(self, azim, elev):
""" Orbits the camera around the center position.
Parameters
----------
azim : float
Angle in degrees to rotate horizontally around the center point.
elev : float
Angle in degrees to rotate vertically around the center point.
"""
self.azimuth += azim
self.elevation = np.clip(self.elevation + elev, -90, 90)
self.view_changed()
3
Example 25
Project: biggus Source File: test__Elementwise.py
def test_partial_function(self):
clip_between = partial(np.clip, a_min=1, a_max=4)
self._test(clip_between)
array = np.arange(10000, dtype=np.float32)
actual = Elementwise(array, None, clip_between)
assert_array_equal(actual.ndarray(), clip_between(array))
self.assertEqual(actual.ndarray().max(), 4)
3
Example 26
def format_date(self, x, pos=None):
thisind = np.clip(int(x+0.5), 0, len(self.index)-1)
date = self.index[thisind]
gen_freq = self.locator.gen_freq
if gen_freq == 'T':
return date.strftime('%H:%M %m/%d/%y')
if gen_freq == 'H':
return date.strftime('%H:%M %m/%d/%y')
if gen_freq in ['D', 'W']:
return date.strftime('%m/%d/%Y')
if gen_freq in ['M', 'MS']:
return date.strftime('%m/%d/%Y')
return date.strftime('%m/%d/%Y %H:%M')
3
Example 27
Project: JoustMania Source File: bubble.py
def change_music_speed(self, fast):
change_percent = numpy.clip((time.time() - self.change_time)/INTERVAL_CHANGE, 0, 1)
if fast:
self.music_speed.value = common.lerp(FAST_MUSIC_SPEED, SLOW_MUSIC_SPEED, change_percent)
elif not fast:
self.music_speed.value = common.lerp(SLOW_MUSIC_SPEED, FAST_MUSIC_SPEED, change_percent)
self.audio.change_ratio(self.music_speed.value)
3
Example 28
Project: SimpleCV Source File: frame_convert.py
def pretty_depth(depth):
"""Converts depth into a 'nicer' format for display
This is abstracted to allow for experimentation with normalization
Args:
depth: A numpy array with 2 bytes per pixel
Returns:
A numpy array that has been processed whos datatype is unspecified
"""
np.clip(depth, 0, 2**10 - 1, depth)
depth >>= 2
depth = depth.astype(np.uint8)
return depth
3
Example 29
Project: polar2grid Source File: rescale.py
def lookup_scale(img, min_out, max_out, min_in, max_in, table_name="crefl", **kwargs):
lut = lookup_tables[table_name]
tmp_max_out = lut.shape[0] - 1
LOG.debug("Running 'lookup_scale' with LUT '%s' which has %d elements...", table_name, tmp_max_out + 1)
img = linear_flexible_scale(img, 0, tmp_max_out, min_in, max_in)
numpy.clip(img, 0, tmp_max_out, out=img)
img = lut[img.astype(numpy.uint32)]
img = linear_flexible_scale(img, min_out, max_out, lut.min(), lut.max(), **kwargs)
return img
3
Example 30
Project: tfdeploy Source File: tfdeploy.py
@Operation.factory
def Relu6(a):
"""
Relu6 op.
"""
return np.clip(a, 0, 6),
3
Example 31
Project: pyensemble Source File: ensemble.py
def _mxentropy(y, y_bin, probs):
"""return negative mean cross entropy since we're maximizing the score
for hillclimbing"""
# clip away from extremes to avoid under/overflows
eps = 1.0e-7
clipped = np.clip(probs, eps, 1.0 - eps)
clipped /= clipped.sum(axis=1)[:, np.newaxis]
return (y_bin * np.log(clipped)).sum() / y.shape[0]
3
Example 32
def f(self, x):
exp = np.exp(np.clip(x, self.log_min_bound, self.log_max_bound))
f = np.log(1. + exp)
# if np.isnan(f).any():
# import ipdb;ipdb.set_trace()
return np.clip(f, self.min_bound, self.max_bound)
3
Example 33
def getSlice(self, parent=None):
if self.patch is None:
return ([],[])
(ph,pw) = self.patch.shape
if parent is not None:
(H,W) = parent.shape
return (slice(np.clip(self.y0, 0, H), np.clip(self.y0+ph, 0, H)),
slice(np.clip(self.x0, 0, W), np.clip(self.x0+pw, 0, W)))
return (slice(self.y0, self.y0+ph),
slice(self.x0, self.x0+pw))
3
Example 34
Project: pybrain Source File: bicycle.py
def _updateEtraces(self, state, action, responsibility=1.):
self._etraces *= self.rewardDiscount * self._lambda * responsibility
# This assumes that state is an identity vector (like, from one_to_n).
self._etraces[action] = clip(self._etraces[action] + state, -np.inf, 1.)
# Set the trace for all other actions in this state to 0:
action_bit = one_to_n(action, self.num_actions)
for argstate in argwhere(state == 1) :
self._etraces[argwhere(action_bit != 1), argstate] = 0.
3
Example 35
Project: PyCV-time Source File: lappyr.py
def merge_lappyr(levels):
img = levels[-1]
for lev_img in levels[-2::-1]:
img = cv2.pyrUp(img, dstsize=getsize(lev_img))
img += lev_img
return np.uint8(np.clip(img, 0, 255))
3
Example 36
def _clean(self, p):
"""
Clip logistic values to range (eps, 1-eps)
Parameters
-----------
p : array-like
Probabilities
Returns
--------
pclip : array
Clipped probabilities
"""
return np.clip(p, FLOAT_EPS, 1. - FLOAT_EPS)
3
Example 37
def on_mouse_scroll(self, x, y, dx, dy):
# Normalize mouse coordinates and invert y axis
x = x/(self._width/2.) - 1.
y = 1.0 - y/(self._height/2.)
zoom = np.clip(self._zoom*(1.0+dy/100.0), self.zoom_min, self.zoom_max)
ratio = zoom / self.zoom
xpan = x-ratio*(x-self.pan[0])
ypan = y-ratio*(y-self.pan[1])
self.zoom = zoom
self.pan = xpan, ypan
3
Example 38
Project: director Source File: perception.py
def onWheelDelta(self, delta):
if not self.active:
return False
self.delta += np.clip(delta, -1, 1)
neckPitch = self.getNeckPitchDegrees() + self.delta
self.showText(neckPitch)
return True
3
Example 39
def log_likelihood(self, data):
x = data["x"]
pi = self.pi(data)
pi = np.clip(pi, 1e-16, 1-1e-16)
# Compute the multinomial log likelihood given psi
assert x.shape == pi.shape
ll = 0
ll += gammaln(x.sum(axis=1) + 1).sum() - gammaln(x+1).sum()
ll += (x * np.log(pi)).sum()
return ll
3
Example 40
Project: TensorLog Source File: learn.py
def applyMeanUpdate(self,paramGrads,rate,n):
""" Compute the mean of each parameter gradient, and add it to the
appropriate param, after scaling by rate. If necessary clip
negative parameters to zero.
"""
for (functor,arity),delta0 in paramGrads.items():
#clip the delta vector to avoid exploding gradients
#TODO have a clip function in mutil?
delta = mutil.mapData(lambda d:NP.clip(d,MIN_GRADIENT,MAX_GRADIENT), delta0)
m0 = self.prog.db.getParameter(functor,arity)
if mutil.numRows(m0)==1:
#for a parameter that is a row-vector, we have one gradient per example
m1 = m0 + mutil.mean(delta)*rate
else:
#for a parameter that is matrix, we have one gradient for the whole
m1 = m0 + delta*(1.0/n)*rate
#clip negative entries of parameters to zero
m = mutil.mapData(lambda d:NP.clip(d,0.0,NP.finfo('float64').max), m1)
self.prog.db.setParameter(functor,arity,m)
3
Example 41
Project: supersmoother Source File: smoother.py
def span_int(self, t=None):
if t is None:
t = self.t
if callable(self.span):
spanint = self.span(t) * len(self.t)
elif iterable(self.span):
spanint = self.span[self.isort] * len(self.t)
else:
spanint = self.span * len(self.t)
return np.clip(spanint, 3, None)
3
Example 42
def _dump_image(self, im, idx=None):
assert im.ndim in [2, 3], str(im.ndim)
fname = os.path.join(
self.log_dir,
self.prefix + '-ep{:03d}{}.png'.format(
self.epoch_num, '-' + str(idx) if idx else ''))
res = im * self.scale
if self.clip:
res = np.clip(res, 0, 255)
cv2.imwrite(fname, res.astype('uint8'))
3
Example 43
Project: lhcb_trigger_ml Source File: rootutilities.py
def tree2pandas(filename, treename, branches=None, start=None, stop=None, selection=None, clip=1e33):
import root_numpy
data = root_numpy.root2array(filenames=filename, treename=treename, branches=branches,
selection=selection, start=start, stop=stop)
data = pandas.DataFrame(data)
if clip is not None:
data = numpy.clip(data, -clip, clip)
return data
3
Example 44
Project: TileStache Source File: Composite.py
def blend_channels_linear_light(bottom_chan, top_chan):
""" Return combination of bottom and top channels.
Math from http://illusions.hu/effectwiki/doku.php?id=linear_light_blending
"""
return numpy.clip(bottom_chan[:,:] + 2 * top_chan[:,:] - 1, 0, 1)
3
Example 45
def anim(fig, params):
global x, y, dx
t, = params
i = int(n * t / T) + 15000
# follow the current position
if i < n:
y = X[i,:]
# or unzoom at the end
else:
y *= (1 - dt)
dx = np.clip(dx + dt * (1 - dx), 0, 1)
if dx < .99:
# filter the current position to avoid "camera shaking"
x = x * (1 - dt) + dt * y
viewbox = [x[0] - dx, x[1] - dx, x[0] + dx, x[1] + dx]
# set the viewbox
fig.process_interaction('SetViewbox', viewbox)
fig.set_data(t=t)
3
Example 46
def bounded(self, value):
"""
Modify value to be a valid value for the transformation.
:param float value: Value to be bounded
:return: Value modified
"""
return np.clip(value, self.LogMin, self.LogMax)
3
Example 47
def get_bin(self, v):
if v < self.minv:
log_once("UniformDiscretizer1D: value smaller than min!")
return 0
if v > self.maxv:
log_once("UniformDiscretizer1D: value larger than max!")
return self.nr_bin - 1
return int(np.clip(
(v - self.minv) / self.spacing,
0, self.nr_bin - 1))
3
Example 48
Project: cortex Source File: euclidean.py
def make_fibrous(self, n_points=40):
y = self.rng.uniform(size=(n_points, self.X.shape[1])).astype(floatX)
for k in xrange(10):
f = self.gravity(self.X, y)
self.X += f
self.X = np.clip(self.X, 0, 1)
3
Example 49
def clip(self):
""" Clip parameters to be within bounds """
for k, bounds in IntrinsicParameters.PARAM_BOUNDS.iteritems():
v = getattr(self, k)
t = type(v)
setattr(self, k, t(np.clip(v, bounds[0], bounds[1])))
3
Example 50
def predict(self, X, feature_names=None):
if feature_names is not None:
y_pred = self.learner.predict(X, feature_names)
else:
y_pred = self.learner.predict(X)
# relevance is in [1,3]
y_pred = np.clip(y_pred, 1., 3.)
return y_pred