Python sklearn.utils.extmath.cartesian() Examples

The following are 8 code examples of sklearn.utils.extmath.cartesian(). 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 also want to check out all available functions/classes of the module sklearn.utils.extmath , or try the search function .
Example #1
Source File: test_extmath.py    From twitter-stock-recommendation with MIT License 7 votes vote down vote up
def test_cartesian():
    # Check if cartesian product delivers the right results

    axes = (np.array([1, 2, 3]), np.array([4, 5]), np.array([6, 7]))

    true_out = np.array([[1, 4, 6],
                         [1, 4, 7],
                         [1, 5, 6],
                         [1, 5, 7],
                         [2, 4, 6],
                         [2, 4, 7],
                         [2, 5, 6],
                         [2, 5, 7],
                         [3, 4, 6],
                         [3, 4, 7],
                         [3, 5, 6],
                         [3, 5, 7]])

    out = cartesian(axes)
    assert_array_equal(true_out, out)

    # check single axis
    x = np.arange(3)
    assert_array_equal(x[:, np.newaxis], cartesian((x,))) 
Example #2
Source File: test_extmath.py    From Mastering-Elasticsearch-7.0 with MIT License 6 votes vote down vote up
def test_cartesian():
    # Check if cartesian product delivers the right results

    axes = (np.array([1, 2, 3]), np.array([4, 5]), np.array([6, 7]))

    true_out = np.array([[1, 4, 6],
                         [1, 4, 7],
                         [1, 5, 6],
                         [1, 5, 7],
                         [2, 4, 6],
                         [2, 4, 7],
                         [2, 5, 6],
                         [2, 5, 7],
                         [3, 4, 6],
                         [3, 4, 7],
                         [3, 5, 6],
                         [3, 5, 7]])

    out = cartesian(axes)
    assert_array_equal(true_out, out)

    # check single axis
    x = np.arange(3)
    assert_array_equal(x[:, np.newaxis], cartesian((x,))) 
Example #3
Source File: Core.py    From AiGEM_TeamHeidelberg2017 with MIT License 5 votes vote down vote up
def __init__(self, Complex, space, size, grid_spacing=1, grid_bounds=[-1e2,1e2]):
        super(EnergyGridSampler, self).__init__(Complex, space, size)
        self.best_energy = 1e100
        self.best_positions = self.positions
        self.grid_spacing = grid_spacing
        self.grid_bounds = grid_bounds
        self.grid = cartesian((np.linspace(self.grid_bounds[0],self.grid_bounds[1],grid_spacing),
                              np.linspace(self.grid_bounds[0],self.grid_bounds[1],grid_spacing),
                              np.linspace(self.grid_bounds[0],self.grid_bounds[1],grid_spacing)))
        self.mask = np.apply_along_axis(self.space.is_in, self.grid, axis=0)
        grid = []
        for position, truth in zip(self.grid, self.mask):
            if truth:
                grid.append(position)
        self.grid = np.array(grid) 
Example #4
Source File: cars3d.py    From disentanglement_lib with Apache License 2.0 5 votes vote down vote up
def __init__(self):
    self.factor_sizes = [4, 24, 183]
    features = cartesian([np.array(list(range(i))) for i in self.factor_sizes])
    self.latent_factor_indices = [0, 1, 2]
    self.num_total_factors = features.shape[1]
    self.index = util.StateSpaceAtomIndex(self.factor_sizes, features)
    self.state_space = util.SplitDiscreteStateSpace(self.factor_sizes,
                                                    self.latent_factor_indices)
    self.data_shape = [64, 64, 3]
    self.images = self._load_data() 
Example #5
Source File: cv.py    From snfpy with GNU Lesser General Public License v3.0 5 votes vote down vote up
def get_neighbors(ijk, shape, neighbors='faces'):
    """
    Returns indices of neighbors to `ijk` in array of shape `shape`

    Parameters
    ----------
    ijk : array_like
        Indices of coordinates of interest
    shape : tuple
        Tuple indicating shape of array from which `ijk` is drawn
    neighbors : str, optional
        One of ['faces', 'edges', 'corners']. Default: 'faces'

    Returns
    -------
    inds : tuple of tuples
        Indices of neighbors to `ijk` (includes input coordinates)
    """

    neigh = ['faces', 'edges', 'corners']
    if neighbors not in neigh:
        raise ValueError('Provided neighbors {} not valid. Must be one of {}.'
                         .format(neighbors, neigh))

    ijk = np.asarray(ijk)
    if ijk.ndim != 2:
        ijk = ijk[np.newaxis]
    if ijk.shape[-1] != len(shape):
        raise ValueError('Provided coordinate {} needs to have same '
                         'dimensions as provided shape {}'.format(ijk, shape))

    dist = np.sqrt(neigh.index(neighbors) + 1)
    xyz = cartesian([range(i) for i in shape])
    inds = tuple(map(tuple, xyz[np.ravel(cdist(ijk, xyz) <= dist)].T))

    return inds 
