本文整理匯總了Python中numpy.ndarry方法的典型用法代碼示例。如果您正苦於以下問題:Python numpy.ndarry方法的具體用法?Python numpy.ndarry怎麽用?Python numpy.ndarry使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類numpy
的用法示例。
在下文中一共展示了numpy.ndarry方法的9個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: get_actions_given_tasks
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import ndarry [as 別名]
def get_actions_given_tasks(self, observations, task_ids):
"""Sample a batch of actions given observations and task ids.
Args:
observations (np.ndarray): Observations from the environment, with
shape :math:`(T, O)`. T is the number of environment steps,
O is the dimension of observation.
task_ids (np.ndarry): One-hot task ids, with shape :math:`(T, N)`.
T is the number of environment steps, N is the number of tasks.
Returns:
np.ndarray: Actions sampled from the policy,
with shape :math:`(T, A)`. T is the number of environment
steps, A is the dimension of action.
dict: Action distribution information, , with keys:
- mean (numpy.ndarray): Mean of the distribution,
with shape :math:`(T, A)`. T is the number of
environment steps. A is the dimension of action.
- log_std (numpy.ndarray): Log standard deviation of the
distribution, with shape :math:`(T, A)`. T is the number of
environment steps. A is the dimension of action.
"""
flat_obses = self.observation_space.flatten_n(observations)
flat_obses = np.expand_dims(flat_obses, 1)
task_ids = np.expand_dims(task_ids, 1)
samples, means, log_stds = self._f_dist_obs_task(flat_obses, task_ids)
samples = self.action_space.unflatten_n(np.squeeze(samples, 1))
means = self.action_space.unflatten_n(np.squeeze(means, 1))
log_stds = self.action_space.unflatten_n(np.squeeze(log_stds, 1))
return samples, dict(mean=means, log_std=log_stds)
示例2: _polynomial_expansion
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import ndarry [as 別名]
def _polynomial_expansion(self, summary_statistics):
"""Helper function that does the polynomial expansion and includes cross-product
terms of summary_statistics, already calculated summary statistics.
Parameters
----------
summary_statistics: numpy.ndarray
nxp matrix where n is number of data points in the datasets data set and p number os
summary statistics calculated.
Returns
-------
numpy.ndarray
nx(p+degree*p+cross*nchoosek(p,2)) matrix where for each of the n pointss with
p statistics, degree*p polynomial expansion term and cross*nchoosek(p,2) many
cross-product terms are calculated.
"""
# Check summary_statistics is a np.ndarry
if not isinstance(summary_statistics, np.ndarray):
raise TypeError('Summary statistics is not of allowed types')
# Include the polynomial expansion
result = summary_statistics
for ind in range(2, self.degree + 1):
result = np.column_stack((result, np.power(summary_statistics, ind)))
# Include the cross-product term
if self.cross == True and summary_statistics.shape[1] > 1:
# Convert to a matrix
for ind1 in range(0, summary_statistics.shape[1]):
for ind2 in range(ind1 + 1, summary_statistics.shape[1]):
result = np.column_stack((result, summary_statistics[:, ind1] * summary_statistics[:, ind2]))
return result
示例3: load_data_wrapper
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import ndarry [as 別名]
def load_data_wrapper():
"""Return a tuple containing ``(training_data, validation_data,
test_data)``. Based on ``load_data``, but the format is more
convenient for use in our implementation of neural networks.
In particular, ``training_data`` is a list containing 50,000
2-tuples ``(x, y)``. ``x`` is a 784-dimensional numpy.ndarray
containing the input image. ``y`` is a 10-dimensional
numpy.ndarray representing the unit vector corresponding to the
correct digit for ``x``.
``validation_data`` and ``test_data`` are lists containing 10,000
2-tuples ``(x, y)``. In each case, ``x`` is a 784-dimensional
numpy.ndarry containing the input image, and ``y`` is the
corresponding classification, i.e., the digit values (integers)
corresponding to ``x``.
Obviously, this means we're using slightly different formats for
the training data and the validation / test data. These formats
turn out to be the most convenient for use in our neural network
code."""
tr_d, va_d, te_d = load_data()
print("Shape of training data",tr_d.shape)
training_inputs = [np.reshape(x, (1024, 1)) for x in tr_d[0]]
training_results = [vectorized_result(y) for y in tr_d[1]]
training_data = zip(training_inputs, training_results)
validation_inputs = [np.reshape(x, (1024, 1)) for x in va_d[0]]
validation_data = zip(validation_inputs, va_d[1])
test_inputs = [np.reshape(x, (1024, 1)) for x in te_d[0]]
test_data = zip(test_inputs, te_d[1])
return (training_data, validation_data, test_data)
示例4: k_means
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import ndarry [as 別名]
def k_means(points: np.ndarray):
"""返回一個數組經kmeans分類後的k值以及標簽,k值由計算拐點給出
Args:
points (np.ndarray): 需分類數據
Returns:
Tuple[int, np.ndarry]: k值以及標簽數組
"""
# Define criteria = ( type, max_iter = 10 , epsilon = 1.0 )
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)
# Set flags (Just to avoid line break in the code)
flags = cv2.KMEANS_RANDOM_CENTERS
length = []
max_k = min(10, points.shape[0])
for k in range(2, max_k + 1):
avg = 0
for i in range(5):
compactness, _, _ = cv2.kmeans(
points, k, None, criteria, 10, flags)
avg += compactness
avg /= 5
length.append(avg)
peek_pos = find_peek(length)
k = peek_pos + 2
# print(k)
return k, cv2.kmeans(points, k, None, criteria, 10, flags)[1] # labels
示例5: con2R
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import ndarry [as 別名]
def con2R(arr):
"""
Convert user desired contrasts to R-flavored contrast matrix that can be passed directly to lm(). Reference: https://goo.gl/E4Mms2
Args:
arr (np.ndarry): 2d numpy array arranged as contrasts X factor levels
Returns:
np.ndarray: 2d contrast matrix as expected by R's contrasts() function
"""
intercept = np.repeat(1.0 / arr.shape[1], arr.shape[1])
mat = np.vstack([intercept, arr])
inv = np.linalg.inv(mat)[:, 1:]
return inv
示例6: R2con
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import ndarry [as 別名]
def R2con(arr):
"""
Convert R-flavored contrast matrix to intepretable contrasts as would be specified by user. Reference: https://goo.gl/E4Mms2
Args:
arr (np.ndarry): 2d contrast matrix output from R's contrasts() function.
Returns:
np.ndarray: 2d array organized as contrasts X factor levels
"""
intercept = np.ones((arr.shape[0], 1))
mat = np.column_stack([intercept, arr])
inv = np.linalg.inv(mat)
return inv
示例7: set_regular_grid
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import ndarry [as 別名]
def set_regular_grid(self, extent, resolution):
"""
Set a regular grid into the values parameters for further computations
Args:
extent (list, np.ndarry): [x_min, x_max, y_min, y_max, z_min, z_max]
resolution (list, np.ndarray): [nx, ny, nz]
"""
self.extent = np.asarray(extent, dtype='float64')
self.resolution = np.asarray(resolution)
self.values = self.create_regular_grid_3d(extent, resolution)
self.length = self.values.shape[0]
self.dx, self.dy, self.dz = self.get_dx_dy_dz()
return self.values
示例8: __slim_tcr_decomposition
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import ndarry [as 別名]
def __slim_tcr_decomposition(super_core, threshold):
"""
Two-cell reaction decomposition.
Decompose a super-core representing the interactions between two cells.
Parameters
----------
super_core : np.ndarray
tensor with order 4
threshold : float
threshold for reduced SVD decompositions
Returns
-------
core_left : np.ndarray
TT core for first cell
core_right : np.ndarry
TT core for second cell
rank : int
TT rank
"""
# number of states
dimension_1 = super_core.shape[0]
dimension_2 = super_core.shape[2]
# apply SVD in order to split the super-core
[u, s, v] = linalg.svd(super_core.reshape(dimension_1 ** 2, dimension_2 ** 2),
full_matrices=False, overwrite_a=True, check_finite=False, lapack_driver='gesvd')
# rank reduction
if threshold != 0:
indices = np.where(s / s[0] > threshold)[0]
u = u[:, indices]
s = s[indices]
v = v[indices, :]
# set quantities for decomposition
rank = u.shape[1]
core_left = (u.dot(np.diag(s))).reshape(dimension_1, dimension_1, rank)
core_right = v.reshape(rank, dimension_2, dimension_2)
return core_left, core_right, rank
示例9: ao2mo
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import ndarry [as 別名]
def ao2mo(mat, coeffs, MOrange=None, MOrangei=None, MOrangej=None, MOrangek=None, MOrangel=None):
'''Transforms array of one- or two-electron integrals from AO to MO basis.
**Parameters:**
mat : 2 or 4 dimensional numpy.ndarray
integrals to be transformed
coeffs : 2 dimensional numpy.ndarry
MO coefficients
MOrangei, MOrangej, MOrangek, MOrangel : list|range object|None
Only transform selected MOs for indices i, j, k and l respectively.
MOrange: list or range object or None
Set same range for all indices.
**Returns:**
numpy.ndarray
'''
assert len(mat.shape) in (2, 4), "'mat' musst be of size 2 or 4."
if MOrange is not None:
MOrangei = MOrange
MOrangej = MOrange
MOrangek = MOrange
MOrangel = MOrange
if MOrangei is None:
MOrangei = range(coeffs.shape[0])
if MOrangej is None:
MOrangej = range(coeffs.shape[0])
if MOrangek is None:
MOrangek = range(coeffs.shape[0])
if MOrangel is None:
MOrangel = range(coeffs.shape[0])
# discard zero columns in MO coeffs
if len(mat.shape) == 2:
MOs = list(set(chain(MOrangei, MOrangej)))
elif len(mat.shape) == 4:
MOs = list(set(chain(MOrangei, MOrangej, MOrangek, MOrangel)))
AOs = numpy.where(~numpy.isclose(coeffs[MOs,:], 1e-15).all(axis=0))[0]
coeffs = coeffs[:,AOs]
if len(mat.shape) == 2:
# 1-electron integrals
mat = mat[numpy.ix_(AOs, AOs)]
return numpy.dot(coeffs[MOrangei,:], numpy.dot(mat, coeffs[MOrangej,:].T))
elif len(mat.shape) == 4:
# 2-electron integrals
mat = mat[numpy.ix_(AOs, AOs, AOs, AOs)]
mat = numpy.tensordot(mat, coeffs[MOrangei,:], axes=(0, 1))
mat = numpy.tensordot(mat, coeffs[MOrangej,:], axes=(0, 1))
mat = numpy.tensordot(mat, coeffs[MOrangek,:], axes=(0, 1))
mat = numpy.tensordot(mat, coeffs[MOrangel,:], axes=(0, 1))
return mat