Python numpy 模块,rank() 实例源码
我们从Python开源项目中,提取了以下38个代码示例,用于说明如何使用numpy.rank()。
def get_cube_list(category,count,orderType):
url=cube_list_url+"?category="+category+"&count="+count+"&market=cn&profit="+orderType
data = request(url,cookie)
jsonObj = json.loads(data.read())
rank = 1
for TopestCube in jsonObj["list"]:
created_at = TopestCube["created_at"]
ltime=time.localtime(created_at/1000.0)
created_at_str=time.strftime("%Y-%m-%d", ltime)
TopestCube["created_at"] = created_at_str
updated_at = TopestCube["updated_at"]
ltime=time.localtime(updated_at/1000.0)
updated_at_str=time.strftime("%Y-%m-%d", ltime)
TopestCube["updated_at"] = updated_at_str
TopestCube["category"] = category
TopestCube["orderType"] = orderType
TopestCube["Rank"] = rank
del(TopestCube["style"],TopestCube["description"],TopestCube["owner"])
cubelist_save(TopestCube)
rank = rank + 1
def clean_warning_registry():
"""Safe way to reset warnings """
warnings.resetwarnings()
reg = "__warningregistry__"
bad_names = ['MovedModule'] # this is in six.py, and causes bad things
for mod in list(sys.modules.values()):
if mod.__class__.__name__ not in bad_names and hasattr(mod, reg):
getattr(mod, reg).clear()
# hack to deal with old scipy/numpy in tests
if os.getenv('TRAVIS') == 'true' and sys.version.startswith('2.6'):
warnings.simplefilter('default')
try:
np.rank([])
except Exception:
pass
warnings.simplefilter('always')
def __init__(self, config, rng=None):
self.rng = np.random.RandomState(1) if rng is None else rng
self.data_path = os.path.join(config.data_dir, 'gaze')
self.sample_path = os.path.join(self.data_path, config.sample_dir)
self.batch_size = config.batch_size
self.debug = config.debug
self.real_data, synthetic_image_path = load(config, self.data_path, self.sample_path, rng)
self.synthetic_data_paths = np.array(glob(os.path.join(synthetic_image_path, '*_cropped.png')))
self.synthetic_data_dims = list(imread(self.synthetic_data_paths[0]).shape) + [1]
self.synthetic_data_paths.sort()
if np.rank(self.real_data) == 3:
self.real_data = np.expand_dims(self.real_data, -1)
self.real_p = 0
def test(self):
a = np.arange(10)
assert_warns(np.VisibleDeprecationWarning, np.rank, a)
def k(self, x, y):
"""Kernel function."""
for arg in [x, y]:
assert isinstance(arg, (float, np.float32, np.float64)) or \
(isinstance(arg, np.ndarray) and np.rank(arg) == 1)
mi = self.offset + np.minimum(x, y)
return self.theta**2 * (mi**3/3.0 + 0.5*np.abs(x-y)*mi**2)
def kd(self, x, y):
"""Derivative of kernel function, 1st derivative w.r.t. right argument."""
for arg in [x, y]:
assert isinstance(arg, (float, np.float32, np.float64)) or \
(isinstance(arg, np.ndarray) and np.rank(arg) == 1)
xx = x + self.offset
yy = y + self.offset
return self.theta**2 * np.where(x<y, 0.5*xx**2, xx*yy-0.5*yy**2)
def dkd(self, x, y):
"""Derivative of kernel function, 1st derivative w.r.t. both arguments."""
for arg in [x, y]:
assert isinstance(arg, (float, np.float32, np.float64)) or \
(isinstance(arg, np.ndarray) and np.rank(arg) == 1)
xx = x+self.offset
yy = y+self.offset
return self.theta**2 * np.minimum(xx, yy)
def d2k(self, x, y):
"""Derivative of kernel function, 2nd derivative w.r.t. left argument."""
for arg in [x, y]:
assert isinstance(arg, (float, np.float32, np.float64)) or \
(isinstance(arg, np.ndarray) and np.rank(arg) == 1)
return self.theta**2 * np.where(x<y, y-x, 0.)
def d3k(self, x, y):
"""Derivative of kernel function, 3rd derivative w.r.t. left argument."""
for arg in [x, y]:
assert isinstance(arg, (float, np.float32, np.float64)) or \
(isinstance(arg, np.ndarray) and np.rank(arg) == 1)
return self.theta**2 * np.where(x<y, -1., 0.)
def test(self):
a = np.arange(10)
assert_warns(np.VisibleDeprecationWarning, np.rank, a)
def __init__(self, filename=None, scale2float=True):
"""Read a .wav file from disk"""
assert filename is not None, "Specify a filename"
self.filename = filename
fs, samples = scipy.io.wavfile.read(filename)
if np.rank(samples) == 1:
samples = np.expand_dims(samples, axis=1)
Audio.__init__(self, fs=fs, initialdata=samples)
del samples # just to make sure
if scale2float:
self.convert_to_float(targetbits=64)
def test_lin_to_db_to_lin_arrays(self):
x = lin2db(db2lin(( 1.234567, 2.345678)))
self.assertEqual(np.rank(x), 1)
self.assertEqual(len(x), 2)
self.assertAlmostEqual(x[0], 1.234567, places=6)
self.assertAlmostEqual(x[1], 2.345678, places=6)
def test_pow_to_db_to_pow_arrays(self):
x = pow2db(db2pow(( 1.234567, 2.345678)))
self.assertEqual(np.rank(x), 1)
self.assertEqual(len(x), 2)
self.assertAlmostEqual(x[0], 1.234567, places=6)
self.assertAlmostEqual(x[1], 2.345678, places=6)
def test_single(self):
x = lin2db(1)
self.assertEqual(np.rank(x), 0)
self.assertAlmostEqual(x, 0.0, places=6)
def test_tuple(self):
x = lin2db((1, 0.1))
self.assertEqual(np.rank(x), 1)
self.assertAlmostEqual(x[0], 0.0, places=6)
self.assertAlmostEqual(x[1], -20.0, places=6)
def test_np_rank_1(self):
x = lin2db(np.ones(10))
self.assertEqual(np.rank(x), 1)
self.assertTrue((x < 0.0001).all())
self.assertTrue((x > -0.0001).all())
def test_np_rank_2_10x4(self):
x = lin2db(np.ones((10, 4)))
self.assertEqual(np.rank(x), 2)
self.assertTrue((x < 0.0001).all())
self.assertTrue((x > -0.0001).all())
def test_np_rank_2_4x10(self):
x = lin2db(np.ones((4, 10)))
self.assertEqual(np.rank(x), 2)
self.assertTrue((x < 0.0001).all())
self.assertTrue((x > -0.0001).all())
def test_single(self):
x = db2lin(0)
self.assertEqual(np.rank(x), 0)
self.assertAlmostEqual(x, 1.0, places=6)
def test_tuple(self):
x = db2lin((40, -40))
self.assertEqual(np.rank(x), 1)
self.assertAlmostEqual(x[0], 100.0, places=6)
self.assertAlmostEqual(x[1], 0.01, places=6)
def test_np_rank_1(self):
x = db2lin(np.zeros(10))
self.assertEqual(np.rank(x), 1)
self.assertTrue((x < 1.0001).all())
self.assertTrue((x > 0.9999).all())
def test_np_rank_2_10x4(self):
x = db2lin(np.zeros((10, 4)))
self.assertEqual(np.rank(x), 2)
self.assertTrue((x < 1.0001).all())
self.assertTrue((x > 0.9999).all())
def test_np_rank_2_4x10(self):
x = db2lin(np.zeros((4, 10)))
self.assertEqual(np.rank(x), 2)
self.assertTrue((x < 1.0001).all())
self.assertTrue((x > 0.9999).all())
def test(self):
a = np.arange(10)
assert_warns(np.VisibleDeprecationWarning, np.rank, a)
def test(self):
a = np.arange(10)
assert_warns(np.VisibleDeprecationWarning, np.rank, a)
def test(self):
a = np.arange(10)
assert_warns(np.VisibleDeprecationWarning, np.rank, a)
def test(self):
a = np.arange(10)
assert_warns(np.VisibleDeprecationWarning, np.rank, a)
def _addCustomData(self, value, name, **kwargs):
'''
The custom data will be added as an info line in the form:
Custom data: name : value
'''
if numpy.rank(value) > 0:
v = 'Array(%s)' % str(numpy.shape(value))
else:
v = str(value)
self._stream._output('Custom data: %s : %s' % (name, v))
self._stream._flushOutput()
def _addCustomData(self, value, name, **kwargs):
'''
The custom data will be added as a comment line in the form::
#C name : value
..note:: non-scalar values (or name/values containing end-of-line) will not be written
'''
if self.filename is None:
self.info(
'Custom data "%s" will not be stored in SPEC file. Reason: uninitialized file', name)
return
if numpy.rank(value) > 0: # ignore non-scalars
self.info(
'Custom data "%s" will not be stored in SPEC file. Reason: value is non-scalar', name)
return
v = str(value)
if '\n' in v or '\n' in name: # ignore if name or the string representation of the value contains end-of-line
self.info(
'Custom data "%s" will not be stored in SPEC file. Reason: unsupported format', name)
return
fileWasClosed = self.fd is None or self.fd.closed
if fileWasClosed:
try:
self.fd = open(self.filename, 'a')
except:
self.info(
'Custom data "%s" will not be stored in SPEC file. Reason: cannot open file', name)
return
self.fd.write('#C %s : %s\n' % (name, v))
self.fd.flush()
if fileWasClosed:
self.fd.close() # leave the file descriptor as found
def test(self):
a = np.arange(10)
assert_warns(np.VisibleDeprecationWarning, np.rank, a)
def rank(a):
"""
Return the number of dimensions of an array.
If `a` is not already an array, a conversion is attempted.
Scalars are zero dimensional.
.. note::
This function is deprecated in NumPy 1.9 to avoid confusion with
`numpy.linalg.matrix_rank`. The ``ndim`` attribute or function
should be used instead.
Parameters
----------
a : array_like
Array whose number of dimensions is desired. If `a` is not an array,
a conversion is attempted.
Returns
-------
number_of_dimensions : int
The number of dimensions in the array.
See Also
--------
ndim : equivalent function
ndarray.ndim : equivalent property
shape : dimensions of array
ndarray.shape : dimensions of array
Notes
-----
In the old Numeric package, `rank` was the term used for the number of
dimensions, but in Numpy `ndim` is used instead.
Examples
--------
>>> np.rank([1,2,3])
1
>>> np.rank(np.array([[1,2,3],[4,5,6]]))
2
>>> np.rank(1)
0
"""
# 2014-04-12, 1.9
warnings.warn(
"`rank` is deprecated; use the `ndim` attribute or function instead. "
"To find the rank of a matrix see `numpy.linalg.matrix_rank`.",
VisibleDeprecationWarning)
try:
return a.ndim
except AttributeError:
return asarray(a).ndim
def rank(a):
"""
Return the number of dimensions of an array.
If `a` is not already an array, a conversion is attempted.
Scalars are zero dimensional.
.. note::
This function is deprecated in NumPy 1.9 to avoid confusion with
`numpy.linalg.matrix_rank`. The ``ndim`` attribute or function
should be used instead.
Parameters
----------
a : array_like
Array whose number of dimensions is desired. If `a` is not an array,
a conversion is attempted.
Returns
-------
number_of_dimensions : int
The number of dimensions in the array.
See Also
--------
ndim : equivalent function
ndarray.ndim : equivalent property
shape : dimensions of array
ndarray.shape : dimensions of array
Notes
-----
In the old Numeric package, `rank` was the term used for the number of
dimensions, but in Numpy `ndim` is used instead.
Examples
--------
>>> np.rank([1,2,3])
1
>>> np.rank(np.array([[1,2,3],[4,5,6]]))
2
>>> np.rank(1)
0
"""
# 2014-04-12, 1.9
warnings.warn(
"`rank` is deprecated; use the `ndim` attribute or function instead. "
"To find the rank of a matrix see `numpy.linalg.matrix_rank`.",
VisibleDeprecationWarning)
try:
return a.ndim
except AttributeError:
return asarray(a).ndim
def rank(a):
"""
Return the number of dimensions of an array.
If `a` is not already an array, a conversion is attempted.
Scalars are zero dimensional.
.. note::
This function is deprecated in NumPy 1.9 to avoid confusion with
`numpy.linalg.matrix_rank`. The ``ndim`` attribute or function
should be used instead.
Parameters
----------
a : array_like
Array whose number of dimensions is desired. If `a` is not an array,
a conversion is attempted.
Returns
-------
number_of_dimensions : int
The number of dimensions in the array.
See Also
--------
ndim : equivalent function
ndarray.ndim : equivalent property
shape : dimensions of array
ndarray.shape : dimensions of array
Notes
-----
In the old Numeric package, `rank` was the term used for the number of
dimensions, but in Numpy `ndim` is used instead.
Examples
--------
>>> np.rank([1,2,3])
1
>>> np.rank(np.array([[1,2,3],[4,5,6]]))
2
>>> np.rank(1)
0
"""
# 2014-04-12, 1.9
warnings.warn(
"`rank` is deprecated; use the `ndim` attribute or function instead. "
"To find the rank of a matrix see `numpy.linalg.matrix_rank`.",
VisibleDeprecationWarning)
try:
return a.ndim
except AttributeError:
return asarray(a).ndim
def rank(a):
"""
Return the number of dimensions of an array.
If `a` is not already an array, a conversion is attempted.
Scalars are zero dimensional.
.. note::
This function is deprecated in NumPy 1.9 to avoid confusion with
`numpy.linalg.matrix_rank`. The ``ndim`` attribute or function
should be used instead.
Parameters
----------
a : array_like
Array whose number of dimensions is desired. If `a` is not an array,
a conversion is attempted.
Returns
-------
number_of_dimensions : int
The number of dimensions in the array.
See Also
--------
ndim : equivalent function
ndarray.ndim : equivalent property
shape : dimensions of array
ndarray.shape : dimensions of array
Notes
-----
In the old Numeric package, `rank` was the term used for the number of
dimensions, but in Numpy `ndim` is used instead.
Examples
--------
>>> np.rank([1,2,3])
1
>>> np.rank(np.array([[1,2,3],[4,5,6]]))
2
>>> np.rank(1)
0
"""
# 2014-04-12, 1.9
warnings.warn(
"`rank` is deprecated; use the `ndim` attribute or function instead. "
"To find the rank of a matrix see `numpy.linalg.matrix_rank`.",
VisibleDeprecationWarning)
try:
return a.ndim
except AttributeError:
return asarray(a).ndim
def rank(a):
"""
Return the number of dimensions of an array.
If `a` is not already an array, a conversion is attempted.
Scalars are zero dimensional.
.. note::
This function is deprecated in NumPy 1.9 to avoid confusion with
`numpy.linalg.matrix_rank`. The ``ndim`` attribute or function
should be used instead.
Parameters
----------
a : array_like
Array whose number of dimensions is desired. If `a` is not an array,
a conversion is attempted.
Returns
-------
number_of_dimensions : int
The number of dimensions in the array.
See Also
--------
ndim : equivalent function
ndarray.ndim : equivalent property
shape : dimensions of array
ndarray.shape : dimensions of array
Notes
-----
In the old Numeric package, `rank` was the term used for the number of
dimensions, but in Numpy `ndim` is used instead.
Examples
--------
>>> np.rank([1,2,3])
1
>>> np.rank(np.array([[1,2,3],[4,5,6]]))
2
>>> np.rank(1)
0
"""
# 2014-04-12, 1.9
warnings.warn(
"`rank` is deprecated; use the `ndim` attribute or function instead. "
"To find the rank of a matrix see `numpy.linalg.matrix_rank`.",
VisibleDeprecationWarning)
try:
return a.ndim
except AttributeError:
return asarray(a).ndim
def rank(a):
"""
Return the number of dimensions of an array.
If `a` is not already an array, a conversion is attempted.
Scalars are zero dimensional.
.. note::
This function is deprecated in NumPy 1.9 to avoid confusion with
`numpy.linalg.matrix_rank`. The ``ndim`` attribute or function
should be used instead.
Parameters
----------
a : array_like
Array whose number of dimensions is desired. If `a` is not an array,
a conversion is attempted.
Returns
-------
number_of_dimensions : int
The number of dimensions in the array.
See Also
--------
ndim : equivalent function
ndarray.ndim : equivalent property
shape : dimensions of array
ndarray.shape : dimensions of array
Notes
-----
In the old Numeric package, `rank` was the term used for the number of
dimensions, but in NumPy `ndim` is used instead.
Examples
--------
>>> np.rank([1,2,3])
1
>>> np.rank(np.array([[1,2,3],[4,5,6]]))
2
>>> np.rank(1)
0
"""
# 2014-04-12, 1.9
warnings.warn(
"`rank` is deprecated; use the `ndim` attribute or function instead. "
"To find the rank of a matrix see `numpy.linalg.matrix_rank`.",
VisibleDeprecationWarning, stacklevel=2)
try:
return a.ndim
except AttributeError:
return asarray(a).ndim
def estimate_rank(data, tol='auto', return_singular=False,
norm=True, copy=None):
"""Helper to estimate the rank of data
This function will normalize the rows of the data (typically
channels or vertices) such that non-zero singular values
should be close to one.
Parameters
----------
data : array
Data to estimate the rank of (should be 2-dimensional).
tol : float | str
Tolerance for singular values to consider non-zero in
calculating the rank. The singular values are calculated
in this method such that independent data are expected to
have singular value around one. Can be 'auto' to use the
same thresholding as ``scipy.linalg.orth``.
return_singular : bool
If True, also return the singular values that were used
to determine the rank.
norm : bool
If True, data will be scaled by their estimated row-wise norm.
Else data are assumed to be scaled. Defaults to True.
copy : bool
This parameter has been deprecated and will be removed in 0.13.
It is ignored in 0.12.
Returns
-------
rank : int
Estimated rank of the data.
s : array
If return_singular is True, the singular values that were
thresholded to determine the rank are also returned.
"""
if copy is not None:
warn('copy is deprecated and ignored. It will be removed in 0.13.')
data = data.copy() # operate on a copy
if norm is True:
norms = _compute_row_norms(data)
data /= norms[:, np.newaxis]
s = linalg.svd(data, compute_uv=False, overwrite_a=True)
if isinstance(tol, string_types):
if tol != 'auto':
raise ValueError('tol must be "auto" or float')
eps = np.finfo(float).eps
tol = np.max(data.shape) * np.amax(s) * eps
tol = float(tol)
rank = np.sum(s > tol)
if return_singular is True:
return rank, s
else:
return rank
def rank(a):
"""
Return the number of dimensions of an array.
If `a` is not already an array, a conversion is attempted.
Scalars are zero dimensional.
.. note::
This function is deprecated in NumPy 1.9 to avoid confusion with
`numpy.linalg.matrix_rank`. The ``ndim`` attribute or function
should be used instead.
Parameters
----------
a : array_like
Array whose number of dimensions is desired. If `a` is not an array,
a conversion is attempted.
Returns
-------
number_of_dimensions : int
The number of dimensions in the array.
See Also
--------
ndim : equivalent function
ndarray.ndim : equivalent property
shape : dimensions of array
ndarray.shape : dimensions of array
Notes
-----
In the old Numeric package, `rank` was the term used for the number of
dimensions, but in Numpy `ndim` is used instead.
Examples
--------
>>> np.rank([1,2,3])
1
>>> np.rank(np.array([[1,2,3],[4,5,6]]))
2
>>> np.rank(1)
0
"""
# 2014-04-12, 1.9
warnings.warn(
"`rank` is deprecated; use the `ndim` attribute or function instead. "
"To find the rank of a matrix see `numpy.linalg.matrix_rank`.",
VisibleDeprecationWarning)
try:
return a.ndim
except AttributeError:
return asarray(a).ndim