示例#1
0
def non_maximum_suppression(bbox, thresh, score=None, limit=None):
    """非极大值抑制"""
    bbox_y1 = bbox[:, 0]
    bbox_x1 = bbox[:, 1]
    bbox_y2 = bbox[:, 2]
    bbox_x2 = bbox[:, 3]

    area = (bbox_x2 - bbox_x1 + 1) * (bbox_y2 - bbox_y1 + 1)
    n_bbox = bbox.shape[0]

    if score is not None:
        order = score.argsort()[::-1].astype(np.int32)
    else:
        order = cp.arange(n_bbox, dtype=np.int32)
    keep = []

    # 预测框之间进行两两比较,去除重叠面积iou大于thresh的框
    while order.size > 0:
        i = order[0]
        keep.append(i)

        xx1 = cp.maximum(bbox_x1[i], bbox_x1[order[1:]])
        yy1 = cp.maximum(bbox_y1[i], bbox_y1[order[1:]])
        xx2 = cp.minimum(bbox_x2[i], bbox_x2[order[1:]])
        yy2 = cp.minimum(bbox_y2[i], bbox_y2[order[1:]])

        width = cp.maximum(0., (xx2 - xx1 + 1))
        height = cp.maximum(0., (yy2 - yy1 + 1))
        inter = width * height
        iou = inter / (area[i] + area[order[1:]] - inter)
        index = cp.where(iou <= thresh)[0]
        order = order[(index + 1).tolist()]
    if limit is not None:
        keep = keep[:limit]
    return cp.asnumpy(keep)
示例#2
0
    def non_max_suppression(self, A, threshold=0.5):
        """Remove overlapping bounding boxes. Returns filterd boxes in screen coordinates and
        as an array with shape (n_boxes, (x1, y1, x2, y2)).
        Args:
            A (np.array): predicted labels and boxes.
            threshold (float): overlap threshold to treat as new box
        Returns:
            np.array: only max boxes.
        """
        x_stride = 34
        y_stride = 34
        score = []
        x1 = []
        x2 = []
        y1 = []
        y2 = []
        for i in range(0, A.shape[1]):
            for j in range(0, A.shape[2]):
                if A[0, i, j][0] > 0.5:
                    bx, by, w, h = A[0, i, j][1:]
                    score.append(A[0, i, j, 0])
                    x1.append((j + bx - w / 2) * x_stride + 29)
                    y1.append((i + by - h / 2) * y_stride)
                    x2.append((j + bx + w / 2) * x_stride + 29)
                    y2.append((i + by + h / 2) * y_stride)

        score = np.array(score)
        x1 = cp.array(x1)
        x2 = cp.array(x2)
        y1 = cp.array(y1)
        y2 = cp.array(y2)

        score_indexes = score.argsort().tolist()
        boxes_keep_index = []
        while len(score_indexes) > 0:
            index = score_indexes.pop()
            boxes_keep_index.append(index)
            if not len(score_indexes):
                break
            #iou
            xs1 = cp.maximum(x1[index], x1[score_indexes])
            ys1 = cp.maximum(y1[index], y1[score_indexes])
            xs2 = cp.minimum(x2[index], x2[score_indexes])
            ys2 = cp.minimum(y2[index], y2[score_indexes])
            intersections = cp.maximum(ys2 - ys1, 0) * cp.maximum(xs2 - xs1, 0)
            unions = (x2[index]-x1[index])*(y2[index]-y1[index]) \
                + (x2[score_indexes]-x1[score_indexes])*(y2[score_indexes]-y1[score_indexes]) \
                - intersections
            ious = np.array(cp.asnumpy(intersections / unions))
            filtered_indexes = set((ious > threshold).nonzero()[0])
            score_indexes = [
                v for (i, v) in enumerate(score_indexes)
                if i not in filtered_indexes
            ]

        nms_res = np.zeros((len(boxes_keep_index), 5))
        for i, j in enumerate(boxes_keep_index):
            nms_res[i, :] = np.array([score[j], x1[j], y1[j], x2[j], y2[j]])
        return nms_res
