本文整理汇总了Python中numpy.count_nonzero方法的典型用法代码示例。如果您正苦于以下问题:Python numpy.count_nonzero方法的具体用法?Python numpy.count_nonzero怎么用?Python numpy.count_nonzero使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类numpy
的用法示例。
在下文中一共展示了numpy.count_nonzero方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _accuracy
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import count_nonzero [as 别名]
def _accuracy(self, y_test, Y_vote):
"""Calculates accuracy
This method calculates the accuracy based on a vector of
ground-truth labels (y_test) and a 2D voting matrix (Y_vote) of
size (len(y_test), num_classes).
:param y_test: vector of ground-truth labels
:param Y_vote: 2D voting matrix (rows=samples, cols=class votes)
:returns: accuracy e[0,1]
"""
# predicted classes
y_hat = np.argmax(Y_vote, axis=1)
# all cases where predicted class was correct
mask = y_hat == y_test
return np.float32(np.count_nonzero(mask)) / len(y_test)
示例2: _confusion
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import count_nonzero [as 别名]
def _confusion(self, y_test, Y_vote):
"""Calculates confusion matrix
This method calculates the confusion matrix based on a vector of
ground-truth labels (y-test) and a 2D voting matrix (Y_vote) of
size (len(y_test), num_classes).
Matrix element conf[r,c] will contain the number of samples that
were predicted to have label r but have ground-truth label c.
:param y_test: vector of ground-truth labels
:param Y_vote: 2D voting matrix (rows=samples, cols=class votes)
:returns: confusion matrix
"""
y_hat = np.argmax(Y_vote, axis=1)
conf = np.zeros((self.num_classes, self.num_classes)).astype(np.int32)
for c_true in xrange(self.num_classes):
# looking at all samples of a given class, c_true
# how many were classified as c_true? how many as others?
for c_pred in xrange(self.num_classes):
y_this = np.where((y_test == c_true) * (y_hat == c_pred))
conf[c_pred, c_true] = np.count_nonzero(y_this)
return conf
示例3: test_gen_mass
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import count_nonzero [as 别名]
def test_gen_mass(self):
r"""Test gen_mass method.
Approach: Ensures the output is set, of the correct type, length, and units.
Check the range of the returned values. Check that, for this power law, there
are more small than large masses (for n large).
"""
plan_pop = self.fixture
n = 10000
# call the routine
masses = plan_pop.gen_mass(n)
# check the type
self.assertEqual(type(masses), type(1.0 * u.kg))
# crude check on the shape (more small than large for this power law)
midpoint = np.mean(plan_pop.Mprange)
self.assertGreater(np.count_nonzero(masses < midpoint),
np.count_nonzero(masses > midpoint))
# test some illegal "n" values
n_list_bad = [-1, '100', 22.5]
for n in n_list_bad:
with self.assertRaises(AssertionError):
masses = plan_pop.gen_mass(n)
示例4: test_gen_mass
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import count_nonzero [as 别名]
def test_gen_mass(self):
r"""Test gen_mass method.
Approach: Ensures the output is set, of the correct type, length, and units.
Check that returned values are nonnegative. Check that, for this power law, there
are more small than large masses (for n large).
"""
plan_pop = self.fixture
n = 10000
masses = plan_pop.gen_mass(n)
self.assertEqual(len(masses), n)
self.assertTrue(np.all(masses.value >= 0))
self.assertTrue(np.all(np.isfinite(masses.value)))
midpoint = np.mean(masses)
self.assertGreater(np.count_nonzero(masses < midpoint),
np.count_nonzero(masses > midpoint))
# test some illegal "n" values
n_list_bad = [-1, '100', 22.5]
for n in n_list_bad:
with self.assertRaises(AssertionError):
masses = plan_pop.gen_mass(n)
示例5: test_init_indexes
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import count_nonzero [as 别名]
def test_init_indexes(self):
r"""Test of initialization and __init__ -- indexes.
Method: Insure the plan2star and sInds indexes are present.
Performs sanity check on the range of index values.
TODO: More could be done to ensure the index values are correct.
"""
universe = self.fixture
self.basic_validation(universe)
# indexes present
self.assertIn('plan2star', universe.__dict__)
self.assertIn('sInds', universe.__dict__)
# range: 0 <= sInds < nStars
self.assertEqual(0, np.count_nonzero(universe.sInds < 0))
self.assertEqual(0, np.count_nonzero(universe.sInds >= universe.TargetList.nStars))
# domain: plan2star covers 0...nPlans-1
self.assertEqual(len(universe.plan2star), universe.nPlans)
# range: 0 <= plan2star < nStars
self.assertEqual(0, np.count_nonzero(universe.plan2star < 0))
self.assertEqual(0, np.count_nonzero(universe.plan2star >= universe.TargetList.nStars))
示例6: canonicalize
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import count_nonzero [as 别名]
def canonicalize(mf, mo_coeff_kpts, mo_occ_kpts, fock=None):
if fock is None:
dm = mf.make_rdm1(mo_coeff_kpts, mo_occ_kpts)
fock = mf.get_fock(dm=dm)
mo_coeff = []
mo_energy = []
for k, mo in enumerate(mo_coeff_kpts):
mo1 = np.empty_like(mo)
mo_e = np.empty_like(mo_occ_kpts[k])
occidx = mo_occ_kpts[k] == 2
viridx = ~occidx
for idx in (occidx, viridx):
if np.count_nonzero(idx) > 0:
orb = mo[:,idx]
f1 = reduce(np.dot, (orb.T.conj(), fock[k], orb))
e, c = scipy.linalg.eigh(f1)
mo1[:,idx] = np.dot(orb, c)
mo_e[idx] = e
mo_coeff.append(mo1)
mo_energy.append(mo_e)
return mo_energy, mo_coeff
示例7: _frozen_sanity_check
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import count_nonzero [as 别名]
def _frozen_sanity_check(frozen, mo_occ, kpt_idx):
'''Performs a few sanity checks on the frozen array and mo_occ.
Specific tests include checking for duplicates within the frozen array.
Args:
frozen (array_like of int): The orbital indices that will be frozen.
mo_occ (:obj:`ndarray` of int): The occupuation number for each orbital
resulting from a mean-field-like calculation.
kpt_idx (int): The k-point that `mo_occ` and `frozen` belong to.
'''
frozen = np.array(frozen)
nocc = np.count_nonzero(mo_occ > 0)
assert nocc, 'No occupied orbitals?\n\nnocc = %s\nmo_occ = %s' % (nocc, mo_occ)
all_frozen_unique = (len(frozen) - len(np.unique(frozen))) == 0
if not all_frozen_unique:
raise RuntimeError('Frozen orbital list contains duplicates!\n\nkpt_idx %s\n'
'frozen %s' % (kpt_idx, frozen))
if len(frozen) > 0 and np.max(frozen) > len(mo_occ) - 1:
raise RuntimeError('Freezing orbital not in MO list!\n\nkpt_idx %s\n'
'frozen %s\nmax orbital idx %s' % (kpt_idx, frozen, len(mo_occ) - 1))
示例8: _unpack
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import count_nonzero [as 别名]
def _unpack(vo, mo_occ):
za = []
zb = []
p1 = 0
for k, occ in enumerate(mo_occ[0]):
no = numpy.count_nonzero(occ > 0)
nv = occ.size - no
p0, p1 = p1, p1 + no * nv
za.append(vo[p0:p1].reshape(no,nv))
for k, occ in enumerate(mo_occ[1]):
no = numpy.count_nonzero(occ > 0)
nv = occ.size - no
p0, p1 = p1, p1 + no * nv
zb.append(vo[p0:p1].reshape(no,nv))
return za, zb
示例9: canonicalize
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import count_nonzero [as 别名]
def canonicalize(mf, mo_coeff, mo_occ, fock=None):
'''Canonicalization diagonalizes the Fock matrix within occupied, open,
virtual subspaces separatedly (without change occupancy).
'''
if fock is None:
dm = mf.make_rdm1(mo_coeff, mo_occ)
fock = mf.get_fock(dm=dm)
coreidx = mo_occ == 2
viridx = mo_occ == 0
openidx = ~(coreidx | viridx)
mo = numpy.empty_like(mo_coeff)
mo_e = numpy.empty(mo_occ.size)
for idx in (coreidx, openidx, viridx):
if numpy.count_nonzero(idx) > 0:
orb = mo_coeff[:,idx]
f1 = reduce(numpy.dot, (orb.conj().T, fock, orb))
e, c = scipy.linalg.eigh(f1)
mo[:,idx] = numpy.dot(orb, c)
mo_e[idx] = e
return mo_e, mo
示例10: _dump_mo_energy
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import count_nonzero [as 别名]
def _dump_mo_energy(mol, mo_energy, mo_occ, ehomo, elumo, orbsym, title='',
verbose=logger.DEBUG):
log = logger.new_logger(mol, verbose)
for i, ir in enumerate(mol.irrep_id):
irname = mol.irrep_name[i]
ir_idx = (orbsym == ir)
nso = numpy.count_nonzero(ir_idx)
nocc = numpy.count_nonzero(mo_occ[ir_idx])
e_ir = mo_energy[ir_idx]
if nocc == 0:
log.debug('%s%s nocc = 0', title, irname)
elif nocc == nso:
log.debug('%s%s nocc = %d HOMO = %.15g',
title, irname, nocc, e_ir[nocc-1])
else:
log.debug('%s%s nocc = %d HOMO = %.15g LUMO = %.15g',
title, irname, nocc, e_ir[nocc-1], e_ir[nocc])
if e_ir[nocc-1]+1e-3 > elumo:
log.warn('%s%s HOMO %.15g > system LUMO %.15g',
title, irname, e_ir[nocc-1], elumo)
if e_ir[nocc] < ehomo+1e-3:
log.warn('%s%s LUMO %.15g < system HOMO %.15g',
title, irname, e_ir[nocc], ehomo)
log.debug(' mo_energy = %s', e_ir)
示例11: float_occ_
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import count_nonzero [as 别名]
def float_occ_(mf):
'''
For UHF, allowing the Sz value being changed during SCF iteration.
Determine occupation of alpha and beta electrons based on energy spectrum
'''
from pyscf.scf import uhf
assert(isinstance(mf, uhf.UHF))
def get_occ(mo_energy, mo_coeff=None):
mol = mf.mol
ee = numpy.sort(numpy.hstack(mo_energy))
n_a = numpy.count_nonzero(mo_energy[0]<(ee[mol.nelectron-1]+1e-3))
n_b = mol.nelectron - n_a
if mf.nelec is None:
nelec = mf.mol.nelec
else:
nelec = mf.nelec
if n_a != nelec[0]:
logger.info(mf, 'change num. alpha/beta electrons '
' %d / %d -> %d / %d',
nelec[0], nelec[1], n_a, n_b)
mf.nelec = (n_a, n_b)
return uhf.UHF.get_occ(mf, mo_energy, mo_coeff)
mf.get_occ = get_occ
return mf
示例12: test_uniq_var
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import count_nonzero [as 别名]
def test_uniq_var(self):
mo_occ = mf.mo_occ.copy()
nmo = mo_occ.size
nocc = numpy.count_nonzero(mo_occ > 0)
nvir = nmo - nocc
numpy.random.seed(1)
f = numpy.random.random((nmo,nmo))
f_uniq = scf.hf.pack_uniq_var(f, mo_occ)
self.assertEqual(f_uniq.size, nocc*nvir)
f1 = scf.hf.unpack_uniq_var(f_uniq, mo_occ)
self.assertAlmostEqual(abs(f1 + f1.T).max(), 0, 12)
mo_occ[4:7] = 1
ndocc = 4
nocc = 7
f_uniq = scf.hf.pack_uniq_var(f, mo_occ)
self.assertEqual(f_uniq.size, nocc*(nmo-ndocc)-(nocc-ndocc)**2)
f1 = scf.hf.unpack_uniq_var(f_uniq, mo_occ)
self.assertAlmostEqual(abs(f1 + f1.T).max(), 0, 12)
示例13: get_nocc
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import count_nonzero [as 别名]
def get_nocc(mp):
if mp._nocc is not None:
return mp._nocc
elif mp.frozen is None:
nocc = numpy.count_nonzero(mp.mo_occ > 0)
assert(nocc > 0)
return nocc
elif isinstance(mp.frozen, (int, numpy.integer)):
nocc = numpy.count_nonzero(mp.mo_occ > 0) - mp.frozen
assert(nocc > 0)
return nocc
elif isinstance(mp.frozen[0], (int, numpy.integer)):
occ_idx = mp.mo_occ > 0
occ_idx[list(mp.frozen)] = False
nocc = numpy.count_nonzero(occ_idx)
assert(nocc > 0)
return nocc
else:
raise NotImplementedError
示例14: pick_real_eigs
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import count_nonzero [as 别名]
def pick_real_eigs(w, v, nroots, envs):
'''This function searchs the real eigenvalues or eigenvalues with small
imaginary component.
'''
threshold = 1e-3
abs_imag = abs(w.imag)
# Grab `nroots` number of e with small(est) imaginary components
max_imag_tol = max(threshold, numpy.sort(abs_imag)[min(w.size,nroots)-1])
real_idx = numpy.where((abs_imag <= max_imag_tol))[0]
nbelow_thresh = numpy.count_nonzero(abs_imag[real_idx] < threshold)
if nbelow_thresh < nroots and w.size >= nroots:
warnings.warn('Only %d eigenvalues (out of %3d requested roots) with imaginary part < %4.3g.\n'
% (nbelow_thresh, min(w.size,nroots), threshold))
# Guess whether the matrix to diagonalize is real or complex
if envs.get('dtype') == numpy.double:
w, v, idx = _eigs_cmplx2real(w, v, real_idx, real_eigenvectors=True)
else:
w, v, idx = _eigs_cmplx2real(w, v, real_idx, real_eigenvectors=False)
return w, v, idx
示例15: _sort_by_similarity
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import count_nonzero [as 别名]
def _sort_by_similarity(w, v, nroots, conv, vlast, emin=None, heff=None):
if not any(conv) or vlast is None:
return w[:nroots], v[:,:nroots]
head, nroots = vlast.shape
conv = numpy.asarray(conv[:nroots])
ovlp = vlast[:,conv].T.conj().dot(v[:head])
ovlp = numpy.einsum('ij,ij->j', ovlp, ovlp)
nconv = numpy.count_nonzero(conv)
nleft = nroots - nconv
idx = ovlp.argsort()
sorted_idx = numpy.zeros(nroots, dtype=int)
sorted_idx[conv] = numpy.sort(idx[-nconv:])
sorted_idx[~conv] = numpy.sort(idx[:-nconv])[:nleft]
e = w[sorted_idx]
c = v[:,sorted_idx]
return e, c