def mu_law(x, mu=255, int8=False):
"""A TF implementation of Mu-Law encoding.
Args:
x: The audio samples to encode.
mu: The Mu to use in our Mu-Law.
int8: Use int8 encoding.
Returns:
out: The Mu-Law encoded int8 data.
"""
out = tf.sign(x) * tf.log(1 + mu * tf.abs(x)) / np.log(1 + mu)
out = tf.floor(out * 128)
if int8:
out = tf.cast(out, tf.int8)
return out
python类sign()的实例源码
def validate_and_normalize(self, obj, value):
rounded_value = FloatRegister.validate_and_normalize(self, obj, value)
if rounded_value == 0 and value != 0: # value was rounded off to zero
if self.avoid_round_off_to_zero:
rounded_value = FloatRegister.validate_and_normalize(
self, obj, np.abs(self.increment)*np.sign(value))
obj._logger.warning("Avoided rounding value %.1e of the "
"gain register %s to zero. Setting it to %.1e "
"instead. ", value, self.name, rounded_value)
else:
obj._logger.warning("Rounding value %.1e of the "
"gain register %s to zero. ", value, self.name)
if value > self.max or value < self.min:
obj._logger.warning("Requested gain for %s.%s is outside the "
"bounds allowed by the hardware. Desired "
"gain of %.1e is capped to %.1e. ",
obj.name, self.name, value, rounded_value)
return rounded_value
def expect_margin(predictions:np.ndarray,answer:np.ndarray):
predict_sign=np.sign(predictions)
answer_sign = np.sign(answer)
margin_array=[]
for m in range(answer.shape[0]):
row=[]
for n in range(answer.shape[1]):
a=answer[m,n]
p = predictions[m,n]
p_s=predict_sign[m,n]
a_s=answer_sign[m,n]
if p_s==a_s :
row.append(min(abs(a),abs(p)))
# elif p_s!=a_s or p==0:
# row.append(-1*(abs(a)+abs(p)))
else:
#row.append(-1*abs(a))
row.append(-1 * (abs(a) + abs(p)))
margin_array.append(row)
margin_array=np.array(margin_array)
return np.sum(margin_array,0)
mk_ls_svm.py 文件源码
项目:MultipleKernel-LeastSquares-SuportVectorMachine
作者: FormMe
项目源码
文件源码
阅读 20
收藏 0
点赞 0
评论 0
def predict(self, data):
'''Perform classification on samples in data.
:param data: array-like, shape = [n_samples, n_features]
:return target: array-like, shape = [n_samples]
Class labels for samples in data.
'''
def y_prediction(z):
support_vectors_sum = sum([alpha * y *
sum([beta * K.compute(z, x) for beta, K in zip(self.beta, self.kernel_set)])
for alpha, x, y in zip(self.alpha, self.__Xfit, self.__Yfit)])
p = support_vectors_sum + self.b
if p == 0.0:
p = 1.0;
return self.class_dict[str(numpy.sign(p))]
if not self.fited:
raise Exception("Fit classificator before.")
return [y_prediction(test_x) for test_x in data]
def quatFromRotMatx(R):
"""Get a quaternion from a given rotation matrix `R`."""
q = np.zeros(4)
q[0] = ( R[0,0] + R[1,1] + R[2,2] + 1) / 4.0
q[1] = ( R[0,0] - R[1,1] - R[2,2] + 1) / 4.0
q[2] = (-R[0,0] + R[1,1] - R[2,2] + 1) / 4.0
q[3] = (-R[0,0] - R[1,1] + R[2,2] + 1) / 4.0
q[q<0] = 0 # Avoid complex number by numerical error.
q = np.sqrt(q)
q[1] *= np.sign(R[2,1] - R[1,2])
q[2] *= np.sign(R[0,2] - R[2,0])
q[3] *= np.sign(R[1,0] - R[0,1])
return q
def leftOrRight(p,l1,l2):
return np.sign((l2[0] - l1[0]) * (p[1] - l1[1]) - (l2[1] - l1[1]) * (p[0] - l1[0]))
def soft_thresh(r, w):
return np.sign(w) * np.max(np.abs(w)-r, 0)
atari_wrappers_deprecated.py 文件源码
项目:distributional_perspective_on_RL
作者: Kiwoo
项目源码
文件源码
阅读 26
收藏 0
点赞 0
评论 0
def _reward(self, reward):
"""Change all the positive rewards to 1, negative to -1 and keep zero."""
return np.sign(reward)
RankOrderedAutoencoder.py 文件源码
项目:rank-ordered-autoencoder
作者: paulbertens
项目源码
文件源码
阅读 34
收藏 0
点赞 0
评论 0
def derivative(self, X, Y):
return (np.sign(Y) != np.sign(X))
def normalize_hist(hist, norm_method='global-l2'):
"""
Various normalization methods
Refer to:
[1] Improving the Fisher Kernel for Large-Scale Image Classifcation, Perronnin et al
http://www.robots.ox.ac.uk/~vgg/rg/papers/peronnin_etal_ECCV10.pdf
[2] Segmentation Driven Object Detection with Fisher Vectors, Cinbis et al
"""
# Component-wise mass normalization
if norm_method == 'component-wise-mass':
raise NotImplementedError('Component-wise-mass normalization_method not implemented')
# Component-wise L2 normalization
elif norm_method == 'component-wise-l2':
return hist / np.max(np.linalg.norm(hist, axis=1), 1e-12)
# Global L2 normalization
elif norm_method == 'global-l2':
return hist / (np.linalg.norm(hist) + 1e-12)
# Square rooting / Power Normalization with alpha = 0.5
elif norm_method == 'square-rooting':
# Power-normalization followed by L2 normalization as in [2]
hist = np.sign(hist) * np.sqrt(np.fabs(hist))
return hist / (np.linalg.norm(hist) + 1e-12)
else:
raise NotImplementedError('Unknown normalization_method %s' % norm_method)
def demo_plot_stdp(kp=0.1, kd=2):
t=np.arange(-100, 101)
r = kd/float(kp+kd)
kbb = r**(np.abs(t))
k_classic = kbb*np.sign(t)
plt.figure(figsize=(6, 2))
with hstack_plots(spacing=0.1, bottom=0.1, left=0.05, right=0.98, xlabel='$t_{post}-t_{pre}$', ylabel='$\Delta w$', sharex=False, sharey=False, show_x=False, remove_ticks=False, grid=True):
ax=add_subplot()
plt.plot(t, -kbb)
plt.title('$sign(\\bar x_t)=sign(\\bar e_t)$')
plt.xlabel('$t_{post}-t_{pre}$')
add_subplot()
plt.plot(t, kbb)
plt.title('$sign(\\bar x_t)\\neq sign(\\bar e_t)$')
add_subplot()
plt.title('Classic STDP Rule')
plt.plot(t, k_classic)
ax.tick_params(axis='y', labelleft='off')
ax.tick_params(axis='x', labelbottom='off')
plt.show()
def initialize(self, es):
"""late initialization using attributes ``N`` and ``popsize``"""
r = es.sp.weights.mueff / es.popsize
self.index_to_compare = 0.5 * (r**0.5 + 2.0 * (1 - r**0.5) / np.log(es.N + 9)**2) * (es.popsize) # TODO
self.index_to_compare = 0.30 * es.popsize # TODO
self.damp = 2 - 2 / es.N # sign-rule: 2
self.c = 0.3 # sign-rule needs <= 0.3
self.s = 0 # averaged statistics, usually between -1 and +1
def update(self, es, **kwargs):
if es.countiter < 2:
self.initialize(es)
self.fit = es.fit.fit
else:
ft1, ft2 = self.fit[int(self.index_to_compare)], self.fit[int(np.ceil(self.index_to_compare))]
ftt1, ftt2 = es.fit.fit[(es.popsize - 1) // 2], es.fit.fit[int(np.ceil((es.popsize - 1) / 2))]
pt2 = self.index_to_compare - int(self.index_to_compare)
# ptt2 = (es.popsize - 1) / 2 - (es.popsize - 1) // 2 # not in use
s = 0
if 1 < 3:
s += pt2 * sum(es.fit.fit <= self.fit[int(np.ceil(self.index_to_compare))])
s += (1 - pt2) * sum(es.fit.fit < self.fit[int(self.index_to_compare)])
s -= es.popsize / 2.
s *= 2. / es.popsize # the range was popsize, is 2
elif 11 < 3: # compare ft with median of ftt
s += self.index_to_compare - sum(self.fit <= es.fit.fit[es.popsize // 2])
s *= 2 / es.popsize # the range was popsize, is 2
else: # compare ftt j-index of ft
s += (1 - pt2) * np.sign(ft1 - ftt1)
s += pt2 * np.sign(ft2 - ftt1)
self.s = (1 - self.c) * self.s + self.c * s
es.sigma *= np.exp(self.s / self.damp)
# es.more_to_write.append(10**(self.s))
#es.more_to_write.append(10**((2 / es.popsize) * (sum(es.fit.fit < self.fit[int(self.index_to_compare)]) - (es.popsize + 1) / 2)))
# # es.more_to_write.append(10**(self.index_to_compare - sum(self.fit <= es.fit.fit[es.popsize // 2])))
# # es.more_to_write.append(10**(np.sign(self.fit[int(self.index_to_compare)] - es.fit.fit[es.popsize // 2])))
if 11 < 3:
import scipy.stats.stats as stats
zkendall = stats.kendalltau(list(es.fit.fit) + list(self.fit),
len(es.fit.fit) * [0] + len(self.fit) * [1])[0]
es.more_to_write.append(10**zkendall)
self.fit = es.fit.fit
def update(self, es, function_values, **kwargs):
"""the first and second value in ``function_values``
must reflect two mirrored solutions.
Mirrored solutions must have been sampled
in direction / in opposite direction of
the previous mean shift, respectively.
"""
# On the linear function, the two mirrored samples lead
# to a sharp increase of the condition of the covariance matrix,
# unless we have negative weights (which we have now by default).
# Otherwise they should not be used to update the covariance
# matrix, if the step-size inreases quickly.
if self.initialized is not True: # try again
self.initialize(es.N, es.opts)
if self.initialized is not True:
utils.print_warning("dimension not known, damping set to 4",
'update', 'CMAAdaptSigmaTPA')
self.initialized = True
if 1 < 3:
f_vals = function_values
z = sum(f_vals < f_vals[1]) - sum(f_vals < f_vals[0])
z /= len(f_vals) - 1 # z in [-1, 1]
elif 1 < 3:
# use the ranking difference of the mirrors for adaptation
# damp = 5 should be fine
z = np.nonzero(es.fit.idx == 1)[0][0] - np.nonzero(es.fit.idx == 0)[0][0]
z /= es.popsize - 1 # z in [-1, 1]
self.s = (1 - self.sp.c) * self.s + self.sp.c * np.sign(z) * np.abs(z)**self.sp.z_exponent
if self.s > 0:
es.sigma *= np.exp(self.s / self.sp.dampup)
else:
es.sigma *= np.exp(self.s / self.sp.dampdown)
#es.more_to_write.append(10**z)
def defaultboundaryhandling(x, fac):
"""Returns a float penalty for being outside of boundaries [-5, 5]"""
xoutside = np.maximum(0., np.abs(x) - 5) * sign(x)
fpen = fac * np.sum(xoutside**2, -1) # penalty
return fpen
def initwithsize(self, curshape, dim):
# DIM-dependent initialization
if self.dim != dim:
if self.zerox:
self.xopt = zeros(dim) # TODO: what happens here?
else:
self.xopt = 5 * sign(compute_xopt(self.rseed, dim))
self.scales = -sign(self.xopt) * (self.alpha ** .5) ** linspace(0, 1, dim)
# DIM- and POPSI-dependent initialisations of DIM*POPSI matrices
if self.lastshape != curshape:
self.dim = dim
self.lastshape = curshape
self.arrxopt = resize(self.xopt, curshape)
def _evalfull(self, x):
fadd = self.fopt
curshape, dim = self.shape_(x)
# it is assumed x are row vectors
if self.lastshape != curshape:
self.initwithsize(curshape, dim)
fadd = fadd + 5 * np.sum(np.abs(self.scales))
# BOUNDARY HANDLING
# move "too" good coordinates back into domain
x = np.array(x) # convert x and make a copy of x.
# The following may modify x directly.
idx_out_of_bounds = (x * self.arrxopt) > 25 # 25 == 5 * 5
x[idx_out_of_bounds] = sign(x[idx_out_of_bounds]) * 5
# TRANSFORMATION IN SEARCH SPACE
# COMPUTATION core
ftrue = dot(x, self.scales)
fval = self.noise(ftrue)
# FINALIZE
ftrue += fadd
fval += fadd
return fval, ftrue
def _evalfull(self, x):
fadd = self.fopt
curshape, dim = self.shape_(x)
# it is assumed x are row vectors
if self.lastshape != curshape:
self.initwithsize(curshape, dim)
# BOUNDARY HANDLING
xoutside = np.maximum(0, np.abs(x) - 5.) * sign(x)
fpen = (10. / dim) * np.sum(xoutside ** 2, -1)
fadd = fadd + fpen
# TRANSFORMATION IN SEARCH SPACE
x = x - self.arrxopt # cannot be replaced with x -= arrxopt!
x = dot(x, self.rotation)
x = monotoneTFosc(x)
x = dot(x, self.linearTF)
# COMPUTATION core
if len(curshape) < 2: # popsize is one
ftrue = np.sum(dot(self.aK, np.cos(dot(self.bK.T, 2 * np.pi * (np.reshape(x, (1, len(x))) + 0.5)))))
else:
ftrue = np.zeros(curshape[0]) # curshape[0] is popsize
for k, i in enumerate(x):
# TODO: simplify next line
ftrue[k] = np.sum(dot(self.aK, np.cos(dot(self.bK.T, 2 * np.pi * (np.reshape(i, (1, len(i))) + 0.5)))))
ftrue = 10. * (ftrue / dim - self.f0) ** 3
try:
ftrue = np.hstack(ftrue)
except TypeError:
pass
fval = self.noise(ftrue)
# FINALIZE
ftrue += fadd
fval += fadd
return fval, ftrue
def _evalfull(self, x):
fadd = self.fopt
curshape, dim = self.shape_(x)
# it is assumed x are row vectors
if self.lastshape != curshape:
self.initwithsize(curshape, dim)
# TRANSFORMATION IN SEARCH SPACE
x = 2 * self.arrsigns * x # makes the below boundary handling effective for coordinates
try:
x[:, 1:] = x[:, 1:] + .25 * (x[:, :-1] - self.arrxopt[:, :-1])
except IndexError:
x[1:] = x[1:] + .25 * (x[:-1] - self.arrxopt[:-1])
x = 100. * (self.arrscales * (x - self.arrxopt) + self.arrxopt)
# BOUNDARY HANDLING
xoutside = np.maximum(0., np.abs(x) - 500.) * sign(x) # in [-500, 500]
fpen = 0.01 * np.sum(xoutside ** 2, -1)
fadd = fadd + fpen
# COMPUTATION core
ftrue = 0.01 * ((418.9828872724339) - np.mean(x * np.sin(np.sqrt(np.abs(x))), -1))
fval = self.noise(ftrue)
# FINALIZE
ftrue += fadd
fval += fadd
return fval, ftrue
def _evalfull(self, x):
fadd = self.fopt
curshape, dim = self.shape_(x)
# it is assumed x are row vectors
if self.lastshape != curshape:
self.initwithsize(curshape, dim)
# BOUNDARY HANDLING
xoutside = np.maximum(0, np.abs(x) - 5.) * sign(x)
fpen = 1e4 * np.sum(xoutside ** 2, -1)
fadd = fadd + fpen
# TRANSFORMATION IN SEARCH SPACE
x = self.arrscales * x
# COMPUTATION core
s = 1 - .5 / ((dim + 20)**0.5 - 4.1) # tested up to DIM = 160 p in [0.25,0.33]
d = 1 # shift [1,3], smaller is more difficult
mu2 = -((self._mu1 ** 2 - d) / s) ** .5
ftrue = np.minimum(np.sum((x - self._mu1) ** 2, -1),
d * dim + s * np.sum((x - mu2) ** 2, -1))
ftrue = ftrue + 10 * (dim - np.sum(np.cos(2 * np.pi * dot(x - self._mu1, self.linearTF)), -1))
fval = self.noise(ftrue)
# FINALIZE
ftrue += fadd
fval += fadd
return fval, ftrue
# dictbbob = {'sphere': F1, 'ellipsoid': F2, 'Rastrigin': F3}