示例#3
0
文件: rpie.py 项目: tomography/tike
def _update_position(
    scan,
    position_options,
    position_update_numerator,
    position_update_denominator,
    alpha=0.05,
    max_shift=1,
):
    step = position_update_numerator / (
        (1 - alpha) * position_update_denominator +
        alpha * position_update_denominator.max())

    step_x = step[..., 0]
    step_y = step[..., 1]

    if position_options.use_adaptive_moment:
        logger.info(
            "position correction with ADAptive Momemtum acceleration enabled.")
        step_x, position_options.vx, position_options.mx = adam(
            step_x,
            position_options.vx,
            position_options.mx,
            vdecay=position_options.vdecay,
            mdecay=position_options.mdecay)
        step_y, position_options.vy, position_options.my = adam(
            step_y,
            position_options.vy,
            position_options.my,
            vdecay=position_options.vdecay,
            mdecay=position_options.mdecay)

    # Step limit for stability
    _max_shift = cp.minimum(
        max_shift,
        _mad(
            cp.concatenate((step_x, step_y), axis=-1),
            axis=-1,
            keepdims=True,
        ),
    )
    step_x = cp.maximum(-_max_shift, cp.minimum(step_x, _max_shift))
    step_y = cp.maximum(-_max_shift, cp.minimum(step_y, _max_shift))

    # Ensure net movement is zero
    step_x -= cp.mean(step_x, axis=-1, keepdims=True)
    step_y -= cp.mean(step_y, axis=-1, keepdims=True)
    logger.info('position update norm is %+.3e', tike.linalg.norm(step_x))

    scan[..., 0] -= step_x
    scan[..., 1] -= step_y

    return scan, position_options
示例#4
0
    def test_min(self):
        @jit.rawkernel()
        def f(x, y, z, r):
            tid = jit.blockDim.x * jit.blockIdx.x + jit.threadIdx.x
            r[tid] = min(x[tid], y[tid], z[tid])

        x = testing.shaped_random((1024,), dtype=numpy.int32, seed=0)
        y = testing.shaped_random((1024,), dtype=numpy.int32, seed=1)
        z = testing.shaped_random((1024,), dtype=numpy.int32, seed=2)
        r = testing.shaped_random((1024,), dtype=numpy.int32, seed=3)
        f((8,), (128,), (x, y, z, r))
        expected = cupy.minimum(x, cupy.minimum(y, z))
        assert bool((r == expected).all())
示例#5
0
def max_white(nimg):
    if nimg.dtype == np.uint8:
        brightest = float(2**8)
    elif nimg.dtype == np.uint16:
        brightest = float(2**16)
    elif nimg.dtype == np.uint32:
        brightest = float(2**32)
    else:
        brightest = float(2**8)
    nimg = nimg.transpose(2, 0, 1)
    nimg = nimg.astype(np.int32)
    nimg[0] = np.minimum(nimg[0] * (brightest / float(nimg[0].max())), 255)
    nimg[1] = np.minimum(nimg[1] * (brightest / float(nimg[1].max())), 255)
    nimg[2] = np.minimum(nimg[2] * (brightest / float(nimg[2].max())), 255)
    return nimg.transpose(1, 2, 0).astype(np.uint8)
示例#6
0
    def _nms_boxes(self, boxes, box_confidences):
        """Apply the Non-Maximum Suppression (NMS) algorithm on the bounding boxes with their
        confidence scores and return an array with the indexes of the bounding boxes we want to
        keep (and display later).

        Keyword arguments:
        boxes -- a NumPy array containing N bounding-box coordinates that survived filtering,
        with shape (N,4); 4 for x,y,height,width coordinates of the boxes
        box_confidences -- a Numpy array containing the corresponding confidences with shape N
        """
        x_coord = boxes[:, 0]
        y_coord = boxes[:, 1]
        width = boxes[:, 2]
        height = boxes[:, 3]

        areas = width * height
        ordered = box_confidences.argsort()[::-1]

        keep = list()
        while ordered.size > 0:
            # Index of the current element:
            i = ordered[0]
            ii = cp.asnumpy(i)
            keep.append(ii)
            xx1 = cp.maximum(x_coord[i], x_coord[ordered[1:]])
            yy1 = cp.maximum(y_coord[i], y_coord[ordered[1:]])
            xx2 = cp.minimum(x_coord[i] + width[i],
                             x_coord[ordered[1:]] + width[ordered[1:]])
            yy2 = cp.minimum(y_coord[i] + height[i],
                             y_coord[ordered[1:]] + height[ordered[1:]])

            width1 = cp.maximum(0.0, xx2 - xx1 + 1)
            height1 = cp.maximum(0.0, yy2 - yy1 + 1)
            intersection = width1 * height1
            union = (areas[i] + areas[ordered[1:]] - intersection)

            # Compute the Intersection over Union (IoU) score:
            iou = intersection / union

            # The goal of the NMS algorithm is to reduce the number of adjacent bounding-box
            # candidates to a minimum. In this step, we keep only those elements whose overlap
            # with the current bounding box is lower than the threshold:
            indexes = cp.where(iou <= self.nms_threshold)[0]
            ordered = ordered[indexes + 1]
        keep = np.array(keep)
        print(keep)
        keep = cp.asarray(keep)
        return keep
