Python numpy.ogrid() Examples

The following are 30 code examples for showing how to use numpy.ogrid(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module numpy , or try the search function .

Example 1
Project: keras-utility-layer-collection   Author: zimmerrol   File: image.py    License: MIT License 6 votes vote down vote up
def _bilinear_upsampling_weights(weight_shape):
        # weight_shape must be (width, height, n_channels, n_channels)

        if weight_shape[-1] != weight_shape[-2]:
            raise ValueError("Number of input channels must be the same as the number of input channels.")

        weight = np.zeros(weight_shape, dtype=np.float32)

        # create single upsampling kernel for one channel
        # according to http://warmspringwinds.github.io/tensorflow/tf-slim/2016/11/22/upsampling-and-image-segmentation-with-tensorflow-and-tf-slim/

        grid = np.ogrid[:weight_shape[0], :weight_shape[1]]
        factors = [(s+1)//2 for s in weight_shape[:2]]
        centers = [(s+1)//2 - 0.5*(s%2 + 1) for s in weight_shape[:2]]

        upsampling_kernel = (1-abs(grid[0] - centers[0]) / factors[0]) * (1-abs(grid[1] - centers[1]) / factors[1])

        for i in range(weight_shape[-1]):
            weight[:, :, i, i] = upsampling_kernel

        return weight 
Example 2
Project: mars   Author: mars-project   File: core.py    License: Apache License 2.0 6 votes vote down vote up
def execute_agg(cls, ctx, op):
        axis = cls.get_arg_axis(op.axis, op.inputs[0].ndim)
        (vals, arg), device_id, xp = as_same_device(
            ctx[op.inputs[0].key], device=op.device, ret_extra=True)

        func_name = getattr(cls, '_func_name')
        arg_func = getattr(xp, func_name)

        with device(device_id):
            if xp.any(xp.isnan(vals)) and 'nan' in func_name:
                raise ValueError("All NaN slice encountered")
            if axis is None:
                local_args = arg_func(vals, axis=axis)
                arg = arg.ravel()[local_args]
            else:
                local_args = arg_func(vals, axis=axis)
                inds = np.ogrid[tuple(map(slice, local_args.shape))]
                if xp != np:
                    inds = [xp.asarray(it) for it in inds]
                inds.insert(axis, local_args)
                arg = arg[tuple(inds)]
            ctx[op.outputs[0].key] = arg 
Example 3
Project: mars   Author: mars-project   File: core.py    License: Apache License 2.0 6 votes vote down vote up
def execute_combine(cls, ctx, op):
        axis = cls.get_arg_axis(op.axis, op.inputs[0].ndim)
        (vals, arg), device_id, xp = as_same_device(
            ctx[op.inputs[0].key], device=op.device, ret_extra=True)

        func_name = getattr(cls, '_func_name')
        arg_func = getattr(xp, func_name)
        with device(device_id):
            if axis is None:
                local_args = arg_func(vals, axis=axis).reshape(op.outputs[0].shape)
                vals = vals.ravel()[local_args]
                arg = arg.ravel()[local_args]
            else:
                local_args = arg_func(vals, axis=axis)
                inds = np.ogrid[tuple(map(slice, local_args.shape))]
                if xp != np:
                    inds = [xp.asarray(it) for it in inds]
                inds.insert(axis, local_args)
                inds_tuple = tuple(inds)
                vals = vals[inds_tuple].reshape(op.outputs[0].shape)
                arg = arg[inds_tuple].reshape(op.outputs[0].shape)
            ctx[op.outputs[0].key] = (vals, arg) 
Example 4
def bilinear_interpolation_kernel(in_channels, out_channels, ksize):
    """calculate a bilinear interpolation kernel

    Args:
        in_channels (int): Number of channels of input arrays. If ``None``,
            parameter initialization will be deferred until the first forward
            data pass at which time the size will be determined.
        out_channels (int): Number of channels of output arrays.
        ksize (int): Size of filters (a.k.a. kernels).
    """

    factor = (ksize + 1) / 2
    if ksize % 2 == 1:
        center = factor - 1
    else:
        center = factor - 0.5
    og = np.ogrid[:ksize, :ksize]
    k = (1 - abs(og[0] - center) / factor) * (1 - abs(og[1] - center) / factor)
                                                                                
    W = np.zeros((in_channels, out_channels, ksize, ksize)).astype(np.float32)
    W[range(in_channels), range(out_channels), :, :] = k
    return W 
Example 5
Project: hed-pytorch   Author: meteorshowers   File: models.py    License: MIT License 6 votes vote down vote up
def make_bilinear_weights(size, num_channels):
    factor = (size + 1) // 2
    if size % 2 == 1:
        center = factor - 1
    else:
        center = factor - 0.5
    og = np.ogrid[:size, :size]
    filt = (1 - abs(og[0] - center) / factor) * (1 - abs(og[1] - center) / factor)
    # print(filt)
    filt = torch.from_numpy(filt)
    w = torch.zeros(num_channels, num_channels, size, size)
    w.requires_grad = False
    for i in range(num_channels):
        for j in range(num_channels):
            if i == j:
                w[i, j] = filt
    return w 
Example 6
Project: gluon-cv   Author: dmlc   File: target_generator.py    License: Apache License 2.0 6 votes vote down vote up
def _gaussian_2d(shape, sigma=1):
    """Generate 2d gaussian.

    Parameters
    ----------
    shape : tuple of int
        The shape of the gaussian.
    sigma : float
        Sigma for gaussian.

    Returns
    -------
    float
        2D gaussian kernel.

    """
    m, n = [(ss - 1.) / 2. for ss in shape]
    y, x = np.ogrid[-m:m+1, -n:n+1]

    h = np.exp(-(x * x + y * y) / (2 * sigma * sigma))
    h[h < np.finfo(h.dtype).eps * h.max()] = 0
    return h 
Example 7
Project: pywonderland   Author: neozhaoliang   File: kaleidoscope.py    License: MIT License 6 votes vote down vote up
def main(imgsize):
    y, x = np.ogrid[6: -6: imgsize*2j, -6: 6: imgsize*2j]
    z = x + y*1j
    z = RiemannSphere(Klein(Mobius(Klein(z))))

    # define colors in hsv space
    H = np.sin(z[0]*np.pi)**2
    S = np.cos(z[1]*np.pi)**2
    V = abs(np.sin(z[2]*np.pi) * np.cos(z[2]*np.pi))**0.2
    HSV = np.stack((H, S, V), axis=2)

    # transform to rgb space
    img = hsv_to_rgb(HSV)
    fig = plt.figure(figsize=(imgsize/100.0, imgsize/100.0), dpi=100)
    ax = fig.add_axes([0, 0, 1, 1], aspect=1)
    ax.axis('off')
    ax.imshow(img)
    fig.savefig('kaleidoscope.png') 
Example 8
Project: modred   Author: belson17   File: util.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def Hankel(first_col, last_row=None):
    """
    Construct a Hankel array, whose skew diagonals are constant.

    Args:
        ``first_col``: 1D array corresponding to first column of Hankel array.

    Kwargs:
        ``last_row``: 1D array corresponding to the last row of Hankel array.
        First element will be ignored.  Default is an array of zeros of the same
        size as ``first_col``.

    Returns:
        Hankel: 2D array with dimensions ``[len(first_col), len(last_row)]``.
    """
    first_col = np.array(first_col).flatten()
    if last_row is None:
        last_row = np.zeros(first_col.shape)
    else:
        last_row = last_row.flatten()

    unique_vals = np.concatenate((first_col, last_row[1:]))
    a, b = np.ogrid[0:len(first_col), 0:len(last_row)]
    indices = a + b
    return unique_vals[indices] 
Example 9
Project: kite   Author: pyrocko   File: scene_processing.py    License: GNU General Public License v3.0 6 votes vote down vote up
def apply(self):
        sc = self.scene
        org = self.original
        factor = self.factor

        sx, sy = sc.displacement.shape
        gx, gy = num.ogrid[0:sx, 0:sy]
        regions = sy/factor * (gx/factor) + gy/factor
        indices = num.arange(regions.max() + 1)

        def block_downsample(arr):
            res = ndimage.mean(
                arr,
                labels=regions,
                index=indices)
            res.shape = (sx/factor, sy/factor)
            return res

        sc.displacement = block_downsample(sc.displacement)
        sc.theta = block_downsample(sc.theta)
        sc.phi = block_downsample(sc.phi)
        sc.frame.dLat = org['frame.dLat'] * self.factor
        sc.frame.dLon = org['frame.dLat'] * self.factor 
Example 10
Project: neural-network-animation   Author: miloharper   File: test_backend_pgf.py    License: MIT License 6 votes vote down vote up
def test_bbox_inches():
    if not check_for('xelatex'):
        raise SkipTest('xelatex + pgf is required')

    rc_xelatex = {'font.family': 'serif',
                  'pgf.rcfonts': False}
    mpl.rcParams.update(rc_xelatex)

    Y, X = np.ogrid[-1:1:40j, -1:1:40j]
    fig = plt.figure()
    ax1 = fig.add_subplot(121)
    ax1.plot(range(5))
    ax2 = fig.add_subplot(122)
    ax2.plot(range(5))
    plt.tight_layout()

    bbox = ax1.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
    compare_figure('pgf_bbox_inches.pdf', savefig_kwargs={'bbox_inches': bbox}) 
Example 11
Project: KCF-DSST-py   Author: ryanfwy   File: tracker.py    License: MIT License 6 votes vote down vote up
def createHanningMats(self):
        hann2t, hann1t = np.ogrid[0:self.size_patch[0], 0:self.size_patch[1]]
 
        hann1t = 0.5 * (1 - np.cos(2 * np.pi * hann1t / (self.size_patch[1] - 1)))
        hann2t = 0.5 * (1 - np.cos(2 * np.pi * hann2t / (self.size_patch[0] - 1)))
        hann2d = hann2t * hann1t
 
        if self._hogfeatures:
            hann1d = hann2d.reshape(self.size_patch[0] * self.size_patch[1])
            self.hann = np.zeros((self.size_patch[2], 1), np.float32) + hann1d
            #相当于把1D汉宁窗复制成多个通道
        else:
            self.hann = hann2d
        
        self.hann = self.hann.astype(np.float32)

    # 创建高斯峰函数,函数只在第一帧的时候执行(高斯响应) 
Example 12
Project: versa   Author: Gordonjo   File: mini_imagenet.py    License: MIT License 6 votes vote down vote up
def onehottify_2d_array(a):
    """
    https://stackoverflow.com/questions/36960320/convert-a-2d-matrix-to-a-3d-one-hot-matrix-numpy
    :param a: 2-dimensional array.
    :return: 3-dim array where last dim corresponds to one-hot encoded vectors.
    """

    # https://stackoverflow.com/a/46103129/ @Divakar
    def all_idx(idx, axis):
        grid = np.ogrid[tuple(map(slice, idx.shape))]
        grid.insert(axis, idx)
        return tuple(grid)

    num_columns = a.max() + 1
    out = np.zeros(a.shape + (num_columns,), dtype=int)
    out[all_idx(a, axis=2)] = 1
    return out 
Example 13
Project: Counting-ICCV-DSSINet   Author: Legion56   File: density_gen.py    License: MIT License 6 votes vote down vote up
def get(self, shape=(3, 3), sigma=0.5):
        if '%d_%d' % (int(shape[0]), int(sigma * 10)) not in self.kernel_set.keys():
            m, n = [(ss - 1.0) / 2.0 for ss in shape]
            y, x = np.ogrid[-m:m + 1, -n:n + 1]
            h = np.exp(-(x * x + y * y) / (2.0 * sigma * sigma))
            h[h < np.finfo(h.dtype).eps * h.max()] = 0
            # import pdb
            # pdb.set_trace()
            t = h[0][int(m)]
            h[h < t] = 0
            sumh = h.sum()
            if sumh != 0:
                h /= sumh
            self.kernel_set['%d_%d' % (int(shape[0]), int(sigma * 10))] = h
            return h
        else:
            return self.kernel_set['%d_%d' % (int(shape[0]), int(sigma * 10))] 
Example 14
Project: dal   Author: montrealrobotics   File: utils.py    License: MIT License 6 votes vote down vote up
def create_circular_mask(h, w, center=None, radius=None, angle=None, thick=0):
    # img = np.random.randint(0,2,(4,224,224))
    # print (img.shape)
    # mask = create_circular_mask(224,224, center = (100,100), radius = 20)
    # img[3,~mask] = 0
    # plt.imshow(img[3,:,:])
    # plt.show()

    if center is None: # use the middle of the image
        center = [int(w/2), int(h/2)]
    if radius is None: # use the smallest distance between the center and image walls
        radius = min(center[0], center[1], w-center[0], h-center[1])

    Y, X = np.ogrid[:h, :w]
    dist_from_center = np.sqrt((X - center[0])**2 + (Y-center[1])**2)
    if angle is None:
        mask = (dist_from_center <= radius)
    else:
        angle_from_center = np.arctan2(Y-center[1],X-center[0])
        mask = (dist_from_center <= radius) & (np.abs(np.unwrap(angle_from_center-angle)) * dist_from_center <= thick)
        #(angle_from_center < angle+0.15/(dist_from_center+0.01)) & (angle_from_center > angle-0.15/(dist_from_center+0.01))
    return mask 
Example 15
Project: dal   Author: montrealrobotics   File: utils.py    License: MIT License 6 votes vote down vote up
def create_circular_mask(h, w, center=None, radius=None, angle=None, thick=0):
    # img = np.random.randint(0,2,(4,224,224))
    # print (img.shape)
    # mask = create_circular_mask(224,224, center = (100,100), radius = 20)
    # img[3,~mask] = 0
    # plt.imshow(img[3,:,:])
    # plt.show()

    if center is None: # use the middle of the image
        center = [int(w/2), int(h/2)]
    if radius is None: # use the smallest distance between the center and image walls
        radius = min(center[0], center[1], w-center[0], h-center[1])

    Y, X = np.ogrid[:h, :w]
    dist_from_center = np.sqrt((X - center[0])**2 + (Y-center[1])**2)
    if angle is None:
        mask = (dist_from_center <= radius)
    else:
        angle_from_center = np.arctan2(Y-center[1],X-center[0])
        mask = (dist_from_center <= radius) & (np.abs(np.unwrap(angle_from_center-angle)) * dist_from_center <= thick)
        #(angle_from_center < angle+0.15/(dist_from_center+0.01)) & (angle_from_center > angle-0.15/(dist_from_center+0.01))
    return mask 
Example 16
Project: dal   Author: montrealrobotics   File: utils.py    License: MIT License 6 votes vote down vote up
def create_circular_mask(h, w, center=None, radius=None, angle=None, thick=0):
    # img = np.random.randint(0,2,(4,224,224))
    # print (img.shape)
    # mask = create_circular_mask(224,224, center = (100,100), radius = 20)
    # img[3,~mask] = 0
    # plt.imshow(img[3,:,:])
    # plt.show()

    if center is None: # use the middle of the image
        center = [int(w/2), int(h/2)]
    if radius is None: # use the smallest distance between the center and image walls
        radius = min(center[0], center[1], w-center[0], h-center[1])

    Y, X = np.ogrid[:h, :w]
    dist_from_center = np.sqrt((X - center[0])**2 + (Y-center[1])**2)
    if angle is None:
        mask = (dist_from_center <= radius)
    else:
        angle_from_center = np.arctan2(Y-center[1],X-center[0])
        mask = (dist_from_center <= radius) & (np.abs(np.unwrap(angle_from_center-angle)) * dist_from_center <= thick)
        #(angle_from_center < angle+0.15/(dist_from_center+0.01)) & (angle_from_center > angle-0.15/(dist_from_center+0.01))
    return mask 
Example 17
Project: cross-season-segmentation   Author: maunzzz   File: misc.py    License: MIT License 6 votes vote down vote up
def get_upsampling_weight(in_channels, out_channels, kernel_size):
    factor = (kernel_size + 1) // 2
    if kernel_size % 2 == 1:
        center = factor - 1
    else:
        center = factor - 0.5
    og = np.ogrid[:kernel_size, :kernel_size]
    filt = (1 - abs(og[0] - center) / factor) * \
        (1 - abs(og[1] - center) / factor)
    weight = np.zeros(
        (in_channels,
         out_channels,
         kernel_size,
         kernel_size),
        dtype=np.float64)
    weight[list(range(in_channels)), list(range(out_channels)), :, :] = filt
    return torch.from_numpy(weight).float() 
Example 18
Project: CU-Net   Author: zhiqiangdon   File: HumanPts.py    License: Apache License 2.0 6 votes vote down vote up
def pts2resmap(pts, resmap_shape, radius):
    # generate multi-channel resmap, one map for each point
    pts_num = pts.shape[0]
    resmap = np.zeros((pts_num, resmap_shape[0], resmap_shape[1]))
    valid_pts = np.zeros((pts.shape))
    for i in range(0, pts_num):
        # if vis_arr[i] == -1:
        #     continue
        # note that here we can't use vis_arr to indicate whether to draw the annotation
        # because some pts are labeled visible but not within the effective crop area due to the
        # inaccurate person scale in the original annotation
        if pts[i][0] <= 0 or pts[i][1] <= 0 or \
                        pts[i][0] > resmap_shape[1] or pts[i][1] > resmap_shape[0]:
            continue
        y, x = np.ogrid[-pts[i][1]:resmap_shape[0] - pts[i][1], -pts[i][0]:resmap_shape[1] - pts[i][0]]
        mask = x * x + y * y <= radius * radius
        resmap[i][mask] = 1
        valid_pts[i] = pts[i]
        # print('channel %d sum is %.f' % (i, np.sum(resmap[i])))
    return resmap, valid_pts 
Example 19
Project: python3_ios   Author: holzschu   File: test_backend_pgf.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_bbox_inches():
    rc_xelatex = {'font.family': 'serif',
                  'pgf.rcfonts': False}
    mpl.rcParams.update(rc_xelatex)

    Y, X = np.ogrid[-1:1:40j, -1:1:40j]
    fig = plt.figure()
    ax1 = fig.add_subplot(121)
    ax1.plot(range(5))
    ax2 = fig.add_subplot(122)
    ax2.plot(range(5))
    plt.tight_layout()

    bbox = ax1.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
    compare_figure('pgf_bbox_inches.pdf', savefig_kwargs={'bbox_inches': bbox},
                   tol=0) 
Example 20
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: init_fcnxs.py    License: Apache License 2.0 5 votes vote down vote up
def upsample_filt(size):
    factor = (size + 1) // 2
    if size % 2 == 1:
        center = factor - 1.0
    else:
        center = factor - 0.5
    og = np.ogrid[:size, :size]
    return (1 - abs(og[0] - center) / factor) * \
           (1 - abs(og[1] - center) / factor) 
Example 21
Project: Parsing-R-CNN   Author: soeaver   File: bilinear_interpolation2d.py    License: MIT License 5 votes vote down vote up
def __init__(self, in_channels, out_channels, up_scale):
        super().__init__()
        assert in_channels == out_channels
        assert up_scale % 2 == 0, 'Scale should be even'
        self.in_channes = in_channels
        self.out_channels = out_channels
        self.up_scale = int(up_scale)
        self.padding = up_scale // 2

        def upsample_filt(size):
            factor = (size + 1) // 2
            if size % 2 == 1:
                center = factor - 1
            else:
                center = factor - 0.5
            og = np.ogrid[:size, :size]
            return ((1 - abs(og[0] - center) / factor) *
                    (1 - abs(og[1] - center) / factor))

        kernel_size = up_scale * 2
        bil_filt = upsample_filt(kernel_size)

        kernel = np.zeros(
            (in_channels, out_channels, kernel_size, kernel_size), dtype=np.float32
        )
        kernel[range(in_channels), range(out_channels), :, :] = bil_filt

        self.upconv = nn.ConvTranspose2d(in_channels, out_channels, kernel_size,
                                         stride=self.up_scale, padding=self.padding)

        self.upconv.weight.data.copy_(torch.from_numpy(kernel))
        self.upconv.bias.data.fill_(0)
        self.upconv.weight.requires_grad = False
        self.upconv.bias.requires_grad = False 
Example 22
Project: VASPy   Author: PytLab   File: electro.py    License: MIT License 5 votes vote down vote up
def plot_mcontour(self, ndim0, ndim1, z, show_mode):
        "use mayavi.mlab to plot contour."
        if not mayavi_installed:
            self.__logger.info("Mayavi is not installed on your device.")
            return
        #do 2d interpolation
        #get slice object
        s = np.s_[0:ndim0:1, 0:ndim1:1]
        x, y = np.ogrid[s]
        mx, my = np.mgrid[s]
        #use cubic 2d interpolation
        interpfunc = interp2d(x, y, z, kind='cubic')
        newx = np.linspace(0, ndim0, 600)
        newy = np.linspace(0, ndim1, 600)
        newz = interpfunc(newx, newy)
        #mlab
        face = mlab.surf(newx, newy, newz, warp_scale=2)
        mlab.axes(xlabel='x', ylabel='y', zlabel='z')
        mlab.outline(face)
        #save or show
        if show_mode == 'show':
            mlab.show()
        elif show_mode == 'save':
            mlab.savefig('mlab_contour3d.png')
        else:
            raise ValueError('Unrecognized show mode parameter : ' +
                             show_mode)

        return 
Example 23
Project: cycada_release   Author: jhoffman   File: fcn8s.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get_upsample_filter(size):
    """Make a 2D bilinear kernel suitable for upsampling"""
    factor = (size + 1) // 2
    if size % 2 == 1:
        center = factor - 1
    else:
        center = factor - 0.5
    og = np.ogrid[:size, :size]
    filter = (1 - abs(og[0] - center) / factor) * \
             (1 - abs(og[1] - center) / factor)
    return torch.from_numpy(filter).float() 
Example 24
Project: CornerNet-Lite-Pytorch   Author: DataXujing   File: utils.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def gaussian2D(shape, sigma=1):
    """
    :param shape: (diameter, diameter) 直径,直径
    :param sigma: (diameter / 6)
    :return:
    """

    # 先拿到半径
    m, n = [(ss - 1.) / 2. for ss in shape]
    y, x = np.ogrid[-m:m + 1, -n:n + 1]

    h = np.exp(-(x * x + y * y) / (2 * sigma * sigma))
    h[h < np.finfo(h.dtype).eps * h.max()] = 0
    return h 
Example 25
Project: centernet_tensorflow_wilderface_voc   Author: xggIoU   File: create_label.py    License: MIT License 5 votes vote down vote up
def creat_roiheatmap_ellipse(det_size_map):
    sigma_x = ((det_size_map[1] - 1) * 0.5 - 1) * 0.3 + 0.8
    s_x = 2 * (sigma_x ** 2)
    sigma_y = ((det_size_map[0] - 1) * 0.5 - 1) * 0.3 + 0.8
    s_y = 2 * (sigma_y ** 2)
    h, w = [(hw - 1.) / 2. for hw in det_size_map]
    y, x = np.ogrid[-h:h + 1, -w:w + 1]
    heatmap = np.exp(-x**2 / s_x - y**2 / s_y)
    return heatmap 
Example 26
Project: centernet_tensorflow_wilderface_voc   Author: xggIoU   File: create_label.py    License: MIT License 5 votes vote down vote up
def creat_roiheatmap_circle(det_size_map):
    min_size=min(det_size_map)
    sigma = ((min_size - 1) * 0.5 - 1) * 0.3 + 0.8
    s_ = 2 * (sigma ** 2)
    h, w = [(hw - 1.) / 2. for hw in det_size_map]
    y, x = np.ogrid[-h:h + 1, -w:w + 1]
    heatmap = np.exp(-x**2 / s_ - y**2 / s_)
    return heatmap 
Example 27
Project: LagouJob   Author: lucasxlu   File: hot_words_generator.py    License: Apache License 2.0 5 votes vote down vote up
def cal_and_show_job_impression_hot_words(self, interviewee_comments_dir='../spider/impression'):
        """
        calculate and show hot words of Job Impression
        :param interviewee_comments_dir:
        :return:
        """
        if not os.path.exists(interviewee_comments_dir) or len(os.listdir(interviewee_comments_dir)) == 0:
            print('Error! No valid content in {0}'.format(interviewee_comments_dir))
            sys.exit(0)
        else:
            job_and_dir = {_: os.path.join(interviewee_comments_dir, _) for _ in os.listdir(interviewee_comments_dir)}

            for k, v in job_and_dir.items():
                text = self.concat_all_text(v)
                jieba.analyse.set_stop_words(STOPWORDS_PATH)
                jieba.load_userdict(USER_CORPUS)
                hot_words_with_weights = jieba.analyse.extract_tags(text, topK=30, withWeight=True, allowPOS=())

                frequencies = {_[0]: _[1] for _ in hot_words_with_weights}

                print(frequencies)

                x, y = np.ogrid[:300, :300]
                mask = (x - 150) ** 2 + (y - 150) ** 2 > 130 ** 2
                mask = 255 * mask.astype(int)

                wordcloud = WordCloud(font_path='./msyh.ttf', width=600, height=300, background_color="white",
                                      repeat=False,
                                      mask=mask)
                wordcloud.generate_from_frequencies(frequencies)

                import matplotlib.pyplot as plt
                plt.imshow(wordcloud, interpolation='bilinear')
                plt.axis("off")
                plt.show() 
Example 28
Project: LagouJob   Author: lucasxlu   File: hot_words_generator.py    License: Apache License 2.0 5 votes vote down vote up
def cal_and_show_jd_hot_words(self, jd_dir='../spider/jd'):
        """
        calculate and show hot words of Job Description (JD)
        :param jd_dir:
        :return:
        """
        if not os.path.exists(jd_dir) or len(os.listdir(jd_dir)) == 0:
            print('Error! No valid content in {0}'.format(jd_dir))
            sys.exit(0)
        else:
            jd_and_dir = {_.split('.')[0]: os.path.join(jd_dir, _) for _ in os.listdir(jd_dir)}

            for k, v in jd_and_dir.items():
                text = "".join(pd.read_excel(v)['详情描述'])
                jieba.analyse.set_stop_words(STOPWORDS_PATH)
                jieba.load_userdict(USER_CORPUS)
                hot_words_with_weights = jieba.analyse.extract_tags(text, topK=30, withWeight=True, allowPOS=())

                frequencies = {_[0]: _[1] for _ in hot_words_with_weights}

                print(frequencies)

                x, y = np.ogrid[:300, :300]
                mask = (x - 150) ** 2 + (y - 150) ** 2 > 130 ** 2
                mask = 255 * mask.astype(int)

                wordcloud = WordCloud(font_path='./msyh.ttf', width=600, height=300, background_color="white",
                                      repeat=False,
                                      mask=mask)
                wordcloud.generate_from_frequencies(frequencies)

                import matplotlib.pyplot as plt
                plt.imshow(wordcloud, interpolation='bilinear')
                plt.axis("off")
                plt.show() 
Example 29
Project: lambda-packs   Author: ryfeus   File: special_matrices.py    License: MIT License 5 votes vote down vote up
def circulant(c):
    """
    Construct a circulant matrix.

    Parameters
    ----------
    c : (N,) array_like
        1-D array, the first column of the matrix.

    Returns
    -------
    A : (N, N) ndarray
        A circulant matrix whose first column is `c`.

    See Also
    --------
    toeplitz : Toeplitz matrix
    hankel : Hankel matrix
    solve_circulant : Solve a circulant system.

    Notes
    -----
    .. versionadded:: 0.8.0

    Examples
    --------
    >>> from scipy.linalg import circulant
    >>> circulant([1, 2, 3])
    array([[1, 3, 2],
           [2, 1, 3],
           [3, 2, 1]])

    """
    c = np.asarray(c).ravel()
    a, b = np.ogrid[0:len(c), 0:-len(c):-1]
    indx = a + b
    # `indx` is a 2D array of indices into `c`, arranged so that `c[indx]` is
    # the circulant matrix.
    return c[indx] 
Example 30
Project: DSS   Author: Andrew-Qibin   File: run_saliency.py    License: MIT License 5 votes vote down vote up
def upsample_filt(size):
    factor = (size + 1) // 2
    if size % 2 == 1:
        center = factor - 1
    else:
        center = factor - 0.5
    og = np.ogrid[:size, :size]
    return (1 - abs(og[0] - center) / factor) * \
           (1 - abs(og[1] - center) / factor)

# set parameters s.t. deconvolutional layers compute bilinear interpolation
# N.B. this is for deconvolution without groups