本文整理汇总了Python中sparse.COO属性的典型用法代码示例。如果您正苦于以下问题:Python sparse.COO属性的具体用法?Python sparse.COO怎么用?Python sparse.COO使用的例子?那么恭喜您, 这里精选的属性代码示例或许可以为您提供帮助。您也可以进一步了解该属性所在类sparse
的用法示例。
在下文中一共展示了sparse.COO属性的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_scipy_sparse_interface
# 需要导入模块: import sparse [as 别名]
# 或者: from sparse import COO [as 别名]
def test_scipy_sparse_interface():
n = 100
m = 10
row = np.random.randint(0, n, size=n, dtype=np.uint16)
col = np.random.randint(0, m, size=n, dtype=np.uint16)
data = np.ones(n, dtype=np.uint8)
inp = (data, (row, col))
x = scipy.sparse.coo_matrix(inp)
xx = sparse.COO(inp)
assert_eq(x, xx, check_nnz=False)
assert_eq(x.T, xx.T, check_nnz=False)
assert_eq(xx.to_scipy_sparse(), x, check_nnz=False)
assert_eq(COO.from_scipy_sparse(xx.to_scipy_sparse()), xx, check_nnz=False)
assert_eq(x, xx, check_nnz=False)
assert_eq(x.T.dot(x), xx.T.dot(xx), check_nnz=False)
assert isinstance(x + xx, COO)
assert isinstance(xx + x, COO)
示例2: test_caching
# 需要导入模块: import sparse [as 别名]
# 或者: from sparse import COO [as 别名]
def test_caching():
x = COO({(9, 9, 9): 1})
assert (
x[:].reshape((100, 10)).transpose().tocsr()
is not x[:].reshape((100, 10)).transpose().tocsr()
)
x = COO({(9, 9, 9): 1}, cache=True)
assert (
x[:].reshape((100, 10)).transpose().tocsr()
is x[:].reshape((100, 10)).transpose().tocsr()
)
x = COO({(1, 1, 1, 1, 1, 1, 1, 2): 1}, cache=True)
for i in range(x.ndim):
x.reshape(x.size)
assert len(x._cache["reshape"]) < 5
示例3: test_clip
# 需要导入模块: import sparse [as 别名]
# 或者: from sparse import COO [as 别名]
def test_clip():
x = np.array([[0, 0, 1, 0, 2], [5, 0, 0, 3, 0]])
s = sparse.COO.from_numpy(x)
assert_eq(s.clip(min=1), x.clip(min=1))
assert_eq(s.clip(max=3), x.clip(max=3))
assert_eq(s.clip(min=1, max=3), x.clip(min=1, max=3))
assert_eq(s.clip(min=1, max=3.0), x.clip(min=1, max=3.0))
assert_eq(np.clip(s, 1, 3), np.clip(x, 1, 3))
with pytest.raises(ValueError):
s.clip()
out = sparse.COO.from_numpy(np.zeros_like(x))
out2 = s.clip(min=1, max=3, out=out)
assert out is out2
assert_eq(out, x.clip(min=1, max=3))
示例4: test_setting_into_numpy_slice
# 需要导入模块: import sparse [as 别名]
# 或者: from sparse import COO [as 别名]
def test_setting_into_numpy_slice():
actual = np.zeros((5, 5))
s = sparse.COO(data=[1, 1], coords=(2, 4), shape=(5,))
# This calls s.__array__(dtype('float64')) which means that __array__
# must accept a positional argument. If not this will raise, of course,
# TypeError: __array__() takes 1 positional argument but 2 were given
with auto_densify():
actual[:, 0] = s
# Might as well check the content of the result as well.
expected = np.zeros((5, 5))
expected[:, 0] = s.todense()
assert_eq(actual, expected)
# Without densification, setting is unsupported.
with pytest.raises(RuntimeError):
actual[:, 0] = s
示例5: get_adj
# 需要导入模块: import sparse [as 别名]
# 或者: from sparse import COO [as 别名]
def get_adj(self, batch, seq_len):
"""
Returns the adjacency matrix required for applying GCN
Parameters
----------
batch: batch returned by getBatch generator
seq_len: Maximum length of sentence in the batch
Returns
-------
Adjacency matrix shape=[Number of dependency labels, Batch size, seq_len, seq_len]
"""
num_edges = np.sum(batch['elen'])
b_ind = np.expand_dims(np.repeat(np.arange(self.p.batch_size), batch['elen']), axis=1)
e_ind = np.reshape(batch['edges'], [-1, 3])[:num_edges]
adj_ind = np.concatenate([b_ind, e_ind], axis=1)
adj_ind = adj_ind[:, [3,0,1,2]]
adj_data = np.ones(num_edges, dtype=np.float32)
return COO(adj_ind.T, adj_data, shape=(self.num_deLabel, self.p.batch_size, seq_len, seq_len)).todense()
示例6: get_mult_function
# 需要导入模块: import sparse [as 别名]
# 或者: from sparse import COO [as 别名]
def get_mult_function(mt: sparse.COO, gradeList,
grades_a=None, grades_b=None, filter_mask=None):
'''
Returns a function that implements the mult_table on two input multivectors
'''
if (filter_mask is None) and (grades_a is not None) and (grades_b is not None):
# If not specified explicitly, we can specify sparseness by grade
filter_mask = np.zeros(mt.nnz, dtype=bool)
k_list, _, m_list = mt.coords
for i in range(len(filter_mask)):
if gradeList[k_list[i]] in grades_a:
if gradeList[m_list[i]] in grades_b:
filter_mask[i] = 1
filter_mask = sparse.COO(coords=mt.coords, data=filter_mask, shape=mt.shape)
if filter_mask is not None:
# We can pass the sparse filter mask directly
mt = sparse.where(filter_mask, mt, mt.dtype.type(0))
return _get_mult_function(mt)
else:
return _get_mult_function_runtime_sparse(mt)
示例7: get_transition_array
# 需要导入模块: import sparse [as 别名]
# 或者: from sparse import COO [as 别名]
def get_transition_array(self) -> Union[np.ndarray, sparse.COO]:
"""Return the transition matrix for the wrapped environment.
Returns
-------
Union[np.ndarray, sparse.COO]
The transition array, either a numpy array or a sparse coordinate based
matrix. Shape (n_states, n_actions, n_states).
"""
raise NotImplementedError()
示例8: array
# 需要导入模块: import sparse [as 别名]
# 或者: from sparse import COO [as 别名]
def array(x, *args, **kwargs):
if isinstance(x, sparse.SparseArray):
return x
if "dtype" in kwargs:
dtype = kwargs["dtype"]
return sparse.COO(np.asarray(x, dtype=dtype))
return sparse.COO(np.asarray(x))
示例9: stack
# 需要导入模块: import sparse [as 别名]
# 或者: from sparse import COO [as 别名]
def stack(arrays, axis=0, compressed_axes=None):
"""
Stack the input arrays along the given dimension.
Parameters
----------
arrays : Iterable[SparseArray]
The input arrays to stack.
axis : int, optional
The axis along which to stack the input arrays.
compressed_axes : iterable, optional
The axes to compress if returning a GCXS array.
Returns
-------
SparseArray
The output stacked array.
Raises
------
ValueError
If all elements of :code:`arrays` don't have the same fill-value.
See Also
--------
numpy.stack : NumPy equivalent function
"""
from ._coo import COO
if any(isinstance(arr, COO) for arr in arrays):
from ._coo import stack as coo_stack
return coo_stack(arrays, axis)
else:
from ._compressed import stack as gcxs_stack
return gcxs_stack(arrays, axis, compressed_axes)
示例10: concatenate
# 需要导入模块: import sparse [as 别名]
# 或者: from sparse import COO [as 别名]
def concatenate(arrays, axis=0, compressed_axes=None):
"""
Concatenate the input arrays along the given dimension.
Parameters
----------
arrays : Iterable[SparseArray]
The input arrays to concatenate.
axis : int, optional
The axis along which to concatenate the input arrays. The default is zero.
compressed_axes : iterable, optional
The axes to compress if returning a GCXS array.
Returns
-------
SparseArray
The output concatenated array.
Raises
------
ValueError
If all elements of :code:`arrays` don't have the same fill-value.
See Also
--------
numpy.concatenate : NumPy equivalent function
"""
from ._coo import COO
if any(isinstance(arr, COO) for arr in arrays):
from ._coo import concatenate as coo_concat
return coo_concat(arrays, axis)
else:
from ._compressed import concatenate as gcxs_concat
return gcxs_concat(arrays, axis, compressed_axes)
示例11: outer
# 需要导入模块: import sparse [as 别名]
# 或者: from sparse import COO [as 别名]
def outer(a, b, out=None):
"""
Return outer product of two sparse arrays.
Parameters
----------
a, b : sparse.SparseArray
The input arrays.
out : sparse.SparseArray
The output array.
Examples
--------
>>> import numpy as np
>>> import sparse
>>> a = sparse.COO(np.arange(4))
>>> o = sparse.outer(a, a)
>>> o.todense()
array([[0, 0, 0, 0],
[0, 1, 2, 3],
[0, 2, 4, 6],
[0, 3, 6, 9]])
"""
from sparse import SparseArray, COO
if isinstance(a, SparseArray):
a = COO(a)
if isinstance(b, SparseArray):
b = COO(b)
return np.multiply.outer(a.flatten(), b.flatten(), out=out)
示例12: test_ufunc_reductions
# 需要导入模块: import sparse [as 别名]
# 或者: from sparse import COO [as 别名]
def test_ufunc_reductions(random_sparse, reduction, kwargs, axis, keepdims):
x = random_sparse
y = x.todense()
xx = reduction(x, axis=axis, keepdims=keepdims, **kwargs)
yy = reduction(y, axis=axis, keepdims=keepdims, **kwargs)
assert_eq(xx, yy)
# If not a scalar/1 element array, must be a sparse array
if xx.size > 1:
assert isinstance(xx, COO)
示例13: test_ufunc_reductions_kwargs
# 需要导入模块: import sparse [as 别名]
# 或者: from sparse import COO [as 别名]
def test_ufunc_reductions_kwargs(reduction, kwargs):
x = sparse.random((2, 3, 4), density=0.5)
y = x.todense()
xx = reduction(x, **kwargs)
yy = reduction(y, **kwargs)
assert_eq(xx, yy)
# If not a scalar/1 element array, must be a sparse array
if xx.size > 1:
assert isinstance(xx, COO)
示例14: test_all_nan_reduction_warning
# 需要导入模块: import sparse [as 别名]
# 或者: from sparse import COO [as 别名]
def test_all_nan_reduction_warning(reduction, axis):
x = random_value_array(np.nan, 1.0)(2 * 3 * 4).reshape(2, 3, 4)
s = COO.from_numpy(x)
with pytest.warns(RuntimeWarning):
getattr(sparse, reduction)(s, axis=axis)
示例15: test_large_reshape
# 需要导入模块: import sparse [as 别名]
# 或者: from sparse import COO [as 别名]
def test_large_reshape():
n = 100
m = 10
row = np.arange(
n, dtype=np.uint16
) # np.random.randint(0, n, size=n, dtype=np.uint16)
col = row % m # np.random.randint(0, m, size=n, dtype=np.uint16)
data = np.ones(n, dtype=np.uint8)
x = COO((data, (row, col)), sorted=True, has_duplicates=False)
assert_eq(x, x.reshape(x.shape))