示例#7
0
文件: data.py 项目: mike-wendt/cupy
    def _min_or_max(self, axis, out, min_or_max, sum_duplicates, non_zero):
        if out is not None:
            raise ValueError(("Sparse matrices do not support "
                              "an 'out' parameter."))

        util.validateaxis(axis)

        if axis is None:
            if 0 in self.shape:
                raise ValueError("zero-size array to reduction operation")

            zero = cupy.zeros((), dtype=self.dtype)
            if self.nnz == 0:
                return zero
            if sum_duplicates:
                self.sum_duplicates()
            m = min_or_max(self.data)
            if non_zero:
                return m
            if self.nnz != internal.prod(self.shape):
                if min_or_max is cupy.min:
                    m = cupy.minimum(zero, m)
                elif min_or_max is cupy.max:
                    m = cupy.maximum(zero, m)
                else:
                    assert False
            return m

        if axis == 0 or axis == 1:
            return self._min_or_max_axis(axis, min_or_max, sum_duplicates,
                                         non_zero)
        else:
            raise ValueError("axis out of range")
示例#8
0
    def _min_or_max(self, axis, out, min_or_max, explicit):
        if out is not None:
            raise ValueError(("Sparse matrices do not support "
                              "an 'out' parameter."))

        sputils.validateaxis(axis)

        if axis is None:
            if 0 in self.shape:
                raise ValueError("zero-size array to reduction operation")

            zero = cupy.zeros((), dtype=self.dtype)
            if self.nnz == 0:
                return zero
            self.sum_duplicates()
            m = min_or_max(self.data)
            if explicit:
                return m
            if self.nnz != internal.prod(self.shape):
                if min_or_max is cupy.min:
                    m = cupy.minimum(zero, m)
                elif min_or_max is cupy.max:
                    m = cupy.maximum(zero, m)
                else:
                    assert False
            return m

        if axis < 0:
            axis += 2

        return self._min_or_max_axis(axis, min_or_max, explicit)
示例#9
0
def ruzicka_mat(matrix_a, vector_new):
    matrix_a *= cp.arange(1023, -1, -1, dtype=cp.uint16)
    min_up = cp.minimum(cp.array(matrix_a), vector_new)
    max_down = cp.maximum(cp.array(matrix_a), vector_new)
    numerator = cp.sum(min_up, axis=1)
    denominator = cp.sum(max_down, axis=1)
    return cp.asnumpy(cp.divide(numerator, denominator))
