Python scipy.ndarray() Examples

The following are 13 code examples of scipy.ndarray(). 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 scipy , or try the search function .
Example #1
Source File: linear.py    From Stone-Soup with MIT License 6 votes vote down vote up
def matrix(self, time_interval, **kwargs):
        """Model matrix :math:`F`

        Returns
        -------
        : :class:`numpy.ndarray` of shape\
        (:py:attr:`~ndim_state`, :py:attr:`~ndim_state`)
        """
        time_interval_sec = time_interval.total_seconds()
        turn_ratedt = self.turn_rate * time_interval_sec
        z = np.zeros([2, 2])
        transition_matrices = [
            model.matrix(time_interval) for model in self.model_list]
        sandwich = block_diag(z, *transition_matrices, z)
        sandwich[0:2, 0:2] = np.array([[1, np.sin(turn_ratedt)/self.turn_rate],
                                      [0, np.cos(turn_ratedt)]])
        sandwich[0:2, -2:] = np.array(
            [[0, (np.cos(turn_ratedt)-1)/self.turn_rate],
             [0, -np.sin(turn_ratedt)]])
        sandwich[-2:, 0:2] = np.array(
            [[0, (1-np.cos(turn_ratedt))/self.turn_rate],
             [0, np.sin(turn_ratedt)]])
        sandwich[-2:, -2:] = np.array([[1, np.sin(turn_ratedt)/self.turn_rate],
                                       [0, np.cos(turn_ratedt)]])
        return sandwich 
Example #2
Source File: histogram.py    From brats_segmentation-pytorch with MIT License 5 votes vote down vote up
def __kullback_leibler(h1, h2): # 36.3 us
    """
    The actual KL implementation. @see kullback_leibler() for details.
    Expects the histograms to be of type scipy.ndarray.
    """
    result = h1.astype(scipy.float_)
    mask = h1 != 0
    result[mask] = scipy.multiply(h1[mask], scipy.log(h1[mask] / h2[mask]))
    return scipy.sum(result) 
Example #3
Source File: histogram.py    From brats_segmentation-pytorch with MIT License 5 votes vote down vote up
def __prepare_histogram(h1, h2):
    """Convert the histograms to scipy.ndarrays if required."""
    h1 = h1 if scipy.ndarray == type(h1) else scipy.asarray(h1)
    h2 = h2 if scipy.ndarray == type(h2) else scipy.asarray(h2)
    if h1.shape != h2.shape or h1.size != h2.size:
        raise ValueError('h1 and h2 must be of same shape and size')
    return h1, h2 
Example #4
Source File: operations.py    From py-image-dataset-generator with MIT License 5 votes vote down vote up
def execute(self, image_array: ndarray):
        pass 
Example #5
Source File: operations.py    From py-image-dataset-generator with MIT License 5 votes vote down vote up
def execute(self, image_array: ndarray):
        random_degree = random.uniform(-self.max_right_degree, self.max_left_degree)
        return rotate(image_array, random_degree) 
Example #6
Source File: operations.py    From py-image-dataset-generator with MIT License 5 votes vote down vote up
def execute(self, image_array: ndarray):
        return random_noise(image_array) 
Example #7
Source File: operations.py    From py-image-dataset-generator with MIT License 5 votes vote down vote up
def execute(self, image_array: ndarray):
        return ndimage.uniform_filter(image_array, size=(11, 11, 1)) 
Example #8
Source File: operations.py    From py-image-dataset-generator with MIT License 5 votes vote down vote up
def execute(self, image_array: ndarray):
        return resize(image_array, (self.width, self.height)) 
Example #9
Source File: operations.py    From py-image-dataset-generator with MIT License 5 votes vote down vote up
def execute(self, image_array: ndarray):
        return image_array[::-1, :] 
Example #10
Source File: linear.py    From Stone-Soup with MIT License 5 votes vote down vote up
def matrix(self, **kwargs):
        """Model matrix :math:`F`

        Returns
        -------
        : :class:`numpy.ndarray` of shape\
        (:py:attr:`~ndim_state`, :py:attr:`~ndim_state`)
        """

        transition_matrices = [
            model.matrix(**kwargs) for model in self.model_list]
        return block_diag(*transition_matrices) 
Example #11
Source File: linear.py    From Stone-Soup with MIT License 5 votes vote down vote up
def matrix(self, **kwargs):
        """Model matrix :math:`F`

        Returns
        -------
        : :class:`numpy.ndarray` of shape\
        (:py:attr:`~ndim_state`, :py:attr:`~ndim_state`)
            The model matrix evaluated given the provided time interval.
        """

        return self.transition_matrix 
