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


Python cuda.get_array_module方法代码示例

本文整理汇总了Python中chainer.backends.cuda.get_array_module方法的典型用法代码示例。如果您正苦于以下问题:Python cuda.get_array_module方法的具体用法?Python cuda.get_array_module怎么用?Python cuda.get_array_module使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在chainer.backends.cuda的用法示例。


在下文中一共展示了cuda.get_array_module方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: generate_image

# 需要导入模块: from chainer.backends import cuda [as 别名]
# 或者: from chainer.backends.cuda import get_array_module [as 别名]
def generate_image(self, v, r):
        xp = cuda.get_array_module(v)

        batch_size = v.shape[0]
        h_t_gen, c_t_gen, u_t, _, _ = self.generate_initial_state(
            batch_size, xp)
        v = cf.reshape(v, v.shape[:2] + (1, 1))

        for t in range(self.num_layers):
            generation_core = self.get_generation_core(t)

            mean_z_p, ln_var_z_p = self.z_prior_distribution.compute_parameter(
                h_t_gen)
            z_t = cf.gaussian(mean_z_p, ln_var_z_p)

            h_next_gen, c_next_gen, u_next = generation_core(
                h_t_gen, c_t_gen, z_t, v, r, u_t)

            u_t = u_next
            h_t_gen = h_next_gen
            c_t_gen = c_next_gen

        mean_x = self.map_u_x(u_t)
        return mean_x.data 
开发者ID:musyoku,项目名称:chainer-gqn,代码行数:26,代码来源:model.py

示例2: generate_image_from_zero_z

# 需要导入模块: from chainer.backends import cuda [as 别名]
# 或者: from chainer.backends.cuda import get_array_module [as 别名]
def generate_image_from_zero_z(self, v, r):
        xp = cuda.get_array_module(v)

        batch_size = v.shape[0]
        h_t_gen, c_t_gen, u_t, _, _ = self.generate_initial_state(
            batch_size, xp)

        v = cf.reshape(v, v.shape[:2] + (1, 1))

        for t in range(self.num_layers):
            generation_core = self.get_generation_core(t)

            mean_z_p, _ = self.z_prior_distribution.compute_parameter(h_t_gen)
            z_t = xp.zeros_like(mean_z_p.data)

            h_next_gen, c_next_gen, u_next = generation_core(
                h_t_gen, c_t_gen, z_t, v, r, u_t)

            u_t = u_next
            h_t_gen = h_next_gen
            c_t_gen = c_next_gen

        mean_x = self.map_u_x(u_t)
        return mean_x.data 
开发者ID:musyoku,项目名称:chainer-gqn,代码行数:26,代码来源:model.py

示例3: backward_log_softmax

# 需要导入模块: from chainer.backends import cuda [as 别名]
# 或者: from chainer.backends.cuda import get_array_module [as 别名]
def backward_log_softmax(self, x, y, gy):
        if cuda.cudnn_enabled:
            cudnn = cuda.cudnn
            libcudnn = cuda.cuda.cudnn
            _algorithm = libcudnn.CUDNN_SOFTMAX_LOG
            _mode = libcudnn.CUDNN_SOFTMAX_MODE_CHANNEL

        xp = cuda.get_array_module(x)
        if xp is not numpy and chainer.should_use_cudnn('>=auto', 3000):
            oz_dtype = 'd' if x.dtype == 'd' else 'f'
            one = numpy.array(1, dtype=oz_dtype).ctypes
            zero = numpy.array(0, dtype=oz_dtype).ctypes
            handle = cudnn.get_handle()
            gx = xp.empty(x.shape, dtype=x.dtype)
            gx_cube = gx.reshape(gx.shape[:2] + (-1, 1))
            desc = cudnn.create_tensor_descriptor(gx_cube)
            libcudnn.softmaxBackward(
                handle, _algorithm, _mode, one.data, desc.value,
                y.data.ptr, desc.value, gy.data.ptr, zero.data,
                desc.value, gx.data.ptr)
        else:
            gx = gy - xp.exp(y) * gy.sum(axis=1, keepdims=True)

        return gx 
开发者ID:chainer,项目名称:models,代码行数:26,代码来源:adaptive_softmax.py

示例4: _enumerate_shifted_anchor