示例#10
0
def my_min(S1, sig, varargin=None):
    # returns a running minimum applied sequentially across a choice of dimensions and bin sizes
    # S1 is the matrix to be filtered
    # sig is either a scalar or a sequence of scalars, one for each axis to be filtered.
    #  it's the plus/minus bin length for the minimum filter
    # varargin can be the dimensions to do filtering, if len(sig) != x.shape
    # if sig is scalar and no axes are provided, the default axis is 2
    idims = 1
    if varargin is not None:
        idims = varargin
    idims = _make_vect(idims)
    if _is_vect(idims) and _is_vect(sig):
        sigall = sig
    else:
        sigall = np.tile(sig, len(idims))

    for sig, idim in zip(sigall, idims):
        Nd = S1.ndim
        S1 = cp.transpose(S1, [idim] + list(range(0, idim)) +
                          list(range(idim + 1, Nd)))
        dsnew = S1.shape
        S1 = cp.reshape(S1, (S1.shape[0], -1), order='F')
        dsnew2 = S1.shape
        S1 = cp.concatenate((cp.full(
            (sig, dsnew2[1]), np.inf), S1, cp.full((sig, dsnew2[1]), np.inf)),
                            axis=0)
        Smax = S1[:dsnew2[0], :]
        for j in range(1, 2 * sig + 1):
            Smax = cp.minimum(Smax, S1[j:j + dsnew2[0], :])
        S1 = cp.reshape(Smax, dsnew, order='F')
        S1 = cp.transpose(
            S1,
            list(range(1, idim + 1)) + [0] + list(range(idim + 1, Nd)))
    return S1
    def smearing(self, f, f_el, volt_mat, new_ind):
        '''

        Produces B matrix by comparing voltages

        takes:

        f - array shape (n_nodes)
        f_el - array shape (n_electrodes)
        volt_mat - array shape (n_measurements, 2)
        new_ind - array shape (n_measurements)

        returns:

        b-matrix - array shape (n_measurements, n_nodes)

        '''
        i = cp.arange(len(volt_mat))
        f_volt0 = f_el[new_ind, volt_mat[:, 0].astype(int)]
        f_volt1 = f_el[new_ind, volt_mat[:, 1].astype(int)]
        min_fel = cp.minimum(f_volt0, f_volt1)
        max_fel = cp.maximum(f_volt0, f_volt1)
        b_matrix = cp.empty((len(volt_mat), self.n_pts+self.ne))
        b_matrix[:] = (min_fel[:, None] < f[new_ind]) & (f[new_ind] <= max_fel[:, None])

        return b_matrix
示例#12
0
def constrain_variable_probe(variable_probe, weights):
    """Add the following constraints to variable probe weights

    1. Remove outliars from weights
    2. Enforce orthogonality once per epoch

    """
    logger.info('Orthogonalize variable probes')
    variable_probe = tike.linalg.orthogonalize_gs(
        variable_probe,
        axis=(-3, -2, -1),
    )

    logger.info('Remove outliars from variable probe weights')
    aevol = cp.abs(weights)
    weights = cp.minimum(
        aevol,
        1.5 * cp.percentile(
            aevol,
            [95],
            axis=[-3],
            keepdims=True,
        ).astype(weights.dtype),
    ) * cp.sign(weights)

    # TODO: Smooth the weights as a function of the frame index.

    return variable_probe, weights
示例#13
0
def genRecogBase(m, shape):
    """
    Generate recognition database
    
    Arguments:
    m -- number of examples
    shape -- shape

    Returns:
    X -- images
    Y -- labels
    """
    X = 0.5*cp.random.rand(m, shape[0], shape[1], shape[2])
    Y = cp.zeros((3, m))
    for i in range(m):
        typeM = np.random.randint(0, 3)
        if(typeM == 0):
            X[i, :, :, :] += cp.zeros(shape)
            Y[0, i] += 1
        if(typeM == 1):
            X[i, :, :, :] += cp.ones(shape)
            Y[1, i] += 1
        if(typeM == 2):
            X[i, :, :, np.random.randint(0, shape[2])] += cp.eye(shape[0], shape[1])
            Y[2, i] += 1
    return cp.minimum(X, 1), Y
        
示例#14
0
def ruzicka_vec(vector_old, vector_new):
    vector_old_cp = cp.array(vector_old) * cp.arange(
        1023, -1, -1, dtype=cp.uint16)
    min_up = cp.minimum(vector_old_cp, vector_new)
    max_down = cp.maximum(vector_old_cp, vector_new)
    numerator = cp.sum(min_up, axis=1)
    denominator = cp.sum(max_down, axis=1)
    return cp.asnumpy(cp.divide(numerator, denominator))
示例#15
0
 def clip(self, low, high):
     if not isinstance(low, VectorCupy):
         raise TypeError("Provided input low vector not a %s!" %
                         self.whoami)
     if not isinstance(high, VectorCupy):
         raise TypeError("Provided input high vector not a %s!" %
                         self.whoami)
     self.getNdArray()[:] = cp.minimum(
         cp.maximum(low.getNdArray(), self.getNdArray()), high.getNdArray())
     return self