Example #6
Source File: taxi.py    From mushroom-rl with MIT License 5 votes vote down vote up
def compute_reward(grid_map, cell_list, passenger_list, rew):
    """
    Compute the reward matrix.

    Args:
        grid_map (list): list containing the grid structure;
        cell_list (list): list of non-wall cells;
        passenger_list (list): list of passenger cells;
        rew (tuple): rewards obtained in goal states.

    Returns:
        The reward matrix.

    """
    g = np.array(grid_map)
    c = np.array(cell_list)
    n_states = len(cell_list) * 2**len(passenger_list)
    r = np.zeros((n_states, 4, n_states))
    directions = [[-1, 0], [1, 0], [0, -1], [0, 1]]
    passenger_states = cartesian([[0, 1]] * len(passenger_list))

    for goal in np.argwhere(g == 'G'):
        for a in range(len(directions)):
            prev_state = goal - directions[a]
            if prev_state in c:
                for i in range(len(passenger_states)):
                    i_idx = np.where((c == prev_state).all(axis=1))[0] + len(
                        cell_list) * i
                    j_idx = j = np.where((c == goal).all(axis=1))[0] + len(
                        cell_list) * i

                    r[i_idx, a, j_idx] = rew[np.sum(passenger_states[i])]

    return r 
Example #7
Source File: data_engine.py    From RPNplus with MIT License 5 votes vote down vote up
def compute_overlap(mat1, mat2):
    s1 = mat1.shape[0]
    s2 = mat2.shape[0]
    area1 = (mat1[:, 2] - mat1[:, 0]) * (mat1[:, 3] - mat1[:, 1])
    if mat2.shape[1] == 5:
        area2 = mat2[:, 4]
    else:
        area2 = (mat2[:, 2] - mat2[:, 0]) * (mat2[:, 3] - mat2[:, 1])

    x1 = cartesian([mat1[:, 0], mat2[:, 0]])

    x1 = np.amax(x1, axis=1)
    x2 = cartesian([mat1[:, 2], mat2[:, 2]])
    x2 = np.amin(x2, axis=1)
    com_zero = np.zeros(x2.shape[0])
    w = x2 - x1
    w = w - 1

    w = np.maximum(com_zero, w)

    y1 = cartesian([mat1[:, 1], mat2[:, 1]])
    y1 = np.amax(y1, axis=1)
    y2 = cartesian([mat1[:, 3], mat2[:, 3]])
    y2 = np.amin(y2, axis=1)
    h = y2 - y1
    h = h - 1
    h = np.maximum(com_zero, h)

    oo = w * h

    aa = cartesian([area1[:], area2[:]])
    aa = np.sum(aa, axis=1)

    ooo = oo / (aa - oo)

    overlap = np.transpose(ooo.reshape(s1, s2), (1, 0))

    return overlap 
Example #8
Source File: cv.py    From snfpy with GNU Lesser General Public License v3.0 4 votes vote down vote up
def zrand_convolve(labelgrid, neighbors='edges', return_std=False, n_proc=-1):
    """
    Calculates the avg and std z-Rand index using kernel over `labelgrid`

    Kernel is determined by `neighbors`, which can include all entries with
    touching edges (i.e., 4 neighbors) or corners (i.e., 8 neighbors).

    Parameters
    ----------
    grid : (S, K, N) array_like
        Array containing cluster labels for each `N` samples, where `S` is mu
        and `K` is K.
    neighbors : str, optional
        How many neighbors to consider when calculating Z-rand kernel. Must be
        in ['edges', 'corners']. Default: 'edges'
    return_std : bool, optional
        Whether to return `zrand_std` in addition to `zrand_avg`. Default: True

    Returns
    -------
    zrand_avg : (S, K) np.ndarray
        Array containing average of the z-Rand index calculated using provided
        neighbor kernel
    zrand_std : (S, K) np.ndarray
        Array containing standard deviation of the z-Rand index
    """

    def _get_zrand(ijk):
        ninds = get_neighbors(ijk, shape=shape, neighbors=neighbors)
        return zrand_partitions(labelgrid[ninds].T)

    shape = labelgrid.shape[:-1]
    inds = cartesian([range(i) for i in shape])

    if use_joblib:
        _zr = Parallel(n_jobs=n_proc)(delayed(_get_zrand)(ijk) for ijk in inds)
    else:
        _zr = [_get_zrand(ijk) for ijk in inds]

    zr = np.empty(shape=shape + (2,))
    for ijk, z in zip(inds, _zr):
        zr[tuple(ijk)] = z

    if return_std:
        return zr[..., 0], zr[..., 1]

    return zr[..., 0]