本文整理汇总了Python中numpy.divide方法的典型用法代码示例。如果您正苦于以下问题:Python numpy.divide方法的具体用法?Python numpy.divide怎么用?Python numpy.divide使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类numpy
的用法示例。
在下文中一共展示了numpy.divide方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: SpectralClustering
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import divide [as 别名]
def SpectralClustering(CKSym, n):
# This is direct port of JHU vision lab code. Could probably use sklearn SpectralClustering.
CKSym = CKSym.astype(float)
N, _ = CKSym.shape
MAXiter = 1000 # Maximum number of iterations for KMeans
REPlic = 20 # Number of replications for KMeans
DN = np.diag(np.divide(1, np.sqrt(np.sum(CKSym, axis=0) + np.finfo(float).eps)))
LapN = identity(N).toarray().astype(float) - np.matmul(np.matmul(DN, CKSym), DN)
_, _, vN = np.linalg.svd(LapN)
vN = vN.T
kerN = vN[:, N - n:N]
normN = np.sqrt(np.sum(np.square(kerN), axis=1))
kerNS = np.divide(kerN, normN.reshape(len(normN), 1) + np.finfo(float).eps)
km = KMeans(n_clusters=n, n_init=REPlic, max_iter=MAXiter, n_jobs=-1).fit(kerNS)
return km.labels_
示例2: compute_gradients
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import divide [as 别名]
def compute_gradients(self, loss, var_list, **kwargs):
grads_and_vars = tf.train.AdamOptimizer.compute_gradients(self, loss, var_list, **kwargs)
grads_and_vars = [(g, v) for g, v in grads_and_vars if g is not None]
flat_grad = tf.concat([tf.reshape(g, (-1,)) for g, v in grads_and_vars], axis=0)
shapes = [v.shape.as_list() for g, v in grads_and_vars]
sizes = [int(np.prod(s)) for s in shapes]
num_tasks = self.comm.Get_size()
buf = np.zeros(sum(sizes), np.float32)
def _collect_grads(flat_grad):
self.comm.Allreduce(flat_grad, buf, op=MPI.SUM)
np.divide(buf, float(num_tasks), out=buf)
return buf
avg_flat_grad = tf.py_func(_collect_grads, [flat_grad], tf.float32)
avg_flat_grad.set_shape(flat_grad.shape)
avg_grads = tf.split(avg_flat_grad, sizes, axis=0)
avg_grads_and_vars = [(tf.reshape(g, v.shape), v)
for g, (_, v) in zip(avg_grads, grads_and_vars)]
return avg_grads_and_vars
示例3: merge
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import divide [as 别名]
def merge(self, tiles: List[np.ndarray], dtype=np.float32):
if len(tiles) != len(self.crops):
raise ValueError
channels = 1 if len(tiles[0].shape) == 2 else tiles[0].shape[2]
target_shape = self.image_height + self.margin_bottom + self.margin_top, self.image_width + self.margin_right + self.margin_left, channels
image = np.zeros(target_shape, dtype=np.float64)
norm_mask = np.zeros(target_shape, dtype=np.float64)
w = np.dstack([self.weight] * channels)
for tile, (x, y, tile_width, tile_height) in zip(tiles, self.crops):
# print(x, y, tile_width, tile_height, image.shape)
image[y:y + tile_height, x:x + tile_width] += tile * w
norm_mask[y:y + tile_height, x:x + tile_width] += w
# print(norm_mask.min(), norm_mask.max())
norm_mask = np.clip(norm_mask, a_min=np.finfo(norm_mask.dtype).eps, a_max=None)
normalized = np.divide(image, norm_mask).astype(dtype)
crop = self.crop_to_orignal_size(normalized)
return crop
示例4: generate_cRM
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import divide [as 别名]
def generate_cRM(Y,S):
'''
:param Y: mixed/noisy stft
:param S: clean stft
:return: structed cRM
'''
M = np.zeros(Y.shape)
epsilon = 1e-8
# real part
M_real = np.multiply(Y[:,:,0],S[:,:,0])+np.multiply(Y[:,:,1],S[:,:,1])
square_real = np.square(Y[:,:,0])+np.square(Y[:,:,1])
M_real = np.divide(M_real,square_real+epsilon)
M[:,:,0] = M_real
# imaginary part
M_img = np.multiply(Y[:,:,0],S[:,:,1])-np.multiply(Y[:,:,1],S[:,:,0])
square_img = np.square(Y[:,:,0])+np.square(Y[:,:,1])
M_img = np.divide(M_img,square_img+epsilon)
M[:,:,1] = M_img
return M
示例5: cRM_tanh_compress
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import divide [as 别名]
def cRM_tanh_compress(M,K=10,C=0.1):
'''
Recall that the irm takes on vlaues in the range[0,1],compress the cRM with hyperbolic tangent
:param M: crm (298,257,2)
:param K: parameter to control the compression
:param C: parameter to control the compression
:return crm: compressed crm
'''
numerator = 1-np.exp(-C*M)
numerator[numerator == inf] = 1
numerator[numerator == -inf] = -1
denominator = 1+np.exp(-C*M)
denominator[denominator == inf] = 1
denominator[denominator == -inf] = -1
crm = K * np.divide(numerator,denominator)
return crm
示例6: axisangle_from_rotm
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import divide [as 别名]
def axisangle_from_rotm(R):
# logarithm of rotation matrix
# R = R.reshape(-1,3,3)
# tr = np.trace(R, axis1=1, axis2=2)
# phi = np.arccos(np.clip((tr - 1) / 2, -1, 1))
# scale = np.zeros_like(phi)
# div = 2 * np.sin(phi)
# np.divide(phi, div, out=scale, where=np.abs(div) > 1e-6)
# A = (R - R.transpose(0,2,1)) * scale.reshape(-1,1,1)
# aa = np.stack((A[:,2,1], A[:,0,2], A[:,1,0]), axis=1)
# return aa.squeeze()
R = R.reshape(-1,3,3)
omega = np.empty((R.shape[0], 3), dtype=R.dtype)
omega[:,0] = R[:,2,1] - R[:,1,2]
omega[:,1] = R[:,0,2] - R[:,2,0]
omega[:,2] = R[:,1,0] - R[:,0,1]
r = np.linalg.norm(omega, axis=1).reshape(-1,1)
t = np.trace(R, axis1=1, axis2=2).reshape(-1,1)
omega = np.arctan2(r, t-1) * omega
aa = np.zeros_like(omega)
np.divide(omega, r, out=aa, where=r != 0)
return aa.squeeze()
示例7: test_NotImplemented_not_returned
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import divide [as 别名]
def test_NotImplemented_not_returned(self):
# See gh-5964 and gh-2091. Some of these functions are not operator
# related and were fixed for other reasons in the past.
binary_funcs = [
np.power, np.add, np.subtract, np.multiply, np.divide,
np.true_divide, np.floor_divide, np.bitwise_and, np.bitwise_or,
np.bitwise_xor, np.left_shift, np.right_shift, np.fmax,
np.fmin, np.fmod, np.hypot, np.logaddexp, np.logaddexp2,
np.logical_and, np.logical_or, np.logical_xor, np.maximum,
np.minimum, np.mod,
np.greater, np.greater_equal, np.less, np.less_equal,
np.equal, np.not_equal]
a = np.array('1')
b = 1
c = np.array([1., 2.])
for f in binary_funcs:
assert_raises(TypeError, f, a, b)
assert_raises(TypeError, f, c, a)
示例8: test_warnings
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import divide [as 别名]
def test_warnings(self):
# test warning code path
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
with np.errstate(all="warn"):
np.divide(1, 0.)
assert_equal(len(w), 1)
assert_("divide by zero" in str(w[0].message))
np.array(1e300) * np.array(1e300)
assert_equal(len(w), 2)
assert_("overflow" in str(w[-1].message))
np.array(np.inf) - np.array(np.inf)
assert_equal(len(w), 3)
assert_("invalid value" in str(w[-1].message))
np.array(1e-300) * np.array(1e-300)
assert_equal(len(w), 4)
assert_("underflow" in str(w[-1].message))
示例9: test_td64arr_rmul_numeric_array
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import divide [as 别名]
def test_td64arr_rmul_numeric_array(self, box_with_array, vector, dtype):
# GH#4521
# divide/multiply by integers
xbox = get_upcast_box(box_with_array, vector)
tdser = pd.Series(['59 Days', '59 Days', 'NaT'], dtype='m8[ns]')
vector = vector.astype(dtype)
expected = Series(['1180 Days', '1770 Days', 'NaT'],
dtype='timedelta64[ns]')
tdser = tm.box_expected(tdser, box_with_array)
expected = tm.box_expected(expected, xbox)
result = tdser * vector
tm.assert_equal(result, expected)
result = vector * tdser
tm.assert_equal(result, expected)
示例10: planck
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import divide [as 别名]
def planck(f, T):
"""Calculate black body radiation for given frequency and temperature.
Parameters:
f (float or ndarray): Frquencies [Hz].
T (float or ndarray): Temperature [K].
Returns:
float or ndarray: Radiances.
"""
c = constants.speed_of_light
h = constants.planck
k = constants.boltzmann
return 2 * h * f**3 / (c**2 * (np.exp(np.divide(h * f, (k * T))) - 1))
示例11: planck_wavelength
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import divide [as 别名]
def planck_wavelength(l, T):
"""Calculate black body radiation for given wavelength and temperature.
Parameters:
l (float or ndarray): Wavelength [m].
T (float or ndarray): Temperature [K].
Returns:
float or ndarray: Radiances.
"""
c = constants.speed_of_light
h = constants.planck
k = constants.boltzmann
return 2 * h * c**2 / (l**5 * (np.exp(np.divide(h * c, (l * k * T))) - 1))
示例12: planck_wavenumber
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import divide [as 别名]
def planck_wavenumber(n, T):
"""Calculate black body radiation for given wavenumber and temperature.
Parameters:
n (float or ndarray): Wavenumber.
T (float or ndarray): Temperature [K].
Returns:
float or ndarray: Radiances.
"""
c = constants.speed_of_light
h = constants.planck
k = constants.boltzmann
return 2 * h * c**2 * n**3 / (np.exp(np.divide(h * c * n, (k * T))) - 1)
示例13: rayleighjeans_wavelength
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import divide [as 别名]
def rayleighjeans_wavelength(l, T):
"""Calculates the Rayleigh-Jeans approximation of the Planck function.
Calculates the approximation of the Planck function for given
wavelength and temperature.
Parameters:
l (float or ndarray): Wavelength [m].
T (float or ndarray): Temperature [K].
Returns:
float or ndarray: Radiance [W/(m2*Hz*sr)].
"""
c = constants.speed_of_light
k = constants.boltzmann
return np.divide(2 * c * k * T, l**4)
示例14: unitvec
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import divide [as 别名]
def unitvec(vector, ax=1):
v=vector*vector
if len(vector.shape)==1:
sqrtv=np.sqrt(np.sum(v))
elif len(vector.shape)==2:
sqrtv=np.sqrt([np.sum(v, axis=ax)])
else:
raise Exception('It\'s too large.')
if ax==1:
result=np.divide(vector,sqrtv.T)
elif ax==0:
result=np.divide(vector,sqrtv)
return result
示例15: test_evaluate
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import divide [as 别名]
def test_evaluate(self):
(average_precision_per_class, mean_ap, precisions_per_class,
recalls_per_class, corloc_per_class,
mean_corloc) = self.od_eval.evaluate()
expected_precisions_per_class = [np.array([0, 0.5], dtype=float),
np.array([], dtype=float),
np.array([0], dtype=float)]
expected_recalls_per_class = [
np.array([0, 1. / 3.], dtype=float), np.array([], dtype=float),
np.array([0], dtype=float)
]
expected_average_precision_per_class = np.array([1. / 6., 0, 0],
dtype=float)
expected_corloc_per_class = np.array([0, np.divide(0, 0), 0], dtype=float)
expected_mean_ap = 1. / 18
expected_mean_corloc = 0.0
for i in range(self.od_eval.num_class):
self.assertTrue(np.allclose(expected_precisions_per_class[i],
precisions_per_class[i]))
self.assertTrue(np.allclose(expected_recalls_per_class[i],
recalls_per_class[i]))
self.assertTrue(np.allclose(expected_average_precision_per_class,
average_precision_per_class))
self.assertTrue(np.allclose(expected_corloc_per_class, corloc_per_class))
self.assertAlmostEqual(expected_mean_ap, mean_ap)
self.assertAlmostEqual(expected_mean_corloc, mean_corloc)