示例#16
0
def getKernels(params):
    # this function makes upsampling kernels for the temporal components.
    # those are used for interpolating the biggest negative peak,
    # and aligning the template to that peak with sub-sample resolution
    # needs nup, the interpolation factor (default = 10)
    # also needs sig, the interpolation smoothness (default = 1)

    nup = params.nup
    sig = params.sig

    nt0min = params.nt0min
    nt0 = params.nt0

    xs = cp.arange(1, nt0 + 1)
    ys = cp.linspace(.5, nt0 + .5, nt0 * nup + 1)[:-1]

    # these kernels are just standard kriging interpolators

    # first compute distances between the sample coordinates
    # for some reason, this seems to be circular, although the waveforms are not circular
    # I think the reason had to do with some constant offsets in some channels?
    d = cp.mod(xs[:, np.newaxis] - xs[np.newaxis, :] + nt0, nt0)
    d = cp.minimum(d, nt0 - d)
    # the kernel covariance uses a squared exponential of spatial scale sig
    Kxx = cp.exp(-d**2 / sig**2)

    # do the same for the kernel similarities between upsampled "test" timepoints and
    # the original coordinates
    d = cp.mod(ys[:, np.newaxis] - xs[np.newaxis, :] + nt0, nt0)
    d = cp.minimum(d, nt0 - d)
    Kyx = cp.exp(-d**2 / sig**2)

    # the upsampling matrix is given by the following formula,
    # with some light diagonal regularization of the matrix inversion
    B = cp.dot(Kyx, cp.linalg.inv(Kxx + .01 * cp.eye(nt0)))
    B = B.reshape((nup, nt0, nt0), order='F')

    # A is just a slice through this upsampling matrix corresponding to the most negative point
    # this is used to compute the biggest negative deflection (after upsampling)
    A = cp.squeeze(B[:, nt0min - 1, :])
    B = cp.transpose(B, [1, 2, 0])

    return A.astype(np.float64), B.astype(np.float64)
示例#17
0
 def log_likelihood(self,par,**args):
     for k,v in args.items():
         if k=='X_train':
             X=cp.asarray(v)
         elif k=='y_train':
             y=cp.asarray(v)
     y_linear = cp.dot(X, par['weights']) + par['bias']
     y_linear=cp.minimum(y_linear,-cp.log(cp.finfo(float).eps))
     y_linear=cp.maximum(y_linear,-cp.log(1./cp.finfo(float).tiny-1.0))
     return cp.sum(self.cross_entropy(y_linear,y))
示例#18
0
def update_z(a_last, W, b, a, z_old, u, v, rho):
    z1 = np.matmul(W, a_last) + b - u / rho
    z2 = (z1 + a + v) / 2
    z1 = np.minimum(z1, 0)
    z2 = np.maximum(z2, 0)
    value1 = z_obj(a_last, W, b, z1, u, v, a, rho)
    value2 = z_obj(a_last, W, b, z2, u, v, a, rho)
    z = z1
    z[value1 > value2] = z2[value1 > value2]
    return z
示例#19
0
 def net(self,par,**args):
     for k,v in args.items():
         if k=='X_train':
             X=cp.asarray(v)
     y_linear = cp.dot(X, par['weights']) + par['bias']
     y_linear=cp.minimum(y_linear,-cp.log(cp.finfo(float).eps))
     y_linear=cp.maximum(y_linear,-cp.log(1./cp.finfo(float).tiny-1.0))
     #y_linear = cp.dot(X, par['weights']) 
     yhat = self.sigmoid(y_linear)
     return yhat
示例#20
0
 def clipVector(self, low, high):
     """Function to bound vector values based on input vectors low and high"""
     if not isinstance(low, VectorCupy):
         raise TypeError("Provided input low vector not a %s!" %
                         self.whoami)
     if not isinstance(high, VectorCupy):
         raise TypeError("Provided input high vector not a %s!" %
                         self.whoami)
     self.getNdArray()[:] = cp.minimum(
         cp.maximum(low.getNdArray(), self.getNdArray()), high.getNdArray())
     return self
示例#21
0
    def clip_gradient(self, gradient, threshold):
        # We do not use CuPy's linalg.norm, since it uses scalar reductions
        # using one CUDA block. This is a lot slower than the cuBLAS
        # implementation.
        def frobenius_norm(X):
            X_vec = X.reshape(-1)
            return cupy.cublas.nrm2(X_vec)

        grad_norm = cupy.maximum(frobenius_norm(gradient), 1e-12)
        gradient *= cupy.minimum(threshold, grad_norm) / grad_norm
        return gradient
