本文整理匯總了Python中mxnet.nd.array方法的典型用法代碼示例。如果您正苦於以下問題:Python nd.array方法的具體用法?Python nd.array怎麽用?Python nd.array使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類mxnet.nd
的用法示例。
在下文中一共展示了nd.array方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: hybrid_forward
# 需要導入模塊: from mxnet import nd [as 別名]
# 或者: from mxnet.nd import array [as 別名]
def hybrid_forward(self, F, seq):
region_radius = region_size/2
aligned_seq = map(lambda i: F.slice(seq, begin=[None, i-region_radius], end=[None, i-region_radius+region_size]).asnumpy(), \
range(region_radius, seq.shape[1] - region_radius))
aligned_seq = nd.array(aligned_seq)
region_aligned_seq = aligned_seq.transpose((1, 0, 2))
region_aligned_emb = self.embedding_region(region_aligned_seq).reshape((batch_size,-1,region_size,emb_size))
trimed_seq = seq[:, region_radius: seq.shape[1] - region_radius]
context_unit = self.embedding(trimed_seq).reshape((batch_size,-1,region_size,emb_size))
projected_emb = region_aligned_emb * context_unit
feature = self.max_pool(projected_emb.transpose((0,1,3,2)).reshape((batch_size,-1,region_size))).reshape((batch_size,-1,emb_size))
trimed_seq = seq[:,region_radius:seq.shape[1]-region_radius]
mask = F.greater(trimed_seq,0).reshape((batch_size,-1,1))
feature = mask*feature
feature = feature.reshape((-1,emb_size))
feature = self.dense(feature).reshape((batch_size,-1,n_classes)).transpose((0,2,1)).reshape((batch_size*n_classes,-1))
#accumulation
feature = F.expand_dims(feature,axis = 1)
residual = F.sum(feature,axis=2).reshape((batch_size,n_classes))
res = self.dense2(self.dense1(feature)).reshape(batch_size*n_classes,1,-1).reshape((batch_size,n_classes))
return res+residual
示例2: __getitem__
# 需要導入模塊: from mxnet import nd [as 別名]
# 或者: from mxnet.nd import array [as 別名]
def __getitem__(self, idx):
img_path = self.data_frame.iloc[idx, 0]
img = cv2.imread(img_path, 1)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
x, y, w, h = self.data_frame.iloc[idx, 1:5]
l, t, ww, hh = enlarge_bbox(x, y, w, h, self.enlarge_factor)
r, b = l + ww, t + hh
img = img[t: b, l:r, :]
img = cv2.resize(img, (self.img_size, self.img_size))
img = img.astype(np.float32) - 127.5
img = nd.transpose(nd.array(img), (2, 0, 1))
label_path = img_path.replace('.jpg', '.mat')
label = sio.loadmat(label_path)
params_shape = label['Shape_Para'].astype(np.float32).ravel()
params_exp = label['Exp_Para'].astype(np.float32).ravel()
return img, params_shape, params_exp
示例3: crop_resize_normalize
# 需要導入模塊: from mxnet import nd [as 別名]
# 或者: from mxnet.nd import array [as 別名]
def crop_resize_normalize(img, bbox_list, output_size,
mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)):
output_list = []
transform_test = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize(mean, std)
])
for bbox in bbox_list:
x0 = max(int(bbox[0]), 0)
y0 = max(int(bbox[1]), 0)
x1 = min(int(bbox[2]), int(img.shape[1]))
y1 = min(int(bbox[3]), int(img.shape[0]))
w = x1 - x0
h = y1 - y0
res_img = image.fixed_crop(nd.array(img), x0, y0, w, h, (output_size[1], output_size[0]))
res_img = transform_test(res_img)
output_list.append(res_img)
output_array = nd.stack(*output_list)
return output_array
示例4: heatmap_to_coord
# 需要導入模塊: from mxnet import nd [as 別名]
# 或者: from mxnet.nd import array [as 別名]
def heatmap_to_coord(heatmaps, bbox_list):
heatmap_height = heatmaps.shape[2]
heatmap_width = heatmaps.shape[3]
coords, maxvals = get_max_pred(heatmaps)
preds = nd.zeros_like(coords)
for i, bbox in enumerate(bbox_list):
x0 = bbox[0]
y0 = bbox[1]
x1 = bbox[2]
y1 = bbox[3]
w = (x1 - x0) / 2
h = (y1 - y0) / 2
center = np.array([x0 + w, y0 + h])
scale = np.array([w, h])
w_ratio = coords[i][:, 0] / heatmap_width
h_ratio = coords[i][:, 1] / heatmap_height
preds[i][:, 0] = scale[0] * 2 * w_ratio + center[0] - scale[0]
preds[i][:, 1] = scale[1] * 2 * h_ratio + center[1] - scale[1]
return preds, maxvals
示例5: cv_rotate
# 需要導入模塊: from mxnet import nd [as 別名]
# 或者: from mxnet.nd import array [as 別名]
def cv_rotate(img, rot, resW, resH):
cv2 = try_import_cv2()
center = np.array((resW - 1, resH - 1)) / 2
rot_rad = np.pi * rot / 180
src_dir = get_dir([0, (resH - 1) * -0.5], rot_rad)
dst_dir = np.array([0, (resH - 1) * -0.5], np.float32)
src = np.zeros((3, 2), dtype=np.float32)
dst = np.zeros((3, 2), dtype=np.float32)
src[0, :] = center
src[1, :] = center + src_dir
dst[0, :] = [(resW - 1) * 0.5, (resH - 1) * 0.5]
dst[1, :] = np.array([(resW - 1) * 0.5, (resH - 1) * 0.5]) + dst_dir
src[2:, :] = get_3rd_point(src[0, :], src[1, :])
dst[2:, :] = get_3rd_point(dst[0, :], dst[1, :])
trans = cv2.getAffineTransform(np.float32(src), np.float32(dst))
dst_img = cv2.warpAffine(img, trans,
(resW, resH), flags=cv2.INTER_LINEAR)
return dst_img
示例6: default_mp_pad_batchify_fn
# 需要導入模塊: from mxnet import nd [as 別名]
# 或者: from mxnet.nd import array [as 別名]
def default_mp_pad_batchify_fn(data):
"""Use shared memory for collating data into batch, labels are padded to same shape"""
if isinstance(data[0], nd.NDArray):
out = nd.empty((len(data),) + data[0].shape, dtype=data[0].dtype,
ctx=context.Context('cpu_shared', 0))
return nd.stack(*data, out=out)
elif isinstance(data[0], tuple):
data = zip(*data)
return [default_mp_pad_batchify_fn(i) for i in data]
else:
data = np.asarray(data)
batch_size = len(data)
pad = max([l.shape[0] for l in data] + [1,])
buf = np.full((batch_size, pad, data[0].shape[-1]), -1, dtype=data[0].dtype)
for i, l in enumerate(data):
buf[i][:l.shape[0], :] = l
return nd.array(buf, dtype=data[0].dtype, ctx=context.Context('cpu_shared', 0))
示例7: _sample_val_indices
# 需要導入模塊: from mxnet import nd [as 別名]
# 或者: from mxnet.nd import array [as 別名]
def _sample_val_indices(self, num_frames):
if num_frames > self.num_segments + self.skip_length - 1:
tick = (num_frames - self.skip_length + 1) / \
float(self.num_segments)
offsets = np.array([int(tick / 2.0 + tick * x)
for x in range(self.num_segments)])
else:
offsets = np.zeros((self.num_segments,))
if self.temporal_jitter:
skip_offsets = np.random.randint(
self.new_step, size=self.skip_length // self.new_step)
else:
skip_offsets = np.zeros(
self.skip_length // self.new_step, dtype=int)
return offsets + 1, skip_offsets
示例8: _sample_test_indices
# 需要導入模塊: from mxnet import nd [as 別名]
# 或者: from mxnet.nd import array [as 別名]
def _sample_test_indices(self, num_frames):
if num_frames > self.skip_length - 1:
tick = (num_frames - self.skip_length + 1) / \
float(self.num_segments)
offsets = np.array([int(tick / 2.0 + tick * x)
for x in range(self.num_segments)])
else:
offsets = np.zeros((self.num_segments,))
if self.temporal_jitter:
skip_offsets = np.random.randint(
self.new_step, size=self.skip_length // self.new_step)
else:
skip_offsets = np.zeros(
self.skip_length // self.new_step, dtype=int)
return offsets + 1, skip_offsets
示例9: __iter__
# 需要導入模塊: from mxnet import nd [as 別名]
# 或者: from mxnet.nd import array [as 別名]
def __iter__(self):
data = self.dataset[:]
X = data[0]
y = nd.array(data[1])
n = X.shape[0]
if self.shuffle:
idx = np.arange(n)
np.random.shuffle(idx)
X = nd.array(X.asnumpy()[idx])
y = nd.array(y.asnumpy()[idx])
for i in range(n // self.batch_size):
if self.transform is not None:
yield self.transform(X[i * self.batch_size:(i + 1) * self.batch_size],
y[i * self.batch_size:(i + 1) * self.batch_size])
else:
yield (X[i * self.batch_size:(i + 1) * self.batch_size],
y[i * self.batch_size:(i + 1) * self.batch_size])
示例10: data_iter_random
# 需要導入模塊: from mxnet import nd [as 別名]
# 或者: from mxnet.nd import array [as 別名]
def data_iter_random(corpus_indices, batch_size, num_steps, ctx=None):
"""Sample mini-batches in a random order from sequential data."""
# Subtract 1 because label indices are corresponding input indices + 1.
num_examples = (len(corpus_indices) - 1) // num_steps
epoch_size = num_examples // batch_size
# Randomize samples.
example_indices = list(range(num_examples))
random.shuffle(example_indices)
def _data(pos):
return corpus_indices[pos: pos + num_steps]
for i in range(epoch_size):
# Read batch_size random samples each time.
i = i * batch_size
batch_indices = example_indices[i: i + batch_size]
data = nd.array(
[_data(j * num_steps) for j in batch_indices], ctx=ctx)
label = nd.array(
[_data(j * num_steps + 1) for j in batch_indices], ctx=ctx)
yield data, label
示例11: predict_rnn
# 需要導入模塊: from mxnet import nd [as 別名]
# 或者: from mxnet.nd import array [as 別名]
def predict_rnn(rnn, prefix, num_chars, params, hidden_dim, ctx, idx_to_char,
char_to_idx, get_inputs, is_lstm=False):
"""Predict the next chars given the prefix."""
prefix = prefix.lower()
state_h = nd.zeros(shape=(1, hidden_dim), ctx=ctx)
if is_lstm:
state_c = nd.zeros(shape=(1, hidden_dim), ctx=ctx)
output = [char_to_idx[prefix[0]]]
for i in range(num_chars + len(prefix)):
X = nd.array([output[-1]], ctx=ctx)
if is_lstm:
Y, state_h, state_c = rnn(get_inputs(X), state_h, state_c, *params)
else:
Y, state_h = rnn(get_inputs(X), state_h, *params)
if i < len(prefix) - 1:
next_input = char_to_idx[prefix[i + 1]]
else:
next_input = int(Y[0].argmax(axis=1).asscalar())
output.append(next_input)
return ''.join([idx_to_char[i] for i in output])
示例12: _create_pairs
# 需要導入模塊: from mxnet import nd [as 別名]
# 或者: from mxnet.nd import array [as 別名]
def _create_pairs(self):
"""
Create pairs for array
:return:
"""
pos_pairs, neg_pairs = [], []
for ids, ys in enumerate(self.arrs[1]):
for idt, yt in enumerate(self.arrt[1]):
if ys == yt:
pos_pairs.append([ids, ys, idt, yt, 1])
else:
neg_pairs.append([ids, ys, idt, yt, 0])
if self.ratio > 0:
random.shuffle(neg_pairs)
pairs = pos_pairs + neg_pairs[: self.ratio * len(pos_pairs)]
else:
pairs = pos_pairs + neg_pairs
random.shuffle(pairs)
return pairs
示例13: __init__
# 需要導入模塊: from mxnet import nd [as 別名]
# 或者: from mxnet.nd import array [as 別名]
def __init__(self, arr1=None, arr2=None, tform1=None, tform2=None):
"""
Initialization of dataset
:param arr1: source array
:param arr2: target array
:param tform1: transformers for source array
:param tform2: transformers for target array
"""
assert arr1 is not None or arr2 is not None, "One of src array or tgt array should not be None"
self.arr1 = arr1
self.use1 = False if arr1 is None else True
self.arr2 = arr2
self.use2 = False if arr2 is None else True
self.tform1 = tform1
self.tform2 = tform2
self._gen_cls_idx_dicts()
示例14: forward
# 需要導入模塊: from mxnet import nd [as 別名]
# 或者: from mxnet.nd import array [as 別名]
def forward(self, x):
'''
Parameters
----------
x: nd.array, shape is (batch_size, c_in, time_step, num_of_vertices)
Returns
----------
shape is (batch_size, c_out, time_step - Kt + 1, num_of_vertices)
'''
x_input = self.align(x)[:, :, self.Kt - 1:, :]
x_conv = self.conv(x)
if self.activation == 'GLU':
x_conv = self.conv(x)
x_conv1, x_conv2 = nd.split(x_conv, axis=1, num_outputs=2)
return (x_conv1 + x_input) * nd.sigmoid(x_conv2)
if self.activation == 'relu':
return nd.relu(x_conv + x_input)
return x_conv
示例15: crop_resize_normalize
# 需要導入模塊: from mxnet import nd [as 別名]
# 或者: from mxnet.nd import array [as 別名]
def crop_resize_normalize(img, bbox_list, output_size):
output_list = []
transform_test = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
])
for bbox in bbox_list:
x0 = max(int(bbox[0]), 0)
y0 = max(int(bbox[1]), 0)
x1 = min(int(bbox[2]), int(img.shape[1]))
y1 = min(int(bbox[3]), int(img.shape[0]))
w = x1 - x0
h = y1 - y0
res_img = image.fixed_crop(nd.array(img), x0, y0, w, h, (output_size[1], output_size[0]))
res_img = transform_test(res_img)
output_list.append(res_img)
output_array = nd.stack(*output_list)
return output_array