# 需要导入模块: from chainer.backends import cuda [as 别名]
# 或者: from chainer.backends.cuda import get_array_module [as 别名]
def _enumerate_shifted_anchor(anchor_base, feat_stride, height, width):
    # Enumerate all shifted anchors:
    #
    # add A anchors (1, A, 4) to
    # cell K shifts (K, 1, 4) to get
    # shift anchors (K, A, 4)
    # reshape to (K*A, 4) shifted anchors
    xp = cuda.get_array_module(anchor_base)
    shift_y = xp.arange(0, height * feat_stride, feat_stride)
    shift_x = xp.arange(0, width * feat_stride, feat_stride)
    shift_x, shift_y = xp.meshgrid(shift_x, shift_y)
    shift = xp.stack((shift_y.ravel(), shift_x.ravel(),
                      shift_y.ravel(), shift_x.ravel()), axis=1)

    A = anchor_base.shape[0]
    K = shift.shape[0]
    anchor = anchor_base.reshape((1, A, 4)) + \
        shift.reshape((1, K, 4)).transpose((1, 0, 2))
    anchor = anchor.reshape((K * A, 4)).astype(np.float32)
    return anchor 
开发者ID:chainer,项目名称:chainercv,代码行数:22,代码来源:region_proposal_network.py

示例5: __call__

# 需要导入模块: from chainer.backends import cuda [as 别名]
# 或者: from chainer.backends.cuda import get_array_module [as 别名]
def __call__(self, **kwargs):
        image = kwargs.pop('image', None)
        words = kwargs.pop('words', None)
        return_predictions = kwargs.pop('return_predictions', False)

        with chainer.using_device(self.device):
            rois, bboxes = self.localizer.predict(image)[:2]
            predicted_words = self.recognizer.predict(rois).array
            self.xp = cuda.get_array_module(bboxes)
            batch_size, num_bboxes, num_channels, height, width = rois.shape
            rois = self.xp.reshape(rois.array, (-1, num_channels, height, width))
            bboxes = self.xp.reshape(bboxes.array, (-1, 2, height, width))

            self.calc_word_accuracy(predicted_words, words)

        if return_predictions:
            return rois, bboxes, predicted_words 
开发者ID:Bartzi,项目名称:kiss,代码行数:19,代码来源:text_recognition_evaluator.py

示例6: r2_score

# 需要导入模块: from chainer.backends import cuda [as 别名]
# 或者: from chainer.backends.cuda import get_array_module [as 别名]
def r2_score(self, pred, true, sample_weight=None,
                 multioutput='uniform_average', ignore_nan=False):

        if self.sample_weight is not None:
            raise NotImplementedError()
        if self.multioutput not in ['uniform_average', 'raw_values']:
            raise ValueError('invalid multioutput argument')

        xp = cuda.get_array_module(pred)
        diff = pred - true
        dev = true - xp.mean(true, axis=0)
        if self.ignore_nan:
            diff[xp.isnan(diff)] = 0.
            dev[xp.isnan(dev)] = 0.
        SS_res = xp.asarray(xp.sum(diff ** 2, axis=0))
        SS_tot = xp.asarray(xp.sum(dev ** 2, axis=0))
        SS_tot_iszero = SS_tot == 0
        SS_tot[SS_tot_iszero] = 1  # Assign dummy value to avoid zero-division
        ret = xp.where(
            SS_tot_iszero, 0.0, 1 - SS_res / SS_tot).astype(pred.dtype)
        if self.multioutput == 'uniform_average':
            return xp.asarray(ret.mean())
        elif self.multioutput == 'raw_values':
            return ret 
开发者ID:chainer,项目名称:chainer-chemistry,代码行数:26,代码来源:r2_score_evaluator.py

示例7: forward

# 需要导入模块: from chainer.backends import cuda [as 别名]
# 或者: from chainer.backends.cuda import get_array_module [as 别名]
def forward(self, inputs):
        xp = cuda.get_array_module(*inputs)
        pred, true = inputs
        diff = pred - true
        dev = true - xp.mean(true, axis=0)
        if self.ignore_nan:
            diff[xp.isnan(diff)] = 0.
            dev[xp.isnan(dev)] = 0.
        SS_res = xp.asarray(
            xp.sum(diff ** 2, axis=0))
        SS_tot = xp.asarray(
            xp.sum(dev ** 2, axis=0))
        SS_tot_iszero = SS_tot == 0
        SS_tot[SS_tot_iszero] = 1  # Assign dummy value to avoid zero-division
        ret = xp.where(
            SS_tot_iszero, 0.0, 1 - SS_res / SS_tot).astype(pred.dtype)
        if self.multioutput == 'uniform_average':
            return xp.asarray(ret.mean()),
        elif self.multioutput == 'raw_values':
            return ret, 
开发者ID:chainer,项目名称:chainer-chemistry,代码行数:22,代码来源:r2_score.py

示例8: update_core