示例#22
0
def colour_iterations(i: np.ndarray) -> np.ndarray:
    li = np.log(i)

    img = np.empty((TILE_SIZE, TILE_SIZE, 3), dtype=np.uint8)
    img[:, :, 0] = (li * 255) % 255
    img[:, :, 1] = 192
    img[:, :,
        2] = 128 + 13 * np.sin(li * 100) - np.minimum(115, (10000 * 13 /
                                                            (10000 - i)))

    return img
示例#23
0
def synaptic_plasticity(h, syn_x, syn_u, constants, use_stp, hidden_size):
    """ If required, applies STP updates to the hidden state and STP
        variables.  If not required, just ensures correct hidden shape. """

    # h = h[0,...] if h.ndim == 5 else False

    if use_stp:

        global which_step

        print("STARTING SYNAPTIC_PLASTICITY")
        print("running step {}".format(which_step))
        print(which_step)

        which_step = which_step + 1

        print("syn_x.shape")
        print(syn_x.shape)
        print("syn_u.shape")
        print(syn_u.shape)
        print("h.shape")
        print(h.shape)

        # input()

        syn_x += constants['alpha_std'] * (
            1 - syn_x) - constants['stp_mod'] * syn_u * syn_x * h
        syn_u += constants['alpha_stf'] * (
            constants['U'] -
            syn_u) + constants['stp_mod'] * constants['U'] * (1 - syn_u) * h
        syn_x = cp.minimum(1., relu(syn_x))
        syn_u = cp.minimum(1., relu(syn_u))
        h_post = syn_u * syn_x * h
    else:
        h_post = h * cp.ones([1, 1, hidden_size], dtype=h.dtype)

    return h_post, syn_x, syn_u
示例#24
0
	def _select_next(self, X_pairwise, gain, idx):
		"""This function will add the given item to the selected set."""

		if self.cupy:
			self.current_values = cupy.minimum(self.max_values,
				self.current_values + X_pairwise)
		elif self.sparse:
			self.current_values = numpy.minimum(self.max_values,
				X_pairwise.toarray()[0] + self.current_values)
		else:
			self.current_values = numpy.minimum(self.max_values,
				self.current_values + X_pairwise)

		super(SaturatedCoverageSelection, self)._select_next(
			X_pairwise, gain, idx)
示例#25
0
    def generate_q_u_matrix(x_coordinate: cp.array,
                            y_coordinate: cp.array) -> tuple:
        flatten_flag = x_coordinate.ndim > 1
        if flatten_flag:
            x_coordinate = x_coordinate.flatten()
            y_coordinate = y_coordinate.flatten()

        t, u = cp.modf(y_coordinate)
        u = u.astype(int)
        uy = cp.vstack([
            cp.minimum(cp.maximum(u - 1, 0), h - 1),
            cp.minimum(cp.maximum(u, 0), h - 1),
            cp.minimum(cp.maximum(u + 1, 0), h - 1),
            cp.minimum(cp.maximum(u + 2, 0), h - 1),
        ]).astype(int)
        Qy = cp.dot(
            coeff,
            cp.vstack([
                cp.ones_like(t, dtype=cp.float32), t,
                cp.power(t, 2),
                cp.power(t, 3)
            ]))
        t, u = cp.modf(x_coordinate)
        u = u.astype(int)
        ux = cp.vstack([
            cp.minimum(cp.maximum(u - 1, 0), w - 1),
            cp.minimum(cp.maximum(u, 0), w - 1),
            cp.minimum(cp.maximum(u + 1, 0), w - 1),
            cp.minimum(cp.maximum(u + 2, 0), w - 1),
        ])
        Qx = cp.dot(
            coeff,
            cp.vstack([
                cp.ones_like(t, dtype=cp.float32), t,
                cp.power(t, 2),
                cp.power(t, 3)
            ]))

        if flatten_flag:
            Qx = Qx.reshape(4, frame_n, int(w * mag)).transpose(1, 0, 2).copy()
            Qy = Qy.reshape(4, frame_n, int(h * mag)).transpose(1, 0, 2).copy()
            ux = ux.reshape(4, frame_n, int(w * mag)).transpose(1, 0, 2).copy()
            uy = uy.reshape(4, frame_n, int(h * mag)).transpose(1, 0, 2).copy()
        return Qx, Qy, ux, uy
