当前位置: 首页>>代码示例>>Python>>正文


Python nd.array方法代码示例

本文整理汇总了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 
开发者ID:NonvolatileMemory,项目名称:AAAI_2019_EXAM,代码行数:23,代码来源:TextEXAM_multi-class.py

示例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 
开发者ID:ShownX,项目名称:mxnet-E2FAR,代码行数:25,代码来源:E2FAR.py

示例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 
开发者ID:dmlc,项目名称:gluon-cv,代码行数:21,代码来源:pose.py

示例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 
开发者ID:dmlc,项目名称:gluon-cv,代码行数:23,代码来源:pose.py

示例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 
开发者ID:dmlc,项目名称:gluon-cv,代码行数:26,代码来源:pose.py

示例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)) 
开发者ID:dmlc,项目名称:gluon-cv,代码行数:19,代码来源:dataloader.py

示例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 
开发者ID:dmlc,项目名称:gluon-cv,代码行数:18,代码来源:classification.py

示例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 
开发者ID:dmlc,项目名称:gluon-cv,代码行数:18,代码来源:classification.py

示例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]) 
开发者ID:auroua,项目名称:InsightFace_TF,代码行数:20,代码来源:utils_final.py

示例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 
开发者ID:auroua,项目名称:InsightFace_TF,代码行数:23,代码来源:utils_final.py

示例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]) 
开发者ID:auroua,项目名称:InsightFace_TF,代码行数:22,代码来源:utils_final.py

示例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 
开发者ID:aws-samples,项目名称:d-SNE,代码行数:24,代码来源:datasets_su.py

示例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() 
开发者ID:aws-samples,项目名称:d-SNE,代码行数:22,代码来源:datasets_su.py

示例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 
开发者ID:Davidham3,项目名称:STGCN,代码行数:24,代码来源:base_layers.py

示例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 
开发者ID:Angzz,项目名称:panoptic-fpn-gluon,代码行数:20,代码来源:pose.py


注:本文中的mxnet.nd.array方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。