本文整理汇总了Python中numpy.get_printoptions函数的典型用法代码示例。如果您正苦于以下问题:Python get_printoptions函数的具体用法?Python get_printoptions怎么用?Python get_printoptions使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了get_printoptions函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: test_precision
def test_precision():
"""test various values for float_precision."""
f = PlainTextFormatter()
nt.assert_equal(f(pi), repr(pi))
f.float_precision = 0
if numpy:
po = numpy.get_printoptions()
nt.assert_equal(po['precision'], 0)
nt.assert_equal(f(pi), '3')
f.float_precision = 2
if numpy:
po = numpy.get_printoptions()
nt.assert_equal(po['precision'], 2)
nt.assert_equal(f(pi), '3.14')
f.float_precision = '%g'
if numpy:
po = numpy.get_printoptions()
nt.assert_equal(po['precision'], 2)
nt.assert_equal(f(pi), '3.14159')
f.float_precision = '%e'
nt.assert_equal(f(pi), '3.141593e+00')
f.float_precision = ''
if numpy:
po = numpy.get_printoptions()
nt.assert_equal(po['precision'], 8)
nt.assert_equal(f(pi), repr(pi))
开发者ID:mattvonrocketstein,项目名称:smash,代码行数:26,代码来源:test_formatters.py
示例2: magic_push_print
def magic_push_print(self, arg):
""" Set numpy array printing options by pushing onto a stack.
"""
try:
import numpy
except ImportError:
raise UsageError("could not import numpy.")
args = parse_argstring(magic_push_print, arg)
kwds = {}
if args.precision is not None:
kwds['precision'] = args.precision
if args.threshold is not None:
if args.threshold == 0:
args.threshold = sys.maxint
kwds['threshold'] = args.threshold
if args.edgeitems is not None:
kwds['edgeitems'] = args.edgeitems
if args.linewidth is not None:
kwds['linewidth'] = args.linewidth
if args.suppress is not None:
kwds['suppress'] = args.suppress
if args.nanstr is not None:
kwds['nanstr'] = args.nanstr
if args.infstr is not None:
kwds['infstr'] = args.infstr
old_options = numpy.get_printoptions()
numpy.set_printoptions(**kwds)
stack = getattr(self, '_numpy_printoptions_stack', [])
stack.append(old_options)
self._numpy_printoptions_stack = stack
if not args.quiet:
print_numpy_printoptions(numpy.get_printoptions())
开发者ID:rkern,项目名称:kernmagic,代码行数:34,代码来源:mymagics.py
示例3: test_ctx_mgr_restores
def test_ctx_mgr_restores(self):
# test that print options are actually restrored
opts = np.get_printoptions()
with np.printoptions(precision=opts['precision'] - 1,
linewidth=opts['linewidth'] - 4):
pass
assert_equal(np.get_printoptions(), opts)
开发者ID:Nodd,项目名称:numpy,代码行数:7,代码来源:test_arrayprint.py
示例4: test_precision
def test_precision():
"""test various values for float_precision."""
f = PlainTextFormatter()
nt.assert_equals(f(pi), repr(pi))
f.float_precision = 0
if numpy:
po = numpy.get_printoptions()
nt.assert_equals(po["precision"], 0)
nt.assert_equals(f(pi), "3")
f.float_precision = 2
if numpy:
po = numpy.get_printoptions()
nt.assert_equals(po["precision"], 2)
nt.assert_equals(f(pi), "3.14")
f.float_precision = "%g"
if numpy:
po = numpy.get_printoptions()
nt.assert_equals(po["precision"], 2)
nt.assert_equals(f(pi), "3.14159")
f.float_precision = "%e"
nt.assert_equals(f(pi), "3.141593e+00")
f.float_precision = ""
if numpy:
po = numpy.get_printoptions()
nt.assert_equals(po["precision"], 8)
nt.assert_equals(f(pi), repr(pi))
开发者ID:chensunn,项目名称:PortableJekyll,代码行数:26,代码来源:test_formatters.py
示例5: _get_suppress
def _get_suppress(self):
"""
Gets the current suppression settings (from numpy).
"""
suppress = np.get_printoptions()['suppress']
suppress_thresh = 0.1 ** (np.get_printoptions()['precision'] + 0.5)
return (suppress, suppress_thresh)
开发者ID:dstahlke,项目名称:qitensor,代码行数:8,代码来源:arrayformatter.py
示例6: test_ctx_mgr_exceptions
def test_ctx_mgr_exceptions(self):
# test that print options are restored even if an exeption is raised
opts = np.get_printoptions()
try:
with np.printoptions(precision=2, linewidth=11):
raise ValueError
except ValueError:
pass
assert_equal(np.get_printoptions(), opts)
开发者ID:Nodd,项目名称:numpy,代码行数:9,代码来源:test_arrayprint.py
示例7: testTensorStrReprObeyNumpyPrintOptions
def testTensorStrReprObeyNumpyPrintOptions(self):
orig_threshold = np.get_printoptions()["threshold"]
orig_edgeitems = np.get_printoptions()["edgeitems"]
np.set_printoptions(threshold=2, edgeitems=1)
t = _create_tensor(np.arange(10, dtype=np.int32))
self.assertIn("[0 ..., 9]", str(t))
self.assertIn("[0, ..., 9]", repr(t))
# Clean up: reset to previous printoptions.
np.set_printoptions(threshold=orig_threshold, edgeitems=orig_edgeitems)
开发者ID:marcomarchesi,项目名称:tensorflow,代码行数:11,代码来源:tensor_test.py
示例8: testTensorStrReprObeyNumpyPrintOptions
def testTensorStrReprObeyNumpyPrintOptions(self):
orig_threshold = np.get_printoptions()["threshold"]
orig_edgeitems = np.get_printoptions()["edgeitems"]
np.set_printoptions(threshold=2, edgeitems=1)
t = _create_tensor(np.arange(10, dtype=np.int32))
self.assertTrue(re.match(r".*\[.*0.*\.\.\..*9.*\]", str(t)))
self.assertTrue(re.match(r".*\[.*0.*\.\.\..*9.*\]", repr(t)))
# Clean up: reset to previous printoptions.
np.set_printoptions(threshold=orig_threshold, edgeitems=orig_edgeitems)
开发者ID:adit-chandra,项目名称:tensorflow,代码行数:11,代码来源:tensor_test.py
示例9: __repr__
def __repr__(self):
if len(self) > np.get_printoptions()['threshold']:
# Show only the first and last edgeitems.
edgeitems = np.get_printoptions()['edgeitems']
data = str(list(self[:edgeitems]))[:-1]
data += ", ..., "
data += str(list(self[-edgeitems:]))[1:]
else:
data = str(list(self))
return "{name}({data})".format(name=self.__class__.__name__,
data=data)
开发者ID:arokem,项目名称:nibabel,代码行数:12,代码来源:array_sequence.py
示例10: __repr__
def __repr__(self):
prefixstr = " "
if self._values.shape == ():
v = [tuple([self._values[nm] for nm in self._values.dtype.names])]
v = np.array(v, dtype=self._values.dtype)
else:
v = self._values
names = self._values.dtype.names
precision = np.get_printoptions()["precision"]
fstyle = functools.partial(_fstyle, precision)
format_val = lambda val: np.array2string(val, style=fstyle)
formatter = {"numpystr": lambda x: "({0})".format(", ".join(format_val(x[name]) for name in names))}
if NUMPY_LT_1P7:
arrstr = np.array2string(v, separator=", ", prefix=prefixstr)
else:
arrstr = np.array2string(v, formatter=formatter, separator=", ", prefix=prefixstr)
if self._values.shape == ():
arrstr = arrstr[1:-1]
unitstr = ("in " + self._unitstr) if self._unitstr else "[dimensionless]"
return "<{0} ({1}) {2:s}\n{3}{4}>".format(
self.__class__.__name__, ", ".join(self.components), unitstr, prefixstr, arrstr
)
开发者ID:n0d,项目名称:astropy,代码行数:28,代码来源:representation.py
示例11: print_array
def print_array(x, debug=False, **kwargs):
opt = np.get_printoptions()
ndigits = int(np.log10(np.nanmax(x))) + 2
if 'precision' in kwargs:
nprec = kwargs['precision']
else:
nprec = 3
if 'formatter' not in kwargs:
if issubclass(x.dtype.type, np.int):
ff = '{:%dd}' % (ndigits)
kwargs['formatter'] = {'int': ff.format}
else:
ff = '{:%d.%df}' % (ndigits + nprec, nprec)
kwargs['formatter'] = {'float': ff.format}
if debug:
print nprec, ndigits, kwargs
np.set_printoptions(**kwargs)
if isinstance(x, np.ndarray):
if len(x.shape) > 1:
_print_helper(x)
else:
print(x)
np.set_printoptions(**opt)
开发者ID:MBlaschek,项目名称:radiosonde,代码行数:27,代码来源:support.py
示例12: __call__
def __call__(self, report_folder, connection_holder, dsg_targets):
""" Convert synaptic matrix for every application edge.
"""
# Update the print options to display everything
print_opts = numpy.get_printoptions()
numpy.set_printoptions(threshold=numpy.nan)
if dsg_targets is None:
raise SynapticConfigurationException(
"dsg_targets should not be none, used as a check for "
"connection holder data to be generated")
# generate folder for synaptic reports
top_level_folder = os.path.join(report_folder, _DIRNAME)
if not os.path.exists(top_level_folder):
os.mkdir(top_level_folder)
# create progress bar
progress = ProgressBar(connection_holder.keys(),
"Generating synaptic matrix reports")
# for each application edge, write matrix in new file
for edge, _ in progress.over(connection_holder.keys()):
# only write matrix's for edges which have matrix's
if isinstance(edge, ProjectionApplicationEdge):
# figure new file name
file_name = os.path.join(
top_level_folder, _TMPL_FILENAME.format(edge.label))
self._write_file(file_name, connection_holder, edge)
# Reset the print options
numpy.set_printoptions(**print_opts)
开发者ID:SpiNNakerManchester,项目名称:sPyNNaker,代码行数:33,代码来源:spynnaker_synaptic_matrix_report.py
示例13: linprog_verbose_callback
def linprog_verbose_callback(xk, **kwargs):
"""
This is a sample callback for use with linprog, demonstrating the callback interface.
This callback produces detailed output to sys.stdout before each iteration and after
the final iteration of the simplex algorithm.
Parameters
----------
xk : array_like
The current solution vector.
**kwargs : dict
A dictionary containing the following parameters:
tableau : array_like
The current tableau of the simplex algorithm. Its structure is defined in _solve_simplex.
phase : int
The current Phase of the simplex algorithm (1 or 2)
iter : int
The current iteration number.
pivot : tuple(int, int)
The index of the tableau selected as the next pivot, or nan if no pivot exists
basis : array(int)
A list of the current basic variables. Each element contains the name of a basic variable and
its value.
complete : bool
True if the simplex algorithm has completed (and this is the final call to callback), otherwise False.
"""
tableau = kwargs["tableau"]
iter = kwargs["iter"]
pivrow, pivcol = kwargs["pivot"]
phase = kwargs["phase"]
basis = kwargs["basis"]
complete = kwargs["complete"]
saved_printoptions = np.get_printoptions()
np.set_printoptions(linewidth=500,
formatter={'float':lambda x: "{: 12.4f}".format(x)})
if complete:
print("--------- Iteration Complete - Phase {:d} -------\n".format(phase))
print("Tableau:")
elif iter == 0:
print("--------- Initial Tableau - Phase {:d} ----------\n".format(phase))
else:
print("--------- Iteration {:d} - Phase {:d} --------\n".format(iter, phase))
print("Tableau:")
if iter >= 0:
print("" + str(tableau) + "\n")
if not complete:
print("Pivot Element: T[{:.0f}, {:.0f}]\n".format(pivrow, pivcol))
print("Basic Variables:", basis)
print()
print("Current Solution:")
print("x = ", xk)
print()
print("Current Objective Value:")
print("f = ", -tableau[-1, -1])
print()
np.set_printoptions(**saved_printoptions)
开发者ID:jabooth,项目名称:scipy,代码行数:60,代码来源:_linprog.py
示例14: print_table
def print_table(self):
'''Print a table of probabilities at each SNP.'''
options = np.get_printoptions()
np.set_printoptions(precision=3, suppress=True, threshold=np.nan, linewidth=200)
print 'lambda = %s, Delta = %s, eps = %.1e' % (self.lam, repr(self.Delta)[6:-1], self.e)
print 'Viterbi path (frame SNPs): ' + ' -> '.join(map(lambda x: '%d (%d-%d)' % (x[0], x[1][0], x[1][1]),
itemutil.groupby_with_range(self.Q_star + 1)))
print 'Viterbi path (SNPs): ' + ' -> '.join(map(lambda x: '%d (%d-%d)' % (x[0], self.snps[x[1][0]], self.snps[x[1][1]]),
itemutil.groupby_with_range(self.Q_star + 1)))
print ' %-10s%-10s%-10s%-10s%-10s%-10s%-10s%-10s%-10s%-10s%-10s%-10s%-10s%-10s%-10s%-10s%-10s%-10s%-10s' % \
('t', 'SNP#', 'Obs', 'G1', 'G2', 'lam*dx', 'p',
'Gam1', 'Gam2', 'Gam3', 'Gam4', 'Gam5', 'Gam6', 'Gam7', 'Gam8', 'Gam9',
'p(IBD)', 'Viterbi', 'IBD?')
print np.concatenate((np.arange(len(self.x))[np.newaxis].transpose(),
self.snps[np.newaxis].transpose(),
self.Obs[np.newaxis].transpose(),
np.array([ProbIbdHmmCalculator._T_STATE_G[t][0] for t in self.Obs])[np.newaxis].transpose(),
np.array([ProbIbdHmmCalculator._T_STATE_G[t][1] for t in self.Obs])[np.newaxis].transpose(),
np.concatenate((self.lam_x, [0]))[np.newaxis].transpose(),
self.p[np.newaxis].transpose(),
self.Gamma.transpose(),
self.p_ibd_gamma[np.newaxis].transpose(),
(self.Q_star + 1)[np.newaxis].transpose(),
self.p_ibd_viterbi[np.newaxis].transpose()
), axis=1)
util.set_printoptions(options)
开发者ID:orenlivne,项目名称:ober,代码行数:26,代码来源:ibd_hmm.py
示例15: printoptions
def printoptions(*args, **kwargs):
original = np.get_printoptions()
np.set_printoptions(*args, **kwargs)
try:
yield
finally:
np.set_printoptions(**original)
开发者ID:HounD,项目名称:IDNNs,代码行数:7,代码来源:mutual_info_estimation.py
示例16: printvar
def printvar(locals_, varname, attr='.shape', typepad=0):
npprintopts = np.get_printoptions()
np.set_printoptions(threshold=5)
dotpos = varname.find('.')
# Locate var
if dotpos == -1:
var = locals_[varname]
else:
varname_ = varname[:dotpos]
dotname_ = varname[dotpos:]
var_ = locals_[varname_] # NOQA
var = eval('var_' + dotname_)
# Print in format
typestr = str(util_type.get_type(var)).ljust(typepad)
if isinstance(var, np.ndarray):
varstr = eval('str(var' + attr + ')')
print('[var] %s %s = %s' % (typestr, varname + attr, varstr))
elif isinstance(var, list):
if attr == '.shape':
func = 'len'
else:
func = ''
varstr = eval('str(' + func + '(var))')
print('[var] %s len(%s) = %s' % (typestr, varname, varstr))
else:
print('[var] %s %s = %r' % (typestr, varname, var))
np.set_printoptions(**npprintopts)
开发者ID:animalus,项目名称:utool,代码行数:28,代码来源:util_dbg.py
示例17: test
def test(self, patterns):
error = 0.0
bin_correct = 0
precision = np.get_printoptions()['precision']
np.set_printoptions(precision=7, suppress=True)
print('')
for values, targets in patterns:
a = self.predict(values)
# sum of squares error
# noinspection PyUnresolvedReferences
sse = ((np.array(targets)-a)**2).sum()
error += sse
# noinspection PyTypeChecker
u_bin = a >= .5
bin_targets = np.array(targets) >= .5
bin_correct += np.all(u_bin == bin_targets)
print('{} -> {} = {}'.format(values, targets, a))
print('')
print('correct: {}/{}'.format(bin_correct, len(patterns)))
print('overall error: {}'.format(error))
np.set_printoptions(precision=precision, suppress=False)
return bin_correct, len(patterns), error
开发者ID:JesseBuesking,项目名称:dbn,代码行数:28,代码来源:backprop_nn.py
示例18: _pprint
def _pprint(params, offset=0, printer=repr):
# Do a multi-line justified repr:
options = np.get_printoptions()
np.set_printoptions(precision=5, threshold=64, edgeitems=2)
params_list = list()
this_line_length = offset
line_sep = ',\n' + (1 + offset) * ' '
for i, (k, v) in enumerate(params):
if type(v) is float:
# use str for representing floating point numbers
# this way we get consistent representation across
# architectures and versions.
this_repr = '%s=%s' % (k, str(v))
else:
# use repr of the rest
this_repr = '%s=%s' % (k, printer(v))
if len(this_repr) > 500:
this_repr = this_repr[:300] + '...' + this_repr[-100:]
if i > 0:
if (this_line_length + len(this_repr) >= 75 or '\n' in this_repr):
params_list.append(line_sep)
this_line_length = len(line_sep)
else:
params_list.append(', ')
this_line_length += 2
params_list.append(this_repr)
this_line_length += len(this_repr)
np.set_printoptions(**options)
lines = ''.join(params_list)
# Strip trailing space to avoid nightmare in doctests
lines = '\n'.join(l.rstrip(' ') for l in lines.split('\n'))
return lines
开发者ID:ibab,项目名称:datapipe,代码行数:33,代码来源:task.py
示例19: _register_neighb_to_model
def _register_neighb_to_model(self, model_bundle, neighb_streamlines,
metric=None, x0=None, bounds=None,
select_model=400, select_target=600,
method='L-BFGS-B',
nb_pts=20, num_threads=None):
if self.verbose:
print('# Local SLR of neighb_streamlines to model')
t = time()
if metric is None or metric == 'symmetric':
metric = BundleMinDistanceMetric(num_threads=num_threads)
if metric == 'asymmetric':
metric = BundleMinDistanceAsymmetricMetric()
if metric == 'diagonal':
metric = BundleSumDistanceMatrixMetric()
if x0 is None:
x0 = 'similarity'
if bounds is None:
bounds = [(-30, 30), (-30, 30), (-30, 30),
(-45, 45), (-45, 45), (-45, 45), (0.8, 1.2)]
# TODO this can be speeded up by using directly the centroids
static = select_random_set_of_streamlines(model_bundle,
select_model, rng=self.rng)
moving = select_random_set_of_streamlines(neighb_streamlines,
select_target, rng=self.rng)
static = set_number_of_points(static, nb_pts)
moving = set_number_of_points(moving, nb_pts)
slr = StreamlineLinearRegistration(metric=metric, x0=x0,
bounds=bounds,
method=method)
slm = slr.optimize(static, moving)
transf_streamlines = neighb_streamlines.copy()
transf_streamlines._data = apply_affine(
slm.matrix, transf_streamlines._data)
transf_matrix = slm.matrix
slr_bmd = slm.fopt
slr_iterations = slm.iterations
if self.verbose:
print(' Square-root of BMD is %.3f' % (np.sqrt(slr_bmd),))
if slr_iterations is not None:
print(' Number of iterations %d' % (slr_iterations,))
print(' Matrix size {}'.format(slm.matrix.shape))
original = np.get_printoptions()
np.set_printoptions(3, suppress=True)
print(transf_matrix)
print(slm.xopt)
np.set_printoptions(**original)
print(' Duration %0.3f sec. \n' % (time() - t,))
return transf_streamlines, slr_bmd
开发者ID:grlee77,项目名称:dipy,代码行数:60,代码来源:bundles.py
示例20: fullprint
def fullprint(*args, **kwargs):
from pprint import pprint
import numpy
opt = numpy.get_printoptions()
numpy.set_printoptions(threshold='nan')
pprint(*args, **kwargs)
numpy.set_printoptions(**opt)
开发者ID:skconsulting,项目名称:ild,代码行数:7,代码来源:predict_roi.py
注:本文中的numpy.get_printoptions函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论