def assert_mpa_identical(mpa1, mpa2, decimal=np.infty):
"""Verify that two MPAs are complety identical
"""
assert len(mpa1) == len(mpa2)
assert mpa1.canonical_form == mpa2.canonical_form
assert mpa1.dtype == mpa2.dtype
for i, lten1, lten2 in zip(it.count(), mpa1.lt, mpa2.lt):
if decimal is np.infty:
assert_array_equal(lten1, lten2,
err_msg='mismatch in lten {}'.format(i))
else:
assert_array_almost_equal(lten1, lten2, decimal=decimal,
err_msg='mismatch in lten {}'.format(i))
# TODO: We should make a comprehensive comparison between `mpa1`
# and `mpa2`. Are we missing other things?
python类infty()的实例源码
def __init__(self, reg_e=1., max_iter=1000,
tol=10e-9, verbose=False, log=False,
metric="sqeuclidean", norm=None,
distribution_estimation=distribution_estimation_uniform,
out_of_sample_map='ferradans', limit_max=np.infty):
self.reg_e = reg_e
self.max_iter = max_iter
self.tol = tol
self.verbose = verbose
self.log = log
self.metric = metric
self.norm = norm
self.limit_max = limit_max
self.distribution_estimation = distribution_estimation
self.out_of_sample_map = out_of_sample_map
def __init__(self, reg_e=1., reg_cl=0.1,
max_iter=10, max_inner_iter=200,
tol=10e-9, verbose=False,
metric="sqeuclidean", norm=None,
distribution_estimation=distribution_estimation_uniform,
out_of_sample_map='ferradans', limit_max=np.infty):
self.reg_e = reg_e
self.reg_cl = reg_cl
self.max_iter = max_iter
self.max_inner_iter = max_inner_iter
self.tol = tol
self.verbose = verbose
self.metric = metric
self.norm = norm
self.distribution_estimation = distribution_estimation
self.out_of_sample_map = out_of_sample_map
self.limit_max = limit_max
def train_gmm(X, max_iter, tol, means, covariances):
xp = cupy.get_array_module(X)
lower_bound = -np.infty
converged = False
weights = xp.array([0.5, 0.5], dtype=np.float32)
inv_cov = 1 / xp.sqrt(covariances)
for n_iter in six.moves.range(max_iter):
prev_lower_bound = lower_bound
log_prob_norm, log_resp = e_step(X, inv_cov, means, weights)
weights, means, covariances = m_step(X, xp.exp(log_resp))
inv_cov = 1 / xp.sqrt(covariances)
lower_bound = log_prob_norm
change = lower_bound - prev_lower_bound
if abs(change) < tol:
converged = True
break
if not converged:
print('Failed to converge. Increase max-iter or tol.')
return inv_cov, means, weights, covariances
dtopotools_horiz_okada_and_1d.py 文件源码
项目:finite_volume_seismic_model
作者: cjvogl
项目源码
文件源码
阅读 26
收藏 0
点赞 0
评论 0
def containing_rect(self):
r"""Find containing rectangle of fault in x-y plane.
Returns tuple of x-limits and y-limits.
"""
extent = [numpy.infty, -numpy.infty, numpy.infty, -numpy.infty]
for subfault in self.subfaults:
for corner in subfault.corners:
extent[0] = min(corner[0], extent[0])
extent[1] = max(corner[0], extent[1])
extent[2] = min(corner[1], extent[2])
extent[3] = max(corner[1], extent[3])
return extent
dtopotools_horiz_okada_and_1d.py 文件源码
项目:finite_volume_seismic_model
作者: cjvogl
项目源码
文件源码
阅读 24
收藏 0
点赞 0
评论 0
def containing_rect(self):
r"""Find containing rectangle of fault in x-y plane.
Returns tuple of x-limits and y-limits.
"""
extent = [numpy.infty, -numpy.infty, numpy.infty, -numpy.infty]
for subfault in self.subfaults:
for corner in subfault.corners:
extent[0] = min(corner[0], extent[0])
extent[1] = max(corner[0], extent[1])
extent[2] = min(corner[1], extent[2])
extent[3] = max(corner[1], extent[3])
return extent
acousticModelTraining.py 文件源码
项目:jingjuSingingPhraseMatching
作者: ronggong
项目源码
文件源码
阅读 26
收藏 0
点赞 0
评论 0
def bicGMMModelSelection(X):
'''
bic model selection
:param X: features - observation * dimension
:return:
'''
lowest_bic = np.infty
bic = []
n_components_range = [10,15,20,25,30,35,40,45,50,55,60,65,70]
best_n_components = n_components_range[0]
for n_components in n_components_range:
# Fit a Gaussian mixture with EM
print 'Fitting GMM with n_components =',str(n_components)
gmm = mixture.GaussianMixture(n_components=n_components,
covariance_type='diag')
gmm.fit(X)
bic.append(gmm.bic(X))
if bic[-1] < lowest_bic:
lowest_bic = bic[-1]
best_n_components = n_components
best_gmm = gmm
return best_n_components,gmm
def chivecfn(theta):
"""A version of lnprobfn that returns the simple uncertainty
normalized residual instead of the log-posterior, for use with
least-squares optimization methods like Levenburg-Marquardt.
"""
lnp_prior = model.prior_product(theta)
if not np.isfinite(lnp_prior):
return -np.infty
# Generate mean model
t1 = time.time()
try:
spec, phot, x = model.mean_model(theta, obs, sps=sps)
except(ValueError):
return -np.infty
d1 = time.time() - t1
chispec = chi_spec(spec, obs)
chiphot = chi_phot(phot, obs)
return np.concatenate([chispec, chiphot])
def chivecfn(theta):
"""A version of lnprobfn that returns the simple uncertainty
normalized residual instead of the log-posterior, for use with
least-squares optimization methods like Levenburg-Marquardt.
"""
lnp_prior = model.prior_product(theta)
if not np.isfinite(lnp_prior):
return -np.infty
# Generate mean model
t1 = time.time()
try:
spec, phot, x = model.mean_model(theta, obs, sps=sps)
except(ValueError):
return -np.infty
d1 = time.time() - t1
chispec = chi_spec(spec, obs)
chiphot = chi_phot(phot, obs)
return np.concatenate([chispec, chiphot])
def chivecfn(theta):
"""A version of lnprobfn that returns the simple uncertainty
normalized residual instead of the log-posterior, for use with
least-squares optimization methods like Levenburg-Marquardt.
"""
lnp_prior = model.prior_product(theta)
if not np.isfinite(lnp_prior):
return -np.infty
# Generate mean model
t1 = time.time()
try:
spec, phot, x = model.mean_model(theta, obs, sps=sps)
except(ValueError):
return -np.infty
d1 = time.time() - t1
chispec = chi_spec(spec, obs)
chiphot = chi_phot(phot, obs)
return np.concatenate([chispec, chiphot])
###
def chivecfn(theta):
"""A version of lnprobfn that returns the simple uncertainty
normalized residual instead of the log-posterior, for use with
least-squares optimization methods like Levenburg-Marquardt.
"""
lnp_prior = model.prior_product(theta)
if not np.isfinite(lnp_prior):
return -np.infty
# Generate mean model
t1 = time.time()
try:
spec, phot, x = model.mean_model(theta, obs, sps=sps)
except(ValueError):
return -np.infty
d1 = time.time() - t1
chispec = chi_spec(spec, obs)
chiphot = chi_phot(phot, obs)
return np.concatenate([chispec, chiphot])
###
def chivecfn(theta):
"""A version of lnprobfn that returns the simple uncertainty
normalized residual instead of the log-posterior, for use with
least-squares optimization methods like Levenburg-Marquardt.
"""
lnp_prior = model.prior_product(theta)
if not np.isfinite(lnp_prior):
return -np.infty
# Generate mean model
t1 = time.time()
try:
spec, phot, x = model.mean_model(theta, obs, sps=sps)
except(ValueError):
return -np.infty
d1 = time.time() - t1
chispec = chi_spec(spec, obs)
chiphot = chi_phot(phot, obs)
return np.concatenate([chispec, chiphot])
def chivecfn(theta):
"""A version of lnprobfn that returns the simple uncertainty
normalized residual instead of the log-posterior, for use with
least-squares optimization methods like Levenburg-Marquardt.
"""
lnp_prior = model.prior_product(theta)
if not np.isfinite(lnp_prior):
return -np.infty
# Generate mean model
t1 = time.time()
try:
spec, phot, x = model.mean_model(theta, obs, sps=sps)
except(ValueError):
return -np.infty
d1 = time.time() - t1
chispec = chi_spec(spec, obs)
chiphot = chi_phot(phot, obs)
return np.concatenate([chispec, chiphot])
###
def chivecfn(theta):
"""A version of lnprobfn that returns the simple uncertainty
normalized residual instead of the log-posterior, for use with
least-squares optimization methods like Levenburg-Marquardt.
"""
lnp_prior = model.prior_product(theta)
if not np.isfinite(lnp_prior):
return -np.infty
# Generate mean model
t1 = time.time()
try:
spec, phot, x = model.mean_model(theta, obs, sps=sps)
except(ValueError):
return -np.infty
d1 = time.time() - t1
chispec = chi_spec(spec, obs)
chiphot = chi_phot(phot, obs)
return np.concatenate([chispec, chiphot])
###
def sanity_check(test_emb, train_emb, num_test):
'''
Sanity check on the cosine similarity calculations
Finds the closest vector in the space by brute force
'''
correct_list = []
for i in xrange(num_test):
smallest_norm = np.infty
index = 0
for j in xrange(len(train_emb)):
norm = np.linalg.norm(emb - test_emb[i])
if norm < smallest_norm:
smallest_norm = norm
index = j
correct_list.append(index)
# Pad the list to make it the same length as test_emb
for i in xrange(len(test_emb) - num_test):
correct_list.append(-1)
return correct_list
def sanity_check(test_emb, train_emb, num_test):
'''
Sanity check on the cosine similarity calculations
Finds the closest vector in the space by brute force
'''
correct_list = []
for i in xrange(num_test):
smallest_norm = np.infty
index = 0
for j in xrange(len(train_emb)):
norm = np.linalg.norm(emb - test_emb[i])
if norm < smallest_norm:
smallest_norm = norm
index = j
correct_list.append(index)
# Pad the list to make it the same length as test_emb
for i in xrange(len(test_emb) - num_test):
correct_list.append(-1)
return correct_list
def crowding_distance(models, *attrs):
"""
Assumes models in lexicographical sorted.
"""
get_fit = _get_fit(models, attrs)
f = np.array(sorted([get_fit(m) for m in models]))
scale = np.max(f, axis=0) - np.min(f, axis=0)
with np.errstate(invalid="ignore"):
dist = np.sum(abs(np.roll(f, 1, axis=0) - np.roll(f, -1, axis=0) ) / scale, axis=1)
dist[0] = np.infty
dist[-1] = np.infty
return dist
decisionboundaryplot.py 文件源码
项目:highdimensional-decision-boundary-plot
作者: tmadl
项目源码
文件源码
阅读 26
收藏 0
点赞 0
评论 0
def _find_decision_boundary_on_hypersphere(self, centroid, R, penalize_known=False):
def objective(phi, grad=0):
# search on hypersphere surface in polar coordinates - map back to cartesian
cx = centroid + polar_to_cartesian(phi, R)
try:
cx2d = self.dimensionality_reduction.transform([cx])[0]
error = self.decision_boundary_distance(cx)
if penalize_known:
# slight penalty for being too close to already known decision boundary
# keypoints
db_distances = [euclidean(cx2d, self.decision_boundary_points_2d[k])
for k in range(len(self.decision_boundary_points_2d))]
error += 1e-8 * ((self.mean_2d_dist - np.min(db_distances)) /
self.mean_2d_dist)**2
return error
except (Exception, ex):
print("Error in objective function:", ex)
return np.infty
optimizer = self._get_optimizer(
D=self.X.shape[1] - 1, upper_bound=2 * np.pi, iteration_budget=self.hypersphere_iteration_budget)
optimizer.set_min_objective(objective)
db_phi = optimizer.optimize([rnd.random() * 2 * np.pi for k in range(self.X.shape[1] - 1)])
db_point = centroid + polar_to_cartesian(db_phi, R)
return db_point
def find_best_match(patch, strip):
# TODO: Find patch in strip and return column index (x value) of topleft corner
# We will use SSD to find out the best match
best_id = 0
min_diff = np.infty
for i in range(int(strip.shape[1] - patch.shape[1])):
temp = strip[:, i: i + patch.shape[1]]
ssd = np.sum((temp - patch) ** 2)
if ssd < min_diff:
min_diff = ssd
best_id = i
return best_id
# Test code:
# Load images
def converge(self, x):
"""Finds cluster centers through an alternating optimization routine.
Terminates when either the number of cycles reaches `max_iter` or the
objective function changes by less than `tol`.
Parameters
----------
x : :obj:`np.ndarray`
(n_samples, n_features)
The original data.
"""
centers = []
j_new = np.infty
for i in range(self.max_iter):
j_old = j_new
self.update(x)
centers.append(self.centers)
j_new = self.objective(x)
if np.abs(j_old - j_new) < self.tol:
break
return np.array(centers)
def test_generate_np_gives_adversarial_example_linfinity(self):
self.help_generate_np_gives_adversarial_example(np.infty)
def E(self, x): # pylint: disable=invalid-name
"""Electric field vector.
Ref: http://www.phys.uri.edu/gerhard/PHY204/tsl31.pdf
"""
x = array(x)
x1, x2, lam = self.x1, self.x2, self.lam
# Get lengths and angles for the different triangles
theta1, theta2 = angle(x, x1, x2), pi - angle(x, x2, x1)
a = point_line_distance(x, x1, x2)
r1, r2 = norm(x - x1), norm(x - x2)
# Calculate the parallel and perpendicular components
sign = where(is_left(x, x1, x2), 1, -1)
# pylint: disable=invalid-name
Epara = lam*(1/r2-1/r1)
Eperp = -sign*lam*(cos(theta2)-cos(theta1))/where(a == 0, infty, a)
# Transform into the coordinate space and return
dx = x2 - x1
if len(x.shape) == 2:
Epara = Epara[::, newaxis]
Eperp = Eperp[::, newaxis]
return Eperp * (array([-dx[1], dx[0]])/norm(dx)) + Epara * (dx/norm(dx))
def interpolation(X, Y, extend_to_infty=True):
if extend_to_infty:
X = [-np.infty] + X + [np.infty]
Y = [Y[0]] + Y + [Y[-1]]
X = np.array(X)
Y = np.array(Y)
return lambda x: evaluate_interpolation(x, X, Y)
test_imaging.py 文件源码
项目:algorithm-reference-library
作者: SKA-ScienceDataProcessor
项目源码
文件源码
阅读 35
收藏 0
点赞 0
评论 0
def test_predict_facets(self):
self.actualSetUp()
self.params['facets'] = 2
self._predict_base(predict_facets, fluxthreshold=numpy.infty)
test_imaging.py 文件源码
项目:algorithm-reference-library
作者: SKA-ScienceDataProcessor
项目源码
文件源码
阅读 35
收藏 0
点赞 0
评论 0
def test_predict_timeslice(self):
# This works poorly because of the poor interpolation accuracy for point sources. The corresponding
# invert works well particularly if the beam sampling is high
self.actualSetUp()
self._predict_base(predict_timeslice, fluxthreshold=numpy.infty)
test_imaging.py 文件源码
项目:algorithm-reference-library
作者: SKA-ScienceDataProcessor
项目源码
文件源码
阅读 44
收藏 0
点赞 0
评论 0
def test_predict_timeslice_wprojection(self):
self.actualSetUp()
self.params['kernel'] = 'wprojection'
self.params['wstep'] = 2.0
self._predict_base(predict_timeslice, fluxthreshold=numpy.infty)
def initialize_run(nnet):
if nnet.data.dataset_name == 'imagenet':
nnet.max_passes = 1
nnet.max_inner_iterations = 5
nnet.max_outer_iterations = 1
nnet.epoch = epoch_imagenet
elif Cfg.store_on_gpu:
nnet.max_passes = 50
nnet.max_inner_iterations = 100
nnet.max_outer_iterations = 1
nnet.epoch = epoch_full_gpu
nnet.old_objective = np.infty
nnet.old_validation_acc = 0.
performance(nnet, which_set='train', print_=True)
else:
nnet.max_passes = 50
nnet.max_inner_iterations = 100
nnet.max_outer_iterations = 1
nnet.epoch = epoch_part_gpu
nnet.old_objective = np.infty
nnet.old_validation_acc = 0.
performance(nnet, which_set='train', print_=True)
return
def get_series_g2_taus( fra_max_list, acq_time=1, max_fra_num=None, log_taus = True,
num_bufs = 8):
'''
Get taus for dose dependent analysis
Parameters:
fra_max_list: a list, a lsit of largest available frame number
acq_time: acquistion time for each frame
log_taus: if true, will use the multi-tau defined taus bu using buf_num (default=8),
otherwise, use deltau =1
Return:
tausd, a dict, with keys as taus_max_list items
e.g.,
get_series_g2_taus( fra_max_list=[20,30,40], acq_time=1, max_fra_num=None, log_taus = True, num_bufs = 8)
-->
{20: array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16]),
30: array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28]),
40: array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32])
}
'''
tausd = {}
for n in fra_max_list:
if max_fra_num is not None:
L = max_fra_num
else:
L = np.infty
if n>L:
warnings.warn("Warning: the dose value is too large, and please"
"check the maxium dose in this data set and give a smaller dose value."
"We will use the maxium dose of the data.")
n = L
if log_taus:
lag_steps = get_multi_tau_lag_steps(n, num_bufs)
else:
lag_steps = np.arange( n )
tausd[n] = lag_steps * acq_time
return tausd
def wavread(fileName, lmax=np.infty, offset = 0, len_in_smpl = False):
"""reads the wave file file and returns a NDarray and the sampling frequency"""
def isValid(filename):
if not fileName:
return False
try:
fileHandle = wave.open(fileName, 'r')
fileHandle.close()
return True
except:
return False
if not isValid(fileName):
print("invalid WAV file. Aborting")
return None
# metadata properties of a file
length, nChans, fs, sampleWidth = wavinfo(fileName)
if not len_in_smpl:
lmax = lmax * fs
length = min(length - offset, lmax)
waveform = np.zeros((length, nChans))
# reading data
fileHandle = wave.open(fileName, 'r')
fileHandle.setpos(offset)
batchSizeT = 3000000
pos = 0
while pos < length:
batchSize = min(batchSizeT, length - pos)
str_bytestream = fileHandle.readframes(int(batchSize*2/sampleWidth))
tempData = np.fromstring(str_bytestream, 'h')
tempData = tempData.astype(float)
tempData = tempData.reshape(batchSize, nChans)
waveform[pos:pos+batchSize, :] = tempData / float(2**(8*sampleWidth - 1))
pos += batchSize
fileHandle.close()
return (waveform, fs)
def norm_infty(x):
"""Compute infinity norm of `x`."""
if len(x) > 0:
return norm(x, ord=infty)
return 0.0