示例#26
0
def make_buddhabrot(x_min, x_max, x_dim, y_min, y_max, y_dim, iters, gens,
                    sample_size):
    t0 = time.time()
    buddha_tensor = np.zeros((y_dim, x_dim), dtype=np.float32)
    for i in range(gens):
        iterate(buddha_tensor, x_min, x_max, x_dim, y_min, y_max, y_dim, iters,
                sample_size)
        print("\r\titeration: %d/%d" % (i + 1, gens), end='', flush=True)

    t1 = time.time()
    print_stats(buddha_tensor, x_dim, y_dim, t1 - t0)

    s = buddha_tensor.sum()
    buddha_tensor /= buddha_tensor.max()
    buddha_tensor = np.minimum(1.1 * buddha_tensor, buddha_tensor * .2 + .8)

    scipy.misc.toimage(np.asnumpy(buddha_tensor), cmin=0.0, cmax=1.0).save(
        "buddha_%dx%d_%d_%d.png" % (x_dim, y_dim, iters, s))
示例#27
0
 def _initialize_nets(self):
     self.weights = cp.random.normal(
         size=(self.pop_size, self.total, self.total),
         dtype='single') * cp.tile(
             cp.triu(cp.ones(shape=(self.total, self.total), dtype='bool_'),
                     1), (self.pop_size, 1, 1)) * (cp.random.uniform(
                         size=(self.pop_size, self.total, self.total),
                         dtype='single') < .5)
     self.weights[:, :, self.inputs:] *= cp.sqrt(4 / cp.minimum(
         cp.arange(self.inputs, self.total), self.inputs + self.hidden))
     self.weights[:, :self.inputs, :self.inputs] = 0
     self.weights[:, -self.outputs:, -self.outputs:] = cp.tile(
         cp.diag(
             cp.diag(
                 cp.ones(shape=(self.outputs, self.outputs),
                         dtype='bool_'))), (self.pop_size, 1, 1))
     self.biases = cp.random.normal(
         size=(self.pop_size, 1, self.hidden + self.outputs),
         dtype='single') * .5
示例#28
0
def reshape_to_yolo_size(img):
    input_height, input_width, _ = img.shape
    min_pixel = 320
    # max_pixel = 608
    max_pixel = 448

    min_edge = xp.minimum(input_width, input_height)
    if min_edge < min_pixel:
        input_width *= min_pixel / min_edge
        input_height *= min_pixel / min_edge
    max_edge = xp.maximum(input_width, input_height)
    if max_edge > max_pixel:
        input_width *= max_pixel / max_edge
        input_height *= max_pixel / max_edge

    input_width = int(input_width / 32) * 32
    input_height = int(input_height / 32) * 32
    img = cv2.resize(img, (input_width, input_height))

    return img
示例#29
0
def Initialization_Pop(PopSize, Model):
    Dim = 0
    SizeInform = []
    LengthInform = []
    Parameter = list(Model.parameters())

    for i in range(0, len(Parameter)):

        SizeInform.append([Parameter[i].shape])
        if len(Parameter[i].shape) < 2:
            Dim_module = Parameter[i].shape[0]
        else:
            Dim_module = np.array(numpy.prod(Parameter[i].shape))

        LengthInform.extend([Dim_module])

        Dim = Dim + Dim_module

    # Population = (np.random.random((PopSize, Dim * HiddenNum)) - 0.5) * 2 * ((np.power(6 / (Dim + HiddenNum), 1 / 2)))
    Dim = int(Dim)
    Population = np.random.rand(PopSize, Dim) - 0.5

    for i in range(PopSize):
        Model.apply(weight_init)
        Population[i] = Extract_weight(Model, SizeInform)
        Population[i] = Population[i] * (np.random.rand(Dim) <
                                         ((i + 1) / PopSize) / 1)  #

    Boundary = np.tile([[10], [-10]], [1, Dim])

    Upper = np.tile(Boundary[0], (PopSize, 1))
    Lower = np.tile(Boundary[1], (PopSize, 1))
    Population = np.maximum(np.minimum(Upper, Population), Lower)

    # Boundary = np.tile([[20], [-20]], [1, Dim * HiddenNum])
    Coding = 'Real'
    return Population, Boundary, Coding, SizeInform, LengthInform