# 需要导入模块: from chainer.backends import cuda [as 别名]
# 或者: from chainer.backends.cuda import get_array_module [as 别名]
def update_core(self):

		image, labels = self.converter(self.get_iterator('main').next())
		assert image.shape[0] == 1, "Batchsize of only 1 is allowed for now"
		image = Variable(image)

		if self.device >= 0:
			image.to_gpu(self.device)
		cl_output = self._optimizers['main'].target.classify(image)
		xp = get_array_module(cl_output.data)

		target = xp.asarray([[0]*(self.no_of_classes)]*cl_output.shape[0])
		for i in range(labels.shape[0]):
			gt_labels = np.unique(labels[i]).astype(np.int32)[2:] - 1 # Not considering -1 & 0
			target[i][gt_labels] = 1
		loss = F.sigmoid_cross_entropy(cl_output, target, normalize=True)
		report({'Loss':loss}, self.get_optimizer('main').target)
		self._optimizers['main'].target.cleargrads()
		loss.backward()
		self._optimizers['main'].update() 
开发者ID:alokwhitewolf,项目名称:Guided-Attention-Inference-Network,代码行数:22,代码来源:updater.py

示例9: max_singular_value

# 需要导入模块: from chainer.backends import cuda [as 别名]
# 或者: from chainer.backends.cuda import get_array_module [as 别名]
def max_singular_value(W, u=None, Ip=1):
    """
    Apply power iteration for the weight parameter
    """
    xp = cuda.get_array_module(W.data)
    if u is None:
        u = xp.random.normal(size=(1, W.shape[0])).astype(xp.float32)
    _u = u
    for _ in range(Ip):
        _v = _l2normalize(xp.dot(_u, W.data), eps=1e-12)
        _u = _l2normalize(xp.dot(_v, W.data.transpose()), eps=1e-12)
    sigma = sum.sum(linear.linear(_u, transpose.transpose(W)) * _v)
    return sigma, _u, _v 
开发者ID:pstuvwx,项目名称:Deep_VoiceChanger,代码行数:15,代码来源:max_sv.py

示例10: sample_z_and_x_params_from_posterior

# 需要导入模块: from chainer.backends import cuda [as 别名]
# 或者: from chainer.backends.cuda import get_array_module [as 别名]
def sample_z_and_x_params_from_posterior(self, x, v, r):
        batch_size = x.shape[0]
        xp = cuda.get_array_module(x)

        h_t_gen, c_t_gen, u_t, h_t_enc, c_t_enc = self.generate_initial_state(
            batch_size, xp)
        v = cf.reshape(v, v.shape + (1, 1))

        z_t_params_array = []

        for t in range(self.num_layers):
            inference_core = self.get_inference_core(t)
            generation_core = self.get_generation_core(t)

            h_next_enc, c_next_enc = inference_core(h_t_gen, h_t_enc, c_t_enc,
                                                    x, v, r, u_t)

            mean_z_q, ln_var_z_q = self.z_posterior_distribution.compute_parameter(
                h_t_enc)
            z_t = cf.gaussian(mean_z_q, ln_var_z_q)

            mean_z_p, ln_var_z_p = self.z_prior_distribution.compute_parameter(
                h_t_gen)

            h_next_gen, c_next_gen, u_next = generation_core(
                h_t_gen, c_t_gen, z_t, v, r, u_t)

            z_t_params_array.append((mean_z_q, ln_var_z_q, mean_z_p,
                                     ln_var_z_p))

            u_t = u_next
            h_t_gen = h_next_gen
            c_t_gen = c_next_gen
            h_t_enc = h_next_enc
            c_t_enc = c_next_enc

        mean_x = self.map_u_x(u_t)
        return z_t_params_array, mean_x 
开发者ID:musyoku,项目名称:chainer-gqn,代码行数:40,代码来源:model.py

示例11: preprocess_images

# 需要导入模块: from chainer.backends import cuda [as 别名]
# 或者: from chainer.backends.cuda import get_array_module [as 别名]
def preprocess_images(images, add_noise=False):
    xp = cuda.get_array_module(images)
    if add_noise:
        images += xp.random.uniform(0, 1, size=images.shape).astype(xp.float32)
    images = images / 256 - 0.5
    return images 
开发者ID:musyoku,项目名称:chainer-gqn,代码行数:8,代码来源:preprocessing.py

示例12: forward

# 需要导入模块: from chainer.backends import cuda [as 别名]
# 或者: from chainer.backends.cuda import get_array_module [as 别名]
def forward(self, inputs):
        self.retain_inputs((0,))
        x, = inputs
        xp = cuda.get_array_module(x)
        y = xp.arctanh(x)
        return utils.force_array(y, dtype=x.dtype), 
开发者ID:chainer,项目名称:chainerrl,代码行数:8,代码来源:arctanh.py

示例13: bbox_iou

