def unknown_feature_extractor(x, sr, win_len, shift_len, barks, inner_win, inner_shift, win_type, method_version):
x_spectrum = stft_extractor(x, win_len, shift_len, win_type)
coef = get_fft_bark_mat(sr, win_len, barks, 20, sr//2)
bark_spect = np.matmul(coef, x_spectrum)
ams = np.zeros((barks, inner_win//2+1, (bark_spect.shape[1] - inner_win)//inner_shift))
for i in range(barks):
channel_stft = stft_extractor(bark_spect[i, :], inner_win, inner_shift, 'hanning')
if method_version == 'v1':
ams[i, :, :] = 20 * np.log(np.abs(channel_stft[:inner_win//2+1, :(bark_spect.shape[1] - inner_win)//inner_shift]))
elif method_version == 'v2':
channel_amplitude = np.abs(channel_stft[:inner_win//2+1, :(bark_spect.shape[1] - inner_win)//inner_shift])
channel_angle = np.angle(channel_stft[:inner_win//2+1, :(bark_spect.shape[1] - inner_win)//inner_shift])
channel_angle = channel_angle - (np.floor(channel_angle / (2.*np.pi)) * (2.*np.pi))
ams[i, :, :] = np.power(channel_amplitude, 1./3.) * channel_angle
else:
ams[i, :, :] = np.abs(channel_stft)
return ams
python类power()的实例源码
def ams_extractor(x, sr, win_len, shift_len, barks, inner_win, inner_shift, win_type, method_version):
x_spectrum = stft_extractor(x, win_len, shift_len, win_type)
coef = get_fft_bark_mat(sr, win_len, barks, 20, sr//2)
bark_spect = np.matmul(coef, x_spectrum)
ams = np.zeros((barks, inner_win//2+1, (bark_spect.shape[1] - inner_win)//inner_shift))
for i in range(barks):
channel_stft = stft_extractor(bark_spect[i, :], inner_win, inner_shift, 'hanning')
if method_version == 'v1':
ams[i, :, :] = 20 * np.log(np.abs(channel_stft[:inner_win//2+1, :(bark_spect.shape[1] - inner_win)//inner_shift]))
elif method_version == 'v2':
channel_amplitude = np.abs(channel_stft[:inner_win//2+1, :(bark_spect.shape[1] - inner_win)//inner_shift])
channel_angle = np.angle(channel_stft[:inner_win//2+1, :(bark_spect.shape[1] - inner_win)//inner_shift])
channel_angle = channel_angle - (np.floor(channel_angle / (2.*np.pi)) * (2.*np.pi))
ams[i, :, :] = np.power(channel_amplitude, 1./3.) * channel_angle
else:
ams[i, :, :] = np.abs(channel_stft)
return ams
def perp_fit(ts, vs):
def lsq_macrospin(p, ts, vs):
t0 = p[0]
v0 = p[1]
a = v0
b = t0*v0
to = 1
vo = a + b/to
# Here is what we expect
vs_ideal = v0*(1.0 + t0/ts)
Xs = []
Ys = []
for t,v in zip(ts,vs):
ti,vi = find_closest(t,v,t0,v0)
Xs.append(x2X(ti,to,b))
Ys.append(y2Y(v,vi,a,b))
return np.power(Ys,2)
p0 = [0.2, 100]
p, flag = leastsq(lsq_macrospin, p0, args=(ts, vs))
return p
def find_null_offset(xpts, powers, default=0.0):
"""Finds the offset corresponding to the minimum power using a fit to the measured data"""
def model(x, a, b, c):
return a*(x - b)**2 + c
powers = np.power(10, powers/10.)
min_idx = np.argmin(powers)
try:
fit = curve_fit(model, xpts, powers, p0=[1, xpts[min_idx], powers[min_idx]])
except RuntimeError:
logger.warning("Mixer null offset fit failed.")
return default, np.zeros(len(powers))
best_offset = np.real(fit[0][1])
best_offset = np.minimum(best_offset, xpts[-1])
best_offset = np.maximum(best_offset, xpts[0])
xpts_fine = np.linspace(xpts[0],xpts[-1],101)
fit_pts = np.array([np.real(model(x, *fit[0])) for x in xpts_fine])
if min(fit_pts)<0: fit_pts-=min(fit_pts)-1e-10 #prevent log of a negative number
return best_offset, xpts_fine, 10*np.log10(fit_pts)
def Get3FGL(Cat,xdata,ydata,dydata):
#create a spectrum for a given catalog and compute the model+butterfly
# 3FGL CATALOG
Cat.MakeSpectrum("3FGL",1e-4,0.3)
enerbut,but,enerphi,phi = Cat.Plot("3FGL")
# read DATA Point from 3FGL CATALOG
em3FGL,ep3FGL,flux3FGL,dflux3FGL = Cat.GetDataPoints('3FGL') #energy in TeV since the user ask for that in the call of Cat
ener3FGL = numpy.sqrt(em3FGL*ep3FGL)
dem3FGL = ener3FGL-em3FGL
dep3FGL = ep3FGL-ener3FGL
c=Cat.ReadPL('3FGL')[3]
e2dnde3FGL = (-c+1)*flux3FGL*numpy.power(ener3FGL*1e6,-c+2)/(numpy.power((ep3FGL*1e6),-c+1)-numpy.power((em3FGL*1e6),-c+1))*1.6e-6
de2dnde3FGL = e2dnde3FGL*dflux3FGL/flux3FGL
for i in xrange(len(ener3FGL)):
xdata.append(numpy.log10(ener3FGL[i]))
ydata.append(numpy.log10(e2dnde3FGL[i]))
dydata.append(numpy.log10(de2dnde3FGL[i]))
return enerbut,but,enerphi,phi,ener3FGL, e2dnde3FGL, dem3FGL, dep3FGL, de2dnde3FGL
def spectrogram2wav(spectrogram, n_fft, win_length, hop_length, num_iters):
'''
spectrogram: [t, f], i.e. [t, nfft // 2 + 1]
'''
min_level_db = -100
ref_level_db = 20
spec = spectrogram.T
# denormalize
spec = (np.clip(spec, 0, 1) * - min_level_db) + min_level_db
spec = spec + ref_level_db
# Convert back to linear
spec = np.power(10.0, spec * 0.05)
return _griffin_lim(spec ** 1.5, n_fft, win_length, hop_length, num_iters) # Reconstruct phase
def process_commissions(symbol, multiplied_symbols):
try:
symbol_ = Symbols.objects.filter(symbol=symbol).values('currency', 'spread', 'digits', 'tick_size', 'tick_value', 'broker', 'symbol')
if settings.SHOW_DEBUG:
print("Processing commisions for {}".format(symbol_))
if any(symbol_[0]['symbol'] in s for s in multiplied_symbols):
value = (((power(10.0, -symbol_[0]['digits']) * \
float(symbol_[0]['spread'])) / float(symbol_[0]['tick_size'])) * \
float(symbol_[0]['tick_value'])) * 100.0
else:
value = (((power(10.0, -symbol_[0]['digits']) * \
float(symbol_[0]['spread'])) / float(symbol_[0]['tick_size'])) * \
float(symbol_[0]['tick_value']))
symbol.commission = value
symbol.save()
except Exception as err:
print(colored.red("At process commissions {}".format(err)))
symbol.commission = None
symbol.save()
if settings.SHOW_DEBUG:
print("Updated commision value for {0}\n".format(symbol.symbol))
def forward(self, is_train, req, in_data, out_data, aux):
cls_score = in_data[0].asnumpy()
labels = in_data[1].asnumpy()
self._labels = labels
pro_ = np.exp(cls_score - cls_score.max(axis=1).reshape((cls_score.shape[0], 1)))
pro_ /= pro_.sum(axis=1).reshape((cls_score.shape[0], 1))
# pro_ = mx.nd.SoftmaxActivation(cls_score) + 1e-14
# pro_ = pro_.asnumpy()
self.pro_ = pro_
# restore pt for backward
self._pt = pro_[np.arange(pro_.shape[0],dtype = 'int'), labels.astype('int')]
### note!!!!!!!!!!!!!!!!
# focal loss value is not used in this place we should forward the cls_pro in this layer, the focal vale should be calculated in metric.py
# the method is in readme
# focal loss (batch_size,num_class)
loss_ = -1 * np.power(1 - pro_, self._gamma) * np.log(pro_)
print "---------------"
print 'pro:',pro_[1],labels[1]
self.assign(out_data[0],req[0],mx.nd.array(pro_))
def build_data_auto_encoder(data, step, win_size):
count = data.shape[1] / float(step)
docX = np.zeros((count, 3, win_size))
for i in range(0, data.shape[1] - win_size, step):
c = i / step
docX[c][0] = np.abs(data[0, i:i + win_size] - data[1, i:i + win_size])
docX[c][1] = np.power(data[0, i:i + win_size] - data[1, i:i + win_size], 2)
docX[c][2] = np.pad(
(data[0, i:i + win_size - 1] - data[0, i + 1:i + win_size]) * (data[1, i:i + win_size - 1] - data[1, i + 1:i + win_size]),
(0, 1), 'constant', constant_values=0)
data = np.dstack((docX[:, 0], docX[:, 1], docX[:, 2])).reshape(docX.shape[0], docX.shape[1]*docX.shape[2])
return data
def __init__(self, prior, d, U):
self.prior = prior
ones = np.ones( d.shape, dtype=d.dtype )
self.d = ones - np.power(ones + d, -.5)
self.lrsqrt = LowRankOperator(self.d, U)
self.help = Vector()
self.init_vector(self.help, 0)
def trace2(self,W=None):
"""
Compute the trace of A*A (Note this is the square of Frob norm, since A is symmetic).
If the weight W is provided, it will compute the trace of (AW)^2.
This is equivalent to
tr_W(A) = \sum_i lambda_i^2,
where lambda_i are the generalized eigenvalues of
A x = lambda W^-1 x.
Note if U is a W-orthogonal matrix then
tr_W(A) = \sum_i D(i,i)^2.
"""
if W is None:
UtU = np.dot(self.U.T, self.U)
dUtU = self.d[:,None] * UtU #diag(d)*UtU.
tr2 = np.sum(dUtU*dUtU)
else:
WU = np.zeros(self.U.shape, dtype=self.U.dtype)
u, wu = Vector(), Vector()
W.init_vector(u,1)
W.init_vector(wu,0)
for i in range(self.U.shape[1]):
u.set_local(self.U[:,i])
W.mult(u,wu)
WU[:,i] = wu.get_local()
UtWU = np.dot(self.U.T, WU)
dUtWU = self.d[:,None] * UtWU #diag(d)*UtU.
tr2 = np.power(np.linalg.norm(dUtWU),2)
return tr2
def gaussian_2d(x, y, mx, my, cov):
''' x and y are the 2D coordinates to calculate the function value
mx and my are the mean parameters in x and y axes
cov is the 2x2 variance-covariance matrix'''
ret = 0
# ^^ YOUR CODE HERE ^^
sigmax = np.sqrt(cov[0][0])
sigmay = np.sqrt(cov[1][1])
p = cov[0][1] / (np.sqrt(cov[0][0]) * np.sqrt(cov[1][1]))
ret = (1 / (2 * np.pi * sigmax * sigmay * np.sqrt( 1 - np.power(p,2)))) * np.exp((( -1 / ( 2 * ( 1 - np.power(p,2)))) * ( ((np.power((x - mx), 2)) / (np.power(sigmax,2))) + ((np.power((y - my), 2)) / ( np.power(sigmay, 2))) - (( 2 * p * (x - mx) * (y - my)) / (sigmax * sigmay)))))
return ret
## Finally, we compute the Gaussian function outputs for each entry in our mesh and plot the surface for each class.
def pw2wav(features, feat_dim=513, fs=16000):
''' NOTE: Use `order='C'` to ensure Cython compatibility '''
en = np.reshape(features['en'], [-1, 1])
sp = np.power(10., features['sp'])
sp = en * sp
if isinstance(features, dict):
return pw.synthesize(
features['f0'].astype(np.float64).copy(order='C'),
sp.astype(np.float64).copy(order='C'),
features['ap'].astype(np.float64).copy(order='C'),
fs,
)
features = features.astype(np.float64)
sp = features[:, :feat_dim]
ap = features[:, feat_dim:feat_dim*2]
f0 = features[:, feat_dim*2]
en = features[:, feat_dim*2 + 1]
en = np.reshape(en, [-1, 1])
sp = np.power(10., sp)
sp = en * sp
return pw.synthesize(
f0.copy(order='C'),
sp.copy(order='C'),
ap.copy(order='C'),
fs
)
def applyColorAugmentation(self, img, std=0.55, gamma=2.5):
'''Applies random color augmentation following [1]. An additional gamma
transformation is added.
[1] Alex Krizhevsky, Ilya Sutskever, Geoffrey E. Hinton. ImageNet
Classification with Deep Convolutional Neural Networks. NIPS 2012.
'''
alpha = np.clip(np.random.normal(0, std, size=3), -1.3 * std, 1.3 * std)
perturbation = self.data_evecs.dot((alpha * np.sqrt(self.data_evals)).T)
gamma = 1.0 - sum(perturbation) / gamma
return np.power(np.clip(img + perturbation, 0., 1.), gamma)
return np.clip((img + perturbation), 0., 1.)
def applyColorAugmentation(img, std=0.5):
'''Applies random color augmentation following [1].
[1] Alex Krizhevsky, Ilya Sutskever, Geoffrey E. Hinton. \
ImageNet Classification with Deep Convolutional Neural Networks. \
NIPS 2012.'''
alpha = np.clip(np.random.normal(0, std, size=3), -2 * std, 2. * std)
perturbation = sld_evecs.dot((alpha * np.sqrt(sld_evals)).T)
gamma = 1.0 - sum(perturbation) / 3.
return np.power(np.clip(img + perturbation, 0., 1.), gamma)
return np.clip((img + perturbation), 0., 1.)
def ztnb_pmf(y, mu, alpha):
r = 1.0 / alpha
if y <= 0:
raise Exception('y must be larger than 0.')
p = mu/(mu+r+0.0)
ztnbin_mpmath = lambda y, p, r: mpmath.gamma(y + r)/(mpmath.gamma(y+1)*mpmath.gamma(r))*np.power(1-p, r)*np.power(p, y)/(1-np.power(1-p, r))
ztnbin = np.frompyfunc(ztnbin_mpmath, 3, 1)
return float(ztnbin(y, p, r))
def ztnb_cdf(y, mu, alpha):
r = 1.0/alpha
if y <= 0:
raise Exception('y must be larger than 0.')
p = mu/(mu+r+0.0)
F_ztnb = ( 1 - special.btdtr(y+1, r, p) - np.power(1-p, r) ) / (1-np.power(1-p,r))
return F_ztnb
def expected_zeros(pseudo_size, mu, alpha):
min_allowed_alpha=10**-4
max_allowed_prob_zero=0.99
if alpha < min_allowed_alpha:
prob_zero = max_allowed_prob_zero
else:
prob_zero = np.min([np.power(1.0+alpha*mu, -1.0/alpha), 0.99])
expected_zeros = int(pseudo_size*(prob_zero/(1-prob_zero)))
return expected_zeros
def derivative(self, input=None):
"""Backward propagation.
Returns
-------
float32
The derivative of Elliot function.
"""
last_forward = 1 + np.abs(input * self.steepness) if input else self.last_forward
return 0.5 * self.steepness / np.power(last_forward, 2)
# elliot-end
# symmetric-elliot-start
def derivative(self, input=None):
"""Backward propagation.
Returns
-------
float32
The derivative of SymmetricElliot function.
"""
last_forward = 1 + np.abs(input * self.steepness) if input else self.last_forward
return self.steepness / np.power(last_forward, 2)
# symmetric-elliot-end
# softplus-start