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
]
# These functions still return NotImplemented. Will be fixed in
# future.
# bad = [np.greater, np.greater_equal, np.less, np.less_equal, np.not_equal]
a = np.array('1')
b = 1
for f in binary_funcs:
assert_raises(TypeError, f, a, b)
python类true_divide()的实例源码
def test_zero_safe_divide(self):
from blmath.numerics.operations import zero_safe_divide
numerator = np.ones((5, 5))
numerator[3, 3] = 0.
denominator = np.ones((5, 5))
denominator[2, 2] = 0.
denominator[3, 3] = 0.
with warnings.catch_warnings():
warnings.simplefilter("ignore", RuntimeWarning)
true_divide = np.true_divide(numerator, denominator)
safe_divide = zero_safe_divide(numerator, denominator)
self.assertTrue(np.isinf(true_divide[2, 2]))
self.assertEqual(safe_divide[2, 2], 0.)
self.assertTrue(np.isnan(true_divide[3, 3]))
self.assertEqual(safe_divide[3, 3], 0.)
def zero_safe_divide(a, b, default_error_value=0.):
"""Element-wise division that accounts for floating point errors.
Both invalid floating-point (e.g. 0. / 0.) and divide be zero errors are
suppressed. Resulting values (NaN and Inf respectively) are replaced with
`default_error_value`.
"""
import numpy as np
with np.errstate(invalid='ignore', divide='ignore'):
quotient = np.true_divide(a, b)
bad_value_indices = np.logical_or(
np.isnan(quotient), np.isinf(quotient))
quotient[bad_value_indices] = default_error_value
return quotient
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
]
# These functions still return NotImplemented. Will be fixed in
# future.
# bad = [np.greater, np.greater_equal, np.less, np.less_equal, np.not_equal]
a = np.array('1')
b = 1
for f in binary_funcs:
assert_raises(TypeError, f, a, b)
def V_short(self,eta):
sum0 = np.zeros(7,dtype=float)
sum1 = np.zeros(7,dtype=float)
for n1,n2 in product(range(self.N1+1),range(self.N2+1)):
wdo = comb(self.N1,n1,exact=True)*comb(self.N2,n2,exact=True)
wdox10 = comb(self.N1-1,n1,exact=True)*comb(self.N2,n2,exact=True)
wdox11 = comb(self.N1-1,n1-1,exact=True)*comb(self.N2,n2,exact=True)
wdox20 = comb(self.N1,n1,exact=True)*comb(self.N2-1,n2,exact=True)
wdox21 = comb(self.N1,n1,exact=True)*comb(self.N2-1,n2-1,exact=True)
w = np.asarray([wdox10,wdox20,wdox11,wdox21,wdo,wdo,wdo])
pz0,pz1 = self.p_n_given_z(n1,n2)
counts = [self.N1-n1,self.N2-n2,n1,n2,1,1,1]
Q = (eta*pz0*counts*(1-self.pZgivenA)+eta*pz1*counts*self.pZgivenA).sum()
ratio = np.nan_to_num(np.true_divide(pz0*(1-self.pZgivenA)+pz1*self.pZgivenA,Q))
sum0 += np.asfarray(w*pz0*ratio)
sum1 += np.asfarray(w*pz1*ratio)
result = self.pZgivenA*sum1+(1-self.pZgivenA)*sum0
return result
def run(self,T,model):
if T <= model.K: # result is not defined if the horizon is shorter than the number of actions
self.best_action = None
return np.nan
actions = range(0,model.K)
self.trials = np.ones(model.K)
self.success = model.sample_multiple(actions,1)
for t in range(model.K,T):
arm = argmax_rand(self.upper_bound(t))
self.trials[arm] += 1
self.success[arm] +=model.sample_multiple(arm,1)
mu = np.true_divide(self.success,self.trials)
self.best_action = argmax_rand(mu)
return max(model.expected_rewards) - model.expected_rewards[self.best_action]
def fit(self, x, y, verbose=True):
#setting data attributes for the model instance
X = tfidf_to_counts(x)
#splitting by target class so we can calculate the log-count ratio
X_pos = X[np.where(y == 1)]
X_neg = X[np.where(y == 0)]
self.r = log_count_ratio(X_pos, X_neg)
#setting the npos and nneg variables
n_pos = X_pos.shape[0]
n_neg = X_neg.shape[0]
#getting the bais for the MNB model
self.nb_bias = np.log(np.true_divide(n_pos, n_neg))
#trains, tests, and assesses the performance of the model
test_ufunc.py 文件源码
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda
作者: SignalMedia
项目源码
文件源码
阅读 26
收藏 0
点赞 0
评论 0
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
]
# These functions still return NotImplemented. Will be fixed in
# future.
# bad = [np.greater, np.greater_equal, np.less, np.less_equal, np.not_equal]
a = np.array('1')
b = 1
for f in binary_funcs:
assert_raises(TypeError, f, a, b)
core.py 文件源码
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda
作者: SignalMedia
项目源码
文件源码
阅读 27
收藏 0
点赞 0
评论 0
def __itruediv__(self, other):
"""
True divide self by other in-place.
"""
other_data = getdata(other)
dom_mask = _DomainSafeDivide().__call__(self._data, other_data)
other_mask = getmask(other)
new_mask = mask_or(other_mask, dom_mask)
# The following 3 lines control the domain filling
if dom_mask.any():
(_, fval) = ufunc_fills[np.true_divide]
other_data = np.where(dom_mask, fval, other_data)
self._mask |= new_mask
self._data.__itruediv__(np.where(self._mask, self.dtype.type(1),
other_data))
return self
def load_files(avg_file, std_file):
# load files
with open(avg_file) as f:
avg = simplejson.load(f)
with open(std_file) as f:
std = simplejson.load(f)
std = np.array(std)
print std
std = np.true_divide(std, 2.)
print std
avg = np.array(avg)
avg_upper = avg + std
avg_lower = avg - std
return avg, avg_upper, avg_lower
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
]
# These functions still return NotImplemented. Will be fixed in
# future.
# bad = [np.greater, np.greater_equal, np.less, np.less_equal, np.not_equal]
a = np.array('1')
b = 1
for f in binary_funcs:
assert_raises(TypeError, f, a, b)
def __itruediv__(self, other):
"""
True divide self by other in-place.
"""
other_data = getdata(other)
dom_mask = _DomainSafeDivide().__call__(self._data, other_data)
other_mask = getmask(other)
new_mask = mask_or(other_mask, dom_mask)
# The following 3 lines control the domain filling
if dom_mask.any():
(_, fval) = ufunc_fills[np.true_divide]
other_data = np.where(dom_mask, fval, other_data)
self._mask |= new_mask
self._data.__itruediv__(np.where(self._mask, self.dtype.type(1),
other_data))
return self
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
]
# These functions still return NotImplemented. Will be fixed in
# future.
# bad = [np.greater, np.greater_equal, np.less, np.less_equal, np.not_equal]
a = np.array('1')
b = 1
for f in binary_funcs:
assert_raises(TypeError, f, a, b)
def __itruediv__(self, other):
"""
True divide self by other in-place.
"""
other_data = getdata(other)
dom_mask = _DomainSafeDivide().__call__(self._data, other_data)
other_mask = getmask(other)
new_mask = mask_or(other_mask, dom_mask)
# The following 3 lines control the domain filling
if dom_mask.any():
(_, fval) = ufunc_fills[np.true_divide]
other_data = np.where(dom_mask, fval, other_data)
self._mask |= new_mask
self._data.__itruediv__(np.where(self._mask, self.dtype.type(1),
other_data))
return self
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
]
# These functions still return NotImplemented. Will be fixed in
# future.
# bad = [np.greater, np.greater_equal, np.less, np.less_equal, np.not_equal]
a = np.array('1')
b = 1
for f in binary_funcs:
assert_raises(TypeError, f, a, b)
def __itruediv__(self, other):
"""
True divide self by other in-place.
"""
other_data = getdata(other)
dom_mask = _DomainSafeDivide().__call__(self._data, other_data)
other_mask = getmask(other)
new_mask = mask_or(other_mask, dom_mask)
# The following 3 lines control the domain filling
if dom_mask.any():
(_, fval) = ufunc_fills[np.true_divide]
other_data = np.where(dom_mask, fval, other_data)
self._mask |= new_mask
self._data.__itruediv__(np.where(self._mask, self.dtype.type(1),
other_data))
return self
def _entropy(self, y, return_class_counts=False):
""" Entropy for the classes in the array y
:math: \sum_{x \in X} p(x) \log_{2}(1/p(x)) :math: from
https://en.wikipedia.org/wiki/ID3_algorithm
Parameters
----------
y : nparray of shape [n remaining attributes]
containing the class names
Returns
-------
: float
information for remaining examples given feature
"""
n = y.shape[0]
if n <= 0:
return 0
classes, count = unique(y)
p = np.true_divide(count, n)
res = np.abs(np.sum(np.multiply(p, np.log2(p))))
if return_class_counts:
return res, np.vstack((classes, count)).T
else:
return res
def _info_nominal(self, x, y):
""" Info for nominal feature feature_values
:math: p(a)H(a) :math: from
https://en.wikipedia.org/wiki/ID3_algorithm
Parameters
----------
x : np.array of shape [n remaining examples]
containing feature values
y : np.array of shape [n remaining examples]
containing relevent class
Returns
-------
: float
information for remaining examples given feature
"""
info = 0
n = x.shape[0]
items, count = unique(x)
for value, p in zip(items, count):
info += p * self._entropy(y[x == value])
return CalcRecord(CalcRecord.NOM,
info * np.true_divide(1, n),
attribute_counts=count)
def bilinearResize(images, ratiox, ratioy):
'''
images: 4D image batch
ratiox, ratioy: magnification ratio. Positive integer.
'''
b, h, w, c = [v.value for v in images.get_shape()]
sidex = 2 * ratiox - 1
sidey = 2 * ratioy - 1
interpolatex = np.true_divide((ratiox - np.abs(np.arange(sidex) - ratiox + 1)), ratiox)
interpolatey = np.true_divide((ratioy - np.abs(np.arange(sidey) - ratioy + 1)), ratioy)
weight = np.outer(interpolatex, interpolatey).astype(np.float32)
weights = np.zeros((sidex,sidey,c,c), dtype=np.float32)
for i in range(c):
weights[:,:,i,i] = weight
out_shape = [b, h*ratiox, w*ratioy, c]
strides = [1, ratiox, ratioy, 1]
kernel = tf.constant(weights, name='bilinear_convt_weights')
return tf.nn.conv2d_transpose(images, weights,
out_shape, strides=strides, padding='SAME')
def test_cumsum(mock_np, arr, normalize, expected_result):
mock_np.cumsum = mock.Mock(side_effect = lambda *a, **k: np.cumsum(*a, **k))
mock_np.square = mock.Mock(side_effect = lambda *a, **k: np.square(*a, **k))
mock_np.max = mock.Mock(side_effect = lambda *a, **k: np.max(*a, **k))
# mock_np.true_divide = mock.Mock(side_effect = lambda *a, **k: np.true_divide(*a, **k))
mock_np.isnan = mock.Mock(side_effect = lambda *a, **k: np.isnan(*a, **k))
r = cumsum(arr, normalize=normalize)
assert len(r) == len(arr)
assert (r == np.array(expected_result)).all()
assert mock_np.cumsum.called
assert mock_np.square.called
assert mock_np.isnan.called == normalize
assert mock_np.max.called == normalize
# if normalize:
# assert mock_np.isnan.called
# assert mock_np.max.called
# assert mock_np.true_divide.called
# else:
# assert not mock_np.max.called
# assert not mock_np.true_divide.called
def Quadrify(contour):
epsilon = 10
for i in range(1,10):
quad = cv2.approxPolyDP(contour, epsilon, True)
length = len(quad)
randomVar = np.random.random()
epsilon = np.multiply(epsilon, np.true_divide(np.add(length, randomVar), np.add(4, randomVar)))
# print epsilon, length
if length == 4:
return np.multiply(i, 0.01)
return 1
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
]
# These functions still return NotImplemented. Will be fixed in
# future.
# bad = [np.greater, np.greater_equal, np.less, np.less_equal, np.not_equal]
a = np.array('1')
b = 1
for f in binary_funcs:
assert_raises(TypeError, f, a, b)
def test_true_divide(self):
# True_divide has a non uniform signature, see #3484.
# This also tests type_tuple_type_resolver.
a = np.full(5, 12.5)
b = np.full(5, 10.0)
tgt = np.full(5, 1.25)
assert_almost_equal(np.true_divide(a, b, dtype=np.float64), tgt)
assert_almost_equal(np.true_divide(a, b, dtype=np.float32), tgt)
assert_raises(TypeError, np.true_divide, a, b, dtype=np.int)
def _hist_bin_doane(x):
"""
Doane's histogram bin estimator.
Improved version of Sturges' formula which works better for
non-normal data. See
http://stats.stackexchange.com/questions/55134/doanes-formula-for-histogram-binning
Parameters
----------
x : array_like
Input data that is to be histogrammed, trimmed to range. May not
be empty.
Returns
-------
h : An estimate of the optimal bin width for the given data.
"""
if x.size > 2:
sg1 = np.sqrt(6.0 * (x.size - 2) / ((x.size + 1.0) * (x.size + 3)))
sigma = np.std(x)
if sigma > 0.0:
# These three operations add up to
# g1 = np.mean(((x - np.mean(x)) / sigma)**3)
# but use only one temp array instead of three
temp = x - np.mean(x)
np.true_divide(temp, sigma, temp)
np.power(temp, 3, temp)
g1 = np.mean(temp)
return x.ptp() / (1.0 + np.log2(x.size) +
np.log2(1.0 + np.absolute(g1) / sg1))
return 0.0
def __truediv__(self, other):
"""
Divide other into self, and return a new masked array.
"""
if self._delegate_binop(other):
return NotImplemented
return true_divide(self, other)
def __rtruediv__(self, other):
"""
Divide self into other, and return a new masked array.
"""
return true_divide(other, self)
def divide(x, y):
with np.errstate(divide='ignore', invalid='ignore'):
z = np.true_divide(x, y)
z[~ np.isfinite(z)] = 0
return z
def __truediv__(self, other):
return true_divide(self, other)
def __itruediv__(self, other):
return true_divide(self, other, self)
def __rtruediv__(self, other):
return true_divide(other, self)