示例#30
0
def map_coordinates(input,
                    coordinates,
                    output=None,
                    order=None,
                    mode='constant',
                    cval=0.0,
                    prefilter=True):
    """Map the input array to new coordinates by interpolation.
    The array of coordinates is used to find, for each point in the output, the
    corresponding coordinates in the input. The value of the input at those
    coordinates is determined by spline interpolation of the requested order.
    The shape of the output is derived from that of the coordinate array by
    dropping the first axis. The values of the array along the first axis are
    the coordinates in the input array at which the output value is found.
    Args:
        input (cupy.ndarray): The input array.
        coordinates (array_like): The coordinates at which ``input`` is
            evaluated.
        output (cupy.ndarray or ~cupy.dtype): The array in which to place the
            output, or the dtype of the returned array.
        order (int): The order of the spline interpolation. If it is not given,
            order 1 is used. It is different from :mod:`scipy.ndimage` and can
            change in the future. Currently it supports only order 0 and 1.
        mode (str): Points outside the boundaries of the input are filled
            according to the given mode (``'constant'``, ``'nearest'``,
            ``'mirror'`` or ``'opencv'``). Default is ``'constant'``.
        cval (scalar): Value used for points outside the boundaries of
            the input if ``mode='constant'`` or ``mode='opencv'``. Default is
            0.0
        prefilter (bool): It is not used yet. It just exists for compatibility
            with :mod:`scipy.ndimage`.
    Returns:
        cupy.ndarray:
            The result of transforming the input. The shape of the output is
            derived from that of ``coordinates`` by dropping the first axis.
    .. seealso:: :func:`scipy.ndimage.map_coordinates`
    """

    _check_parameter('map_coordinates', order, mode)

    if mode == 'opencv' or mode == '_opencv_edge':
        input = cupy.pad(input, [(1, 1)] * input.ndim,
                         'constant',
                         constant_values=cval)
        coordinates = cupy.add(coordinates, 1)
        mode = 'constant'

    ret = _get_output(output, input, coordinates.shape[1:])

    if mode == 'nearest':
        for i in six.moves.range(input.ndim):
            coordinates[i] = coordinates[i].clip(0, input.shape[i] - 1)
    elif mode == 'mirror':
        for i in six.moves.range(input.ndim):
            length = input.shape[i] - 1
            if length == 0:
                coordinates[i] = 0
            else:
                coordinates[i] = cupy.remainder(coordinates[i], 2 * length)
                coordinates[i] = 2 * cupy.minimum(coordinates[i],
                                                  length) - coordinates[i]

    if input.dtype.kind in 'iu':
        input = input.astype(cupy.float32)

    if order == 0:
        out = input[tuple(cupy.rint(coordinates).astype(cupy.int32))]
    else:
        coordinates_floor = cupy.floor(coordinates).astype(cupy.int32)
        coordinates_ceil = coordinates_floor + 1

        sides = []
        for i in six.moves.range(input.ndim):
            # TODO(mizuno): Use array_equal after it is implemented
            if cupy.all(coordinates[i] == coordinates_floor[i]):
                sides.append([0])
            else:
                sides.append([0, 1])

        out = cupy.zeros(coordinates.shape[1], dtype=input.dtype)
        if input.dtype in (cupy.float64, cupy.complex128):
            weight = cupy.empty(coordinates.shape[1], dtype=cupy.float64)
        else:
            weight = cupy.empty(coordinates.shape[1], dtype=cupy.float32)
        for side in itertools.product(*sides):
            weight.fill(1)
            ind = []
            for i in six.moves.range(input.ndim):
                if side[i] == 0:
                    ind.append(coordinates_floor[i])
                    weight *= coordinates_ceil[i] - coordinates[i]
                else:
                    ind.append(coordinates_ceil[i])
                    weight *= coordinates[i] - coordinates_floor[i]
            out += input[ind] * weight
        del weight

    if mode == 'constant':
        mask = cupy.zeros(coordinates.shape[1], dtype=cupy.bool_)
        for i in six.moves.range(input.ndim):
            mask += coordinates[i] < 0
            mask += coordinates[i] > input.shape[i] - 1
        out[mask] = cval
        del mask

    if ret.dtype.kind in 'iu':
        out = cupy.rint(out)
    ret[:] = out
    return ret