Example #12
Source File: liblinear.py    From AVEC2018 with MIT License 4 votes vote down vote up
def gen_feature_nodearray(xi, feature_max=None):
	if feature_max:
		assert(isinstance(feature_max, int))

	xi_shift = 0 # ensure correct indices of xi
	if scipy and isinstance(xi, tuple) and len(xi) == 2\
			and isinstance(xi[0], scipy.ndarray) and isinstance(xi[1], scipy.ndarray): # for a sparse vector
		index_range = xi[0] + 1 # index starts from 1
		if feature_max:
			index_range = index_range[scipy.where(index_range <= feature_max)]
	elif scipy and isinstance(xi, scipy.ndarray):
		xi_shift = 1
		index_range = xi.nonzero()[0] + 1 # index starts from 1
		if feature_max:
			index_range = index_range[scipy.where(index_range <= feature_max)]
	elif isinstance(xi, (dict, list, tuple)):
		if isinstance(xi, dict):
			index_range = xi.keys()
		elif isinstance(xi, (list, tuple)):
			xi_shift = 1
			index_range = range(1, len(xi) + 1)
		index_range = filter(lambda j: xi[j-xi_shift] != 0, index_range)

		if feature_max:
			index_range = filter(lambda j: j <= feature_max, index_range)
		index_range = sorted(index_range)
	else:
		raise TypeError('xi should be a dictionary, list, tuple, 1-d numpy array, or tuple of (index, data)')

	ret = (feature_node*(len(index_range)+2))()
	ret[-1].index = -1 # for bias term
	ret[-2].index = -1

	if scipy and isinstance(xi, tuple) and len(xi) == 2\
			and isinstance(xi[0], scipy.ndarray) and isinstance(xi[1], scipy.ndarray): # for a sparse vector
		for idx, j in enumerate(index_range):
			ret[idx].index = j
			ret[idx].value = (xi[1])[idx]
	else:
		for idx, j in enumerate(index_range):
			ret[idx].index = j
			ret[idx].value = xi[j - xi_shift]

	max_idx = 0
	if len(index_range) > 0:
		max_idx = index_range[-1]
	return ret, max_idx 
Example #13
Source File: liblinear.py    From AVEC2018 with MIT License 4 votes vote down vote up
def __init__(self, y, x, bias = -1):
		if (not isinstance(y, (list, tuple))) and (not (scipy and isinstance(y, scipy.ndarray))):
			raise TypeError("type of y: {0} is not supported!".format(type(y)))

		if isinstance(x, (list, tuple)):
			if len(y) != len(x):
				raise ValueError("len(y) != len(x)")
		elif scipy != None and isinstance(x, (scipy.ndarray, sparse.spmatrix)):
			if len(y) != x.shape[0]:
				raise ValueError("len(y) != len(x)")
			if isinstance(x, scipy.ndarray):
				x = scipy.ascontiguousarray(x) # enforce row-major
			if isinstance(x, sparse.spmatrix):
				x = x.tocsr()
				pass
		else:
			raise TypeError("type of x: {0} is not supported!".format(type(x)))
		self.l = l = len(y)
		self.bias = -1

		max_idx = 0
		x_space = self.x_space = []
		if scipy != None and isinstance(x, sparse.csr_matrix):
			csr_to_problem(x, self)
			max_idx = x.shape[1]
		else:
			for i, xi in enumerate(x):
				tmp_xi, tmp_idx = gen_feature_nodearray(xi)
				x_space += [tmp_xi]
				max_idx = max(max_idx, tmp_idx)
		self.n = max_idx

		self.y = (c_double * l)()
		if scipy != None and isinstance(y, scipy.ndarray):
			scipy.ctypeslib.as_array(self.y, (self.l,))[:] = y
		else:
			for i, yi in enumerate(y): self.y[i] = yi

		self.x = (POINTER(feature_node) * l)()
		if scipy != None and isinstance(x, sparse.csr_matrix):
			base = addressof(self.x_space.ctypes.data_as(POINTER(feature_node))[0])
			x_ptr = cast(self.x, POINTER(c_uint64))
			x_ptr = scipy.ctypeslib.as_array(x_ptr,(self.l,))
			x_ptr[:] = self.rowptr[:-1]*sizeof(feature_node)+base
		else:
			for i, xi in enumerate(self.x_space): self.x[i] = xi

		self.set_bias(bias)