本文整理汇总了Python中numpy.arrays方法的典型用法代码示例。如果您正苦于以下问题:Python numpy.arrays方法的具体用法?Python numpy.arrays怎么用?Python numpy.arrays使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类numpy
的用法示例。
在下文中一共展示了numpy.arrays方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: generate_tokens
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import arrays [as 别名]
def generate_tokens(self, text: str) -> List[Any]:
""" Split text into padded lists of tokens that are part of the recognized vocabulary
:param text: a piece of text (e.g. a sentence)
:type text: str
:return:
indexed_text (np.array): the token/vocabulary indices of
recognized words in text, padded to the maximum sentence length
mask (np.array): a mask indicating which indices in indexed_text
correspond to words (1s) and which correspond to pads (0s)
:rtype: tuple (of np.arrays)
"""
indexed_text = [
self.word_vocab[word]
if ((word in self.counts) and (self.counts[word]
> self.count_threshold))
else self.word_vocab[UNK]
for word in text.split()
]
pad_length = max((self.token_cutoff - len(indexed_text)), 0)
mask = [1] * min(len(indexed_text), self.token_cutoff) + [0] * pad_length
indexed_text = indexed_text[0:self.token_cutoff] + [self.word_vocab[PAD]] * pad_length
return [np.array(indexed_text), np.array(mask)]
示例2: graph_to_numpy
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import arrays [as 别名]
def graph_to_numpy(graph, dtype=None):
"""
Converts a graph in OGB's library-agnostic format to a representation in
Numpy/Scipy. See the [Open Graph Benchmark's website](https://ogb.stanford.edu)
for more information.
:param graph: OGB library-agnostic graph;
:param dtype: if set, all output arrays will be cast to this dtype.
:return:
- X: np.array of shape (N, F) with the node features;
- A: scipy.sparse adjacency matrix of shape (N, N) in COOrdinate format;
- E: if edge features are available, np.array of shape (n_edges, S),
`None` otherwise.
"""
N = graph['num_nodes']
X = graph['node_feat'].astype(dtype)
row, col = graph['edge_index']
A = sp.coo_matrix((np.ones_like(row), (row, col)), shape=(N, N)).astype(dtype)
E = graph['edge_feat'].astype(dtype)
return X, A, E
示例3: test_numpy_array_equal_unicode_message
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import arrays [as 别名]
def test_numpy_array_equal_unicode_message(self):
# Test ensures that `assert_numpy_array_equals` raises the right
# exception when comparing np.arrays containing differing
# unicode objects (#20503)
expected = """numpy array are different
numpy array values are different \\(33\\.33333 %\\)
\\[left\\]: \\[á, à, ä\\]
\\[right\\]: \\[á, à, å\\]"""
with tm.assert_raises_regex(AssertionError, expected):
assert_numpy_array_equal(np.array([u'á', u'à', u'ä']),
np.array([u'á', u'à', u'å']))
with tm.assert_raises_regex(AssertionError, expected):
assert_almost_equal(np.array([u'á', u'à', u'ä']),
np.array([u'á', u'à', u'å']))
示例4: as_array
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import arrays [as 别名]
def as_array(struct):
"""
Given a dictionary of lists or tuples returns dictionary of np.arrays of same structure.
Args:
struct: dictionary of list, tuples etc.
Returns:
dict of np.arrays
"""
if isinstance(struct,dict):
out = {}
for key, value in struct.items():
out[key] = as_array(value)
return out
else:
return np.asarray(struct)
示例5: _interpolate_single_key
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import arrays [as 别名]
def _interpolate_single_key(self, return_key, tri_index, x, y):
"""
Performs the interpolation at points belonging to the triangulation
(inside an unmasked triangles).
Parameters
----------
return_index : string key from {'z', 'dzdx', 'dzdy'}
Identifies the requested values (z or its derivatives)
tri_index : 1d integer array
Valid triangle index (-1 prohibited)
x, y : 1d arrays, same shape as `tri_index`
Valid locations where interpolation is requested.
Returns
-------
ret : 1-d array
Returned array of the same size as *tri_index*
"""
raise NotImplementedError("TriInterpolator subclasses" +
"should implement _interpolate_single_key!")
示例6: get_function_hessians
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import arrays [as 别名]
def get_function_hessians(self, alpha, J, ecc, dofs):
"""
Parameters
----------
*alpha* is a (N x 3 x 1) array (array of column-matrices) of
barycentric coordinates
*J* is a (N x 2 x 2) array of jacobian matrices (jacobian matrix at
triangle first apex)
*ecc* is a (N x 3 x 1) array (array of column-matrices) of triangle
eccentricities
*dofs* is a (N x 1 x 9) arrays (arrays of row-matrices) of computed
degrees of freedom.
Returns
-------
Returns the values of interpolated function 2nd-derivatives
[d2z/dx2, d2z/dy2, d2z/dxdy] in global coordinates at locations alpha,
as a column-matrices of shape (N x 3 x 1).
"""
d2sdksi2 = self.get_d2Sidksij2(alpha, ecc)
d2fdksi2 = _prod_vectorized(dofs, d2sdksi2)
H_rot = self.get_Hrot_from_J(J)
d2fdx2 = _prod_vectorized(d2fdksi2, H_rot)
return _transpose_vectorized(d2fdx2)
示例7: _to_matrix_vectorized
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import arrays [as 别名]
def _to_matrix_vectorized(M):
"""
Builds an array of matrices from individuals np.arrays of identical
shapes.
*M*: ncols-list of nrows-lists of shape sh.
Returns M_res np.array of shape (sh, nrow, ncols) so that:
M_res[...,i,j] = M[i][j]
"""
assert isinstance(M, (tuple, list))
assert all(isinstance(item, (tuple, list)) for item in M)
c_vec = np.asarray([len(item) for item in M])
assert np.all(c_vec-c_vec[0] == 0)
r = len(M)
c = c_vec[0]
M00 = np.asarray(M[0][0])
dt = M00.dtype
sh = [M00.shape[0], r, c]
M_ret = np.empty(sh, dtype=dt)
for irow in range(r):
for icol in range(c):
M_ret[:, irow, icol] = np.asarray(M[irow][icol])
return M_ret
示例8: compute_neighbors_rapids
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import arrays [as 别名]
def compute_neighbors_rapids(
X: np.ndarray,
n_neighbors: int
):
"""Compute nearest neighbors using RAPIDS cuml.
Parameters
----------
X: array of shape (n_samples, n_features)
The data to compute nearest neighbors for.
n_neighbors
The number of neighbors to use.
Returns
-------
**knn_indices**, **knn_dists** : np.arrays of shape (n_observations, n_neighbors)
"""
from cuml.neighbors import NearestNeighbors
nn = NearestNeighbors(n_neighbors=n_neighbors)
X_contiguous = np.ascontiguousarray(X, dtype=np.float32)
nn.fit(X_contiguous)
knn_distsq, knn_indices = nn.kneighbors(X_contiguous)
return knn_indices, np.sqrt(knn_distsq) # cuml uses sqeuclidean metric so take sqrt
示例9: group_points_by_symmetry
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import arrays [as 别名]
def group_points_by_symmetry(self, points):
"""
This function classifies the points into groups according to the box symmetry given by spglib.
Args:
points: (np.array/list) nx3 array which contains positions
Returns: list of arrays containing geometrically equivalent positions
It is possible that the original points are not found in the returned list, as the positions outsie
the box will be projected back to the box.
"""
struct_copy = self.copy()
points = np.array(points).reshape(-1, 3)
struct_copy += Atoms(elements=len(points) * ["Hs"], positions=points)
struct_copy.center_coordinates_in_unit_cell()
group_IDs = struct_copy.get_symmetry()["equivalent_atoms"][
struct_copy.select_index("Hs")
]
return [
np.round(points[group_IDs == ID], decimals=8) for ID in np.unique(group_IDs)
]
示例10: write
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import arrays [as 别名]
def write(self, filename, format=None, **kwargs):
"""
Write atoms object to a file.
see ase.io.write for formats.
kwargs are passed to ase.io.write.
Args:
filename:
format:
**kwargs:
Returns:
"""
from ase.io import write
atoms = self.copy()
atoms.arrays["positions"] = atoms.positions
write(filename, atoms, format, **kwargs)
示例11: parse_frame_line
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import arrays [as 别名]
def parse_frame_line(frame_line):
"""parse a line in otf output.
:param frame_line: frame line to be parsed
:type frame_line: string
:return: species, position, force, uncertainty, and velocity of atom
:rtype: list, np.arrays
"""
frame_line = frame_line.split()
spec = str(frame_line[0])
position = np.array([float(n) for n in frame_line[1:4]])
force = np.array([float(n) for n in frame_line[4:7]])
uncertainty = np.array([float(n) for n in frame_line[7:10]])
velocity = np.array([float(n) for n in frame_line[10:13]])
return spec, position, force, uncertainty, velocity
示例12: make_dataset
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import arrays [as 别名]
def make_dataset(x, y=None):
"""Create a slice Dataset from a pandas DataFrame and labels"""
# TODO(markdaooust): simplify this after the 1.4 cut.
# Convert the DataFrame to a dict
x = dict(x)
# Convert the pd.Series to np.arrays
for key in x:
x[key] = np.array(x[key])
items = [x]
if y is not None:
items.append(np.array(y, dtype=np.float32))
# Create a Dataset of slices
return tf.data.Dataset.from_tensor_slices(tuple(items))
示例13: test_numpy_array_equal_unicode
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import arrays [as 别名]
def test_numpy_array_equal_unicode():
# see gh-20503
#
# Test ensures that `assert_numpy_array_equals` raises the right
# exception when comparing np.arrays containing differing unicode objects.
msg = """numpy array are different
numpy array values are different \\(33\\.33333 %\\)
\\[left\\]: \\[á, à, ä\\]
\\[right\\]: \\[á, à, å\\]"""
with pytest.raises(AssertionError, match=msg):
assert_numpy_array_equal(np.array([u"á", u"à", u"ä"]),
np.array([u"á", u"à", u"å"]))
示例14: plot_correlations
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import arrays [as 别名]
def plot_correlations(corrs, errors=None, ax=None, **plot_kwargs):
"""
Correlation vs CCA dimension
:param corrs: correlation values for the CCA dimensions
:type corrs: 1-D vector
:param errors: error values
:type shuffled: 1-D array of size len(corrs)
:param ax: axis to plot on (default None)
:type ax: matplotlib axis object
:return: axis if specified, or plot if axis = None
"""
# evaluate if np.arrays are passed
assert type(corrs) is np.ndarray, "'corrs' is not a numpy array."
if errors is not None:
assert type(errors) is np.ndarray, "'errors' is not a numpy array."
# create axis if no axis is passed
if ax is None:
ax = plt.gca()
# get the data for the x and y axis
y_data = corrs
x_data = range(1, (len(corrs) + 1))
# create the plot object
ax.plot(x_data, y_data, **plot_kwargs)
if errors is not None:
ax.fill_between(x_data, y_data - errors, y_data + errors, **plot_kwargs, alpha=0.2)
# change y and x labels and ticks
ax.set_xticks(x_data)
ax.set_ylabel("Correlation")
ax.set_xlabel("CCA dimension")
return ax
示例15: get_features_for_one
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import arrays [as 别名]
def get_features_for_one(self, x):
'''
Computes KNN features for a single object `x`
'''
NN_output = self.NN.kneighbors(x)
# Vector of size `n_neighbors`
# Stores indices of the neighbors
# NN_output = distances,indices
neighs = NN_output[1][0]
# Vector of size `n_neighbors`
# Stores distances to corresponding neighbors
neighs_dist = NN_output[0][0]
# Vector of size `n_neighbors`
# Stores labels of corresponding neighbors
neighs_y = self.y_train[neighs]
## ========================================== ##
## YOUR CODE BELOW
## ========================================== ##
# We will accumulate the computed features here
# Eventually it will be a list of lists or np.arrays
# and we will use np.hstack to concatenate those
return_list = []
return return_list