本文整理汇总了Python中numpy.repeat方法的典型用法代码示例。如果您正苦于以下问题:Python numpy.repeat方法的具体用法?Python numpy.repeat怎么用?Python numpy.repeat使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类numpy
的用法示例。
在下文中一共展示了numpy.repeat方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: offset_to_pts
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import repeat [as 别名]
def offset_to_pts(self, center_list, pred_list):
"""Change from point offset to point coordinate."""
pts_list = []
for i_lvl in range(len(self.point_strides)):
pts_lvl = []
for i_img in range(len(center_list)):
pts_center = center_list[i_img][i_lvl][:, :2].repeat(
1, self.num_points)
pts_shift = pred_list[i_lvl][i_img]
yx_pts_shift = pts_shift.permute(1, 2, 0).view(
-1, 2 * self.num_points)
y_pts_shift = yx_pts_shift[..., 0::2]
x_pts_shift = yx_pts_shift[..., 1::2]
xy_pts_shift = torch.stack([x_pts_shift, y_pts_shift], -1)
xy_pts_shift = xy_pts_shift.view(*yx_pts_shift.shape[:-1], -1)
pts = xy_pts_shift * self.point_strides[i_lvl] + pts_center
pts_lvl.append(pts)
pts_lvl = torch.stack(pts_lvl, 0)
pts_list.append(pts_lvl)
return pts_list
示例2: evaluate_sliding_window
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import repeat [as 别名]
def evaluate_sliding_window(img_filename, crops):
img = io.imread(img_filename).astype(np.float32)/255
if img.ndim == 2: # Handle B/W images
img = np.expand_dims(img, axis=-1)
img = np.repeat(img, 3, 2)
img_crops = np.zeros((batch_size, 227, 227, 3))
for i in xrange(len(crops)):
crop = crops[i]
img_crop = transform.resize(img[crop[1]:crop[1]+crop[3],crop[0]:crop[0]+crop[2]], (227, 227))-0.5
img_crop = np.expand_dims(img_crop, axis=0)
img_crops[i,:,:,:] = img_crop
# compute ranking scores
scores = sess.run([score_func], feed_dict={image_placeholder: img_crops})
# find the optimal crop
idx = np.argmax(scores[:len(crops)])
best_window = crops[idx]
# return the best crop
return (best_window[0], best_window[1], best_window[2], best_window[3])
示例3: testMultilabelMatch3
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import repeat [as 别名]
def testMultilabelMatch3(self):
predictions = np.random.randint(1, 5, size=(100, 1, 1, 1))
targets = np.random.randint(1, 5, size=(100, 10, 1, 1))
weights = np.random.randint(0, 2, size=(100, 1, 1, 1))
targets *= weights
predictions_repeat = np.repeat(predictions, 10, axis=1)
expected = (predictions_repeat == targets).astype(float)
expected = np.sum(expected, axis=(1, 2, 3))
expected = np.minimum(expected / 3.0, 1.)
expected = np.sum(expected * weights[:, 0, 0, 0]) / weights.shape[0]
with self.test_session() as session:
scores, weights_ = metrics.multilabel_accuracy_match3(
tf.one_hot(predictions, depth=5, dtype=tf.float32),
tf.constant(targets, dtype=tf.int32))
a, a_op = tf.metrics.mean(scores, weights_)
session.run(tf.local_variables_initializer())
session.run(tf.global_variables_initializer())
_ = session.run(a_op)
actual = session.run(a)
self.assertAlmostEqual(actual, expected, places=6)
示例4: zxy_grid
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import repeat [as 别名]
def zxy_grid(co_y, tymin, tymax, subs, c, t, c_peat, t_peat):
# create linespace grid between bottom and top of tri z
#subs = 7
t_min = np.min(tymin)
t_max = np.max(tymax)
divs = np.linspace(t_min, t_max, num=subs, dtype=np.float32)
# figure out which triangles and which co are in each section
co_bools = (co_y > divs[:-1][:, nax]) & (co_y < divs[1:][:, nax])
tri_bools = (tymin < divs[1:][:, nax]) & (tymax > divs[:-1][:, nax])
for i, j in zip(co_bools, tri_bools):
if (np.sum(i) > 0) & (np.sum(j) > 0):
c3 = c[i]
t3 = t[j]
c_peat.append(np.repeat(c3, t3.shape[0]))
t_peat.append(np.tile(t3, c3.shape[0]))
示例5: repair_out_of_bounds_manually
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import repeat [as 别名]
def repair_out_of_bounds_manually(X, xl, xu):
only_1d = (X.ndim == 1)
X = at_least_2d_array(X)
if xl is not None:
xl = np.repeat(xl[None, :], X.shape[0], axis=0)
X[X < xl] = xl[X < xl]
if xu is not None:
xu = np.repeat(xu[None, :], X.shape[0], axis=0)
X[X > xu] = xu[X > xu]
if only_1d:
return X[0, :]
else:
return X
示例6: bounds_back
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import repeat [as 别名]
def bounds_back(problem, X):
only_1d = (X.ndim == 1)
X = at_least_2d_array(X)
if problem.xl is not None and problem.xu is not None:
xl = np.repeat(problem.xl[None, :], X.shape[0], axis=0)
xu = np.repeat(problem.xu[None, :], X.shape[0], axis=0)
# otherwise bounds back into the feasible space
_range = xu - xl
X[X < xl] = (xl + np.mod((xl - X), _range))[X < xl]
X[X > xu] = (xu - np.mod((X - xu), _range))[X > xu]
if only_1d:
return X[0, :]
else:
return X
示例7: computeUVN_vec
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import repeat [as 别名]
def computeUVN_vec(n, in_, planeID):
'''
vectorization version of computeUVN
@n N x 3
@in_ MN x 1
@planeID N
'''
n = n.copy()
if (planeID == 2).sum():
n[planeID == 2] = np.roll(n[planeID == 2], 2, axis=1)
if (planeID == 3).sum():
n[planeID == 3] = np.roll(n[planeID == 3], 1, axis=1)
n = np.repeat(n, in_.shape[0] // n.shape[0], axis=0)
assert n.shape[0] == in_.shape[0]
bc = n[:, [0]] * np.sin(in_) + n[:, [1]] * np.cos(in_)
bs = n[:, [2]]
out = np.arctan(-bc / (bs + 1e-9))
return out
示例8: np_sample
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import repeat [as 别名]
def np_sample(img, coords):
# a numpy implementation of ImageSample layer
coords = np.maximum(coords, 0)
coords = np.minimum(coords, np.array([img.shape[0] - 1, img.shape[1] - 1]))
lcoor = np.floor(coords).astype('int32')
ucoor = lcoor + 1
ucoor = np.minimum(ucoor, np.array([img.shape[0] - 1, img.shape[1] - 1]))
diff = coords - lcoor
neg_diff = 1.0 - diff
lcoory, lcoorx = np.split(lcoor, 2, axis=2)
ucoory, ucoorx = np.split(ucoor, 2, axis=2)
diff = np.repeat(diff, 3, 2).reshape((diff.shape[0], diff.shape[1], 2, 3))
neg_diff = np.repeat(neg_diff, 3, 2).reshape((diff.shape[0], diff.shape[1], 2, 3))
diffy, diffx = np.split(diff, 2, axis=2)
ndiffy, ndiffx = np.split(neg_diff, 2, axis=2)
ret = img[lcoory, lcoorx, :] * ndiffx * ndiffy + \
img[ucoory, ucoorx, :] * diffx * diffy + \
img[lcoory, ucoorx, :] * ndiffy * diffx + \
img[ucoory, lcoorx, :] * diffy * ndiffx
return ret[:, :, 0, :]
示例9: setup_mnist
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import repeat [as 别名]
def setup_mnist(self, img_res):
print ("Setting up MNIST...")
if not os.path.exists('datasets/mnist_x.npy'):
# Load the dataset
(mnist_X, mnist_y), (_, _) = mnist.load_data()
# Normalize and rescale images
mnist_X = self.normalize(mnist_X)
mnist_X = np.array([imresize(x, img_res) for x in mnist_X])
mnist_X = np.expand_dims(mnist_X, axis=-1)
mnist_X = np.repeat(mnist_X, 3, axis=-1)
self.mnist_X, self.mnist_y = mnist_X, mnist_y
# Save formatted images
np.save('datasets/mnist_x.npy', self.mnist_X)
np.save('datasets/mnist_y.npy', self.mnist_y)
else:
self.mnist_X = np.load('datasets/mnist_x.npy')
self.mnist_y = np.load('datasets/mnist_y.npy')
print ("+ Done.")
示例10: _project
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import repeat [as 别名]
def _project(self, matrix):
if self.is_scalar():
return 1
else:
# Note that we use Munkres algorithm, but expand columns from n to m
# by replicating each column by group size.
mm = np.repeat(matrix, self.col_sum, axis=1)
indexes = lap.lapjv(np.asarray(-mm))
result = np.zeros(self.shape)
reduce = np.repeat(range(len(self.col_sum)), self.col_sum)
for row, column in enumerate(indexes[1]):
# map expanded column index to reduced group index.
result[row, reduce[column]] = 1
return result
# Constrain all entries to be zero that correspond to
# zeros in the matrix.
示例11: __init__
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import repeat [as 别名]
def __init__(self, env, k, channel_order='hwc'):
"""Stack k last frames.
Returns lazy array, which is much more memory efficient.
See Also
--------
baselines.common.atari_wrappers.LazyFrames
"""
gym.Wrapper.__init__(self, env)
self.k = k
self.frames = deque([], maxlen=k)
self.stack_axis = {'hwc': 2, 'chw': 0}[channel_order]
orig_obs_space = env.observation_space
low = np.repeat(orig_obs_space.low, k, axis=self.stack_axis)
high = np.repeat(orig_obs_space.high, k, axis=self.stack_axis)
self.observation_space = spaces.Box(
low=low, high=high, dtype=orig_obs_space.dtype)
示例12: render_cubemap
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import repeat [as 别名]
def render_cubemap(self, out_size, mode='blend'):
# Create coordinate arrays.
cvec = np.arange(out_size, dtype='float32') - out_size/2 # Coordinate range [-S/2, S/2)
vec0 = np.ones(out_size*out_size, dtype='float32') * out_size/2 # Constant vector +S/2
vec1 = np.repeat(cvec, out_size) # Increment every N steps
vec2 = np.tile(cvec, out_size) # Sweep N times
# Create XYZ coordinate vectors and render each cubemap face.
render = lambda(xyz): self._render(xyz, out_size, out_size, mode)
xm = render(np.matrix([-vec0, vec1, vec2])) # -X face
xp = render(np.matrix([vec0, vec1, -vec2])) # +X face
ym = render(np.matrix([-vec1, -vec0, vec2])) # -Y face
yp = render(np.matrix([vec1, vec0, vec2])) # +Y face
zm = render(np.matrix([-vec2, vec1, -vec0])) # -Z face
zp = render(np.matrix([vec2, vec1, vec0])) # +Z face
# Concatenate the individual faces in canonical order:
# https://en.wikipedia.org/wiki/Cube_mapping#Memory_Addressing
img_mat = np.concatenate([zp, zm, ym, yp, xm, xp], axis=0)
return Image.fromarray(img_mat)
# Get XYZ vectors for an equirectangular render, in raster order.
# (Each row left to right, with rows concatenates from top to bottom.)
示例13: _optimize_2D
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import repeat [as 别名]
def _optimize_2D(nodes, triangles, stay=[]):
''' Optimize the locations of the points by moving them towards the center
of their patch. This is done iterativally for all points for a number of
iterations and using a .05 step length'''
edges, tr_edges, adjacency_list = _edge_list(triangles)
boundary = edges[adjacency_list[:, 1] == -1].reshape(-1)
stay = np.union1d(boundary, stay)
stay = stay.astype(int)
n_iter = 5
step_length = .05
mean_bar = np.zeros_like(nodes)
new_nodes = np.copy(nodes)
k = np.bincount(triangles.reshape(-1), minlength=len(nodes))
for n in range(n_iter):
bar = np.mean(new_nodes[triangles], axis=1)
for i in range(2):
mean_bar[:, i] = np.bincount(triangles.reshape(-1),
weights=np.repeat(bar[:, i], 3),
minlength=len(nodes))
mean_bar /= k[:, None]
new_nodes += step_length * (mean_bar - new_nodes)
new_nodes[stay] = nodes[stay]
return new_nodes
示例14: nodes_areas
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import repeat [as 别名]
def nodes_areas(self):
''' Areas for all nodes in a surface
Returns
---------
nd: NodeData
NodeData structure with normals for each node
'''
areas = self.elements_volumes_and_areas()[self.elm.triangles]
triangle_nodes = self.elm[self.elm.triangles, :3] - 1
nd = np.bincount(
triangle_nodes.reshape(-1),
np.repeat(areas/3., 3), self.nodes.nr
)
return NodeData(nd, 'areas')
示例15: combvec
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import repeat [as 别名]
def combvec(arrays, out=None):
arrays = [np.asarray(x) for x in arrays]
dtype = arrays[0].dtype
n = np.prod([x.size for x in arrays])
if out is None:
out = np.zeros([n, len(arrays)], dtype=dtype)
m = n // arrays[0].size
out[:,0] = np.repeat(arrays[0], m)
if arrays[1:]:
combvec(arrays[1:], out=out[0:m,1:])
for j in range(1, arrays[0].size):
out[j*m:(j+1)*m,1:] = out[0:m,1:]
return out