# 需要导入模块: from chainer.backends import cuda [as 别名]
# 或者: from chainer.backends.cuda import get_array_module [as 别名]
def bbox_iou(bbox_a, bbox_b):
    """Calculate the Intersection of Unions (IoUs) between bounding boxes.

    IoU is calculated as a ratio of area of the intersection
    and area of the union.

    This function accepts both :obj:`numpy.ndarray` and :obj:`cupy.ndarray` as
    inputs. Please note that both :obj:`bbox_a` and :obj:`bbox_b` need to be
    same type.
    The output is same type as the type of the inputs.

    Args:
        bbox_a (array): An array whose shape is :math:`(N, 4)`.
            :math:`N` is the number of bounding boxes.
            The dtype should be :obj:`numpy.float32`.
        bbox_b (array): An array similar to :obj:`bbox_a`,
            whose shape is :math:`(K, 4)`.
            The dtype should be :obj:`numpy.float32`.

    Returns:
        array:
        An array whose shape is :math:`(N, K)`. \
        An element at index :math:`(n, k)` contains IoUs between \
        :math:`n` th bounding box in :obj:`bbox_a` and :math:`k` th bounding \
        box in :obj:`bbox_b`.

    """
    if bbox_a.shape[1] != 4 or bbox_b.shape[1] != 4:
        raise IndexError
    xp = cuda.get_array_module(bbox_a)

    # top left
    tl = xp.maximum(bbox_a[:, None, :2], bbox_b[:, :2])
    # bottom right
    br = xp.minimum(bbox_a[:, None, 2:], bbox_b[:, 2:])

    area_i = xp.prod(br - tl, axis=2) * (tl < br).all(axis=2)
    area_a = xp.prod(bbox_a[:, 2:] - bbox_a[:, :2], axis=1)
    area_b = xp.prod(bbox_b[:, 2:] - bbox_b[:, :2], axis=1)
    return area_i / (area_a[:, None] + area_b - area_i) 
开发者ID:pfnet-research,项目名称:chainer-compiler,代码行数:42,代码来源:bbox_iou.py

示例14: decode

# 需要导入模块: from chainer.backends import cuda [as 别名]
# 或者: from chainer.backends.cuda import get_array_module [as 别名]
def decode(self, segms, bboxes, labels, sizes):
        """Decodes back to masks.

        Args:
            segms (iterable of arrays): An iterable of arrays of
                shape :math:`(R_n, n\_class, M, M)`.
            bboxes (iterable of arrays): An iterable of arrays of
                shape :math:`(R_n, 4)`.
            labels (iterable of arrays): An iterable of arrays of
                shape :math:`(R_n,)`.
            sizes (list of tuples of two ints): A list of
                :math:`(H_n, W_n)`, where :math:`H_n` and :math:`W_n`
                are height and width of the :math:`n`-th image.

        Returns:
            list of arrays:
            This list contains instance segmentation for each image
            in the batch.
            More precisely, this is a list of boolean arrays of shape
            :math:`(R'_n, H_n, W_n)`, where :math:`R'_n` is the number of
            bounding boxes in the :math:`n`-th image.
        """

        xp = chainer.backends.cuda.get_array_module(*segms)
        if xp != np:
            raise ValueError(
                'MaskHead.decode only supports numpy inputs for now.')
        masks = []
        for bbox, segm, label, size in zip(
                bboxes, segms, labels, sizes):
            if len(segm) > 0:
                masks.append(
                    segm_to_mask(segm[np.arange(len(label)), label + 1],
                                 bbox, size))
            else:
                masks.append(np.zeros((0,) + size, dtype=np.bool))
        return masks 
开发者ID:pfnet-research,项目名称:chainer-compiler,代码行数:39,代码来源:mask_head.py

示例15: mask_head_loss_post

# 需要导入模块: from chainer.backends import cuda [as 别名]
# 或者: from chainer.backends.cuda import get_array_module [as 别名]
def mask_head_loss_post(segms, mask_roi_indices, gt_segms, gt_mask_labels,
                        batchsize):
    """Loss function for Mask Head (post).

     Args:
         segms (array): An array whose shape is :math:`(R, n\_class, M, M)`,
             where :math:`R` is the total number of RoIs in the given batch.
         mask_roi_indices (array): A list of arrays returned by
             :func:`mask_head_loss_pre`.
         gt_segms (list of arrays): A list of arrays returned by
             :func:`mask_head_loss_pre`.
         gt_mask_labels (list of arrays): A list of arrays returned by
             :func:`mask_head_loss_pre`.
         batchsize (int): The size of batch.

     Returns:
        chainer.Variable:
        Mask loss.
    """
    xp = cuda.get_array_module(segms.array)

    mask_roi_indices = xp.hstack(mask_roi_indices).astype(np.int32)
    gt_segms = xp.vstack(gt_segms)
    gt_mask_labels = xp.hstack(gt_mask_labels).astype(np.int32)

    mask_loss = F.sigmoid_cross_entropy(
        segms[np.arange(len(gt_mask_labels)), gt_mask_labels],
        gt_segms.astype(np.int32))
    return mask_loss 
开发者ID:pfnet-research,项目名称:chainer-compiler,代码行数:31,代码来源:mask_head.py


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