本文整理汇总了Python中numpy.broadcast_to方法的典型用法代码示例。如果您正苦于以下问题:Python numpy.broadcast_to方法的具体用法?Python numpy.broadcast_to怎么用?Python numpy.broadcast_to使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类numpy
的用法示例。
在下文中一共展示了numpy.broadcast_to方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _prepare_value_nd
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import broadcast_to [as 别名]
def _prepare_value_nd(self, value, vshape):
"""Given value and vshape, create an `NDArray` from value with the same
context and dtype as the current one and broadcast it to vshape."""
if isinstance(value, numeric_types):
value_nd = full(shape=vshape, val=value, ctx=self.context, dtype=self.dtype)
elif isinstance(value, NDArray):
value_nd = value.as_in_context(self.context)
if value_nd.dtype != self.dtype:
value_nd = value_nd.astype(self.dtype)
else:
try:
value_nd = array(value, ctx=self.context, dtype=self.dtype)
except:
raise TypeError('NDArray does not support assignment with non-array-like'
' object %s of type %s' % (str(value), str(type(value))))
if value_nd.shape != vshape:
value_nd = value_nd.broadcast_to(vshape)
return value_nd
示例2: test_max_unbounded
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import broadcast_to [as 别名]
def test_max_unbounded(self):
n_batch = 7
ndim_action = 3
mu = np.random.randn(n_batch, ndim_action).astype(np.float32)
mat = np.broadcast_to(
np.eye(ndim_action, dtype=np.float32)[None],
(n_batch, ndim_action, ndim_action))
v = np.random.randn(n_batch).astype(np.float32)
q_out = action_value.QuadraticActionValue(
chainer.Variable(mu),
chainer.Variable(mat),
chainer.Variable(v))
v_out = q_out.max
self.assertIsInstance(v_out, chainer.Variable)
v_out = v_out.array
np.testing.assert_almost_equal(v_out, v)
示例3: test_getitem
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import broadcast_to [as 别名]
def test_getitem(self):
n_batch = 7
ndim_action = 3
mu = np.random.randn(n_batch, ndim_action).astype(np.float32)
mat = np.broadcast_to(
np.eye(ndim_action, dtype=np.float32)[None],
(n_batch, ndim_action, ndim_action))
v = np.random.randn(n_batch).astype(np.float32)
min_action, max_action = -1, 1
qout = action_value.QuadraticActionValue(
chainer.Variable(mu),
chainer.Variable(mat),
chainer.Variable(v),
min_action,
max_action,
)
sliced = qout[:3]
np.testing.assert_equal(sliced.mu.array, mu[:3])
np.testing.assert_equal(sliced.mat.array, mat[:3])
np.testing.assert_equal(sliced.v.array, v[:3])
np.testing.assert_equal(sliced.min_action, min_action)
np.testing.assert_equal(sliced.max_action, max_action)
示例4: unreduce_array
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import broadcast_to [as 别名]
def unreduce_array(array, shape, axis, keepdims):
"""Reverse summing over a dimension, NumPy implementation.
Args:
array: The array that was reduced.
shape: The original shape of the array before reduction.
axis: The axis or axes that were summed.
keepdims: Whether these axes were kept as singleton axes.
Returns:
An array with axes broadcast to match the shape of the original array.
"""
# NumPy uses a special default value for keepdims, which is equivalent to
# False.
if axis is not None and (not keepdims or keepdims is numpy._NoValue): # pylint: disable=protected-access
if isinstance(axis, int):
axis = axis,
for ax in sorted(axis):
array = numpy.expand_dims(array, ax)
return numpy.broadcast_to(array, shape)
# The values are unary functions.
示例5: to_grayscale
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import broadcast_to [as 别名]
def to_grayscale(img, num_output_channels=1):
"""Convert image to grayscale version of image.
Args:
img (numpy ndarray): Image to be converted to grayscale.
Returns:
numpy ndarray: Grayscale version of the image.
if num_output_channels = 1 : returned image is single channel
if num_output_channels = 3 : returned image is 3 channel with r = g = b
"""
if not _is_numpy_image(img):
raise TypeError('img should be numpy ndarray. Got {}'.format(type(img)))
if num_output_channels==1:
img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)[:,:,np.newaxis]
elif num_output_channels==3:
# much faster than doing cvtColor to go back to gray
img = np.broadcast_to(cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)[:,:,np.newaxis], img.shape)
return img
示例6: _broadcast_shape
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import broadcast_to [as 别名]
def _broadcast_shape(*args):
"""Returns the shape of the arrays that would result from broadcasting the
supplied arrays against each other.
"""
if not args:
return ()
# use the old-iterator because np.nditer does not handle size 0 arrays
# consistently
b = np.broadcast(*args[:32])
# unfortunately, it cannot handle 32 or more arguments directly
for pos in range(32, len(args), 31):
# ironically, np.broadcast does not properly handle np.broadcast
# objects (it treats them as scalars)
# use broadcasting to avoid allocating the full array
b = broadcast_to(0, b.shape)
b = np.broadcast(b, *args[pos:(pos + 31)])
return b.shape
示例7: to_grayscale
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import broadcast_to [as 别名]
def to_grayscale(img, num_output_channels=1):
"""Convert image to grayscale version of image.
Args:
img (numpy ndarray): Image to be converted to grayscale.
Returns:
numpy ndarray: Grayscale version of the image.
if num_output_channels = 1 : returned image is single channel
if num_output_channels = 3 : returned image is 3 channel with r = g = b
"""
if not _is_numpy_image(img):
raise TypeError('img should be numpy ndarray. Got {}'.format(type(img)))
if num_output_channels==1:
img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)[:,:,np.newaxis]
elif num_output_channels==3:
# much faster than doing cvtColor to go back to gray
img = np.broadcast_to(cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)[:,:,np.newaxis], img.shape)
return img
示例8: make_batch_mask
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import broadcast_to [as 别名]
def make_batch_mask(mb_size, n_head, max_length_1, max_length_2,
key_seq_lengths=None,
future_mask=False,
mask_value=-10000):
if future_mask:
assert max_length_1 == max_length_2
mask = np.array(
np.broadcast_to(( (-mask_value) * (np.tri(max_length_1, dtype = np.float32)-1))[None,None,:,:],
(mb_size, n_head, max_length_1, max_length_2))
)
else:
mask = np.zeros((mb_size, n_head, max_length_1, max_length_2), dtype = np.float32)
if key_seq_lengths is not None:
assert mb_size == len(key_seq_lengths)
assert min(key_seq_lengths) > 0
assert max(key_seq_lengths) <= max_length_2
for num_batch, length in enumerate(key_seq_lengths):
mask[num_batch, :, :, length:] = mask_value
return mask
示例9: testBroadcastConcat
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import broadcast_to [as 别名]
def testBroadcastConcat(self):
b = builder_lib.ModelBuilderBase()
p = b._BroadcastConcat('p', b._ArgIdx('arg0', [0]), b._ArgIdx('arg1', [1]))
l = p.Instantiate()
# 2 x 1 x 3
x1 = np.asarray([[[1, 2, 3]], [[4, 5, 6]]])
self.assertEqual(x1.shape, (2, 1, 3))
# 1 x 4 x 2
x2 = np.asarray([[[7, 8], [9, 10], [11, 12], [13, 14]]])
self.assertEqual(x2.shape, (1, 4, 2))
y = l.FPropDefaultTheta(tf.constant(x1), tf.constant(x2))
expected_y = np.concatenate([
np.broadcast_to(x1, [2, 4, 3]),
np.broadcast_to(x2, [2, 4, 2]),
], axis=-1) # pyformat: disable
with self.session():
actual_y = self.evaluate(y)
# x1 will be broadcasted to [2, 4, 3]
# x2 will be broadcasted to [2, 4, 2]
# Concatenation on axis=-1 should result in a tensor of shape [2, 4, 5]
self.assertEqual(actual_y.shape, (2, 4, 5))
self.assertAllEqual(actual_y, expected_y)
示例10: __call__
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import broadcast_to [as 别名]
def __call__(self, x, update=True):
"""Normalize mean and variance of values based on emprical values.
Args:
x (ndarray or Variable): Input values
update (bool): Flag to learn the input values
Returns:
ndarray or Variable: Normalized output values
"""
if self.count == 0:
return x
mean = np.broadcast_to(self._mean, x.shape)
std_inv = np.broadcast_to(self._std_inverse, x.shape)
if update:
self.experience(x)
normalized = (x - mean) * std_inv
if self.clip_threshold is not None:
normalized = np.clip(
normalized, -self.clip_threshold, self.clip_threshold)
return normalized
示例11: _broadcast_shape
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import broadcast_to [as 别名]
def _broadcast_shape(*args):
"""Returns the shape of the ararys that would result from broadcasting the
supplied arrays against each other.
"""
if not args:
raise ValueError('must provide at least one argument')
# use the old-iterator because np.nditer does not handle size 0 arrays
# consistently
b = np.broadcast(*args[:32])
# unfortunately, it cannot handle 32 or more arguments directly
for pos in range(32, len(args), 31):
# ironically, np.broadcast does not properly handle np.broadcast
# objects (it treats them as scalars)
# use broadcasting to avoid allocating the full array
b = broadcast_to(0, b.shape)
b = np.broadcast(b, *args[pos:(pos + 31)])
return b.shape
示例12: render_board
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import broadcast_to [as 别名]
def render_board(board, goals=0, orientation=0, edit_loc=None, edit_color=0):
"""
Just render the board itself. Doesn't require game state.
"""
if edit_loc and (edit_loc[0] >= board.shape[0] or edit_loc[1] >= board.shape[1]):
edit_loc = None
goals = np.broadcast_to(goals, board.shape)
screen = np.empty((board.shape[0]+2, board.shape[1]+3,), dtype=object)
screen[:] = ''
screen[0] = screen[-1] = ' -'
screen[:,0] = screen[:,-2] = ' |'
screen[:,-1] = '\n'
screen[0,0] = screen[0,-2] = screen[-1,0] = screen[-1,-2] = ' +'
screen[1:-1,1:-2] = render_cell(board, goals, orientation)
if edit_loc:
x1, y1 = edit_loc
val = render_cell(board[y1, x1], goals[y1, x1], orientation, edit_color)
screen[y1+1, x1+1] = str(val)
return ''.join(screen.ravel())
示例13: __getitem__
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import broadcast_to [as 别名]
def __getitem__(self, items):
# To make life easier, we only wrap when `items` is a tuple of slices.
# It'd be nifty if they could be integers or work on arbitrary arrays,
# but that's more work and it won't be used.
if not (isinstance(items, tuple) and len(items) == 2 and
isinstance(items[0], slice) and isinstance(items[1], slice)):
return super().__getitem__(items)
rows, cols = items
rows = np.arange(
rows.start or 0,
rows.stop if rows.stop is not None else self.shape[0],
rows.step or 1
) % self.shape[0]
cols = np.arange(
cols.start or 0,
cols.stop if cols.stop is not None else self.shape[0],
cols.step or 1
) % self.shape[1]
nrows = len(rows)
ncols = len(cols)
rows = np.broadcast_to(rows[:,None], (nrows, ncols))
cols = np.broadcast_to(cols[None,:], (nrows, ncols))
return super().__getitem__((rows, cols))
示例14: _dominant_set_sparse
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import broadcast_to [as 别名]
def _dominant_set_sparse(s, k, is_thresh=False, norm=False):
"""Compute dominant set for a sparse matrix."""
if is_thresh:
mask = s > k
idx, data = np.where(mask), s[mask]
s = ssp.coo_matrix((data, idx), shape=s.shape)
else: # keep top k
nr, nc = s.shape
idx = np.argpartition(s, nc - k, axis=1)
col = idx[:, -k:].ravel() # idx largest
row = np.broadcast_to(np.arange(nr)[:, None], (nr, k)).ravel()
data = s[row, col].ravel()
s = ssp.coo_matrix((data, (row, col)), shape=s.shape)
if norm:
s.data /= s.sum(axis=1).A1[s.row]
return s.tocsr(copy=False)
示例15: random_warp
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import broadcast_to [as 别名]
def random_warp( image ):
assert image.shape == (256,256,3)
range_ = numpy.linspace( 128-80, 128+80, 5 )
mapx = numpy.broadcast_to( range_, (5,5) )
mapy = mapx.T
mapx = mapx + numpy.random.normal( size=(5,5), scale=5 )
mapy = mapy + numpy.random.normal( size=(5,5), scale=5 )
interp_mapx = cv2.resize( mapx, (80,80) )[8:72,8:72].astype('float32')
interp_mapy = cv2.resize( mapy, (80,80) )[8:72,8:72].astype('float32')
warped_image = cv2.remap( image, interp_mapx, interp_mapy, cv2.INTER_LINEAR )
src_points = numpy.stack( [ mapx.ravel(), mapy.ravel() ], axis=-1 )
dst_points = numpy.mgrid[0:65:16,0:65:16].T.reshape(-1,2)
mat = umeyama( src_points, dst_points, True )[0:2]
target_image = cv2.warpAffine( image, mat, (64,64) )
return warped_image, target_image