Python autograd.numpy.asarray() Examples

The following are 16 code examples of autograd.numpy.asarray(). 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 autograd.numpy , or try the search function .
Example #1
Source File: sfs.py    From momi2 with GNU General Public License v3.0 6 votes vote down vote up
def resample(self):
        """Create a new SFS by resampling blocks with replacement.

        Note the resampled SFS is assumed to have the same length in base pairs \
        as the original SFS, which may be a poor assumption if the blocks are not of equal length.

        :returns: Resampled SFS
        :rtype: :class:`Sfs`
        """
        loci = np.random.choice(
            np.arange(self.n_loci), size=self.n_loci, replace=True)
        mat = self.freqs_matrix[:, loci]
        to_keep = np.asarray(mat.sum(axis=1) > 0).squeeze()
        to_keep = np.arange(len(self.configs))[to_keep]
        mat = mat[to_keep, :]
        configs = _ConfigList_Subset(self.configs, to_keep)

        return self.from_matrix(mat, configs, self.folded, self.length) 
Example #2
Source File: kernel.py    From kernel-gof with MIT License 6 votes vote down vote up
def __init__(self, sigma2s, wts=None):
        """
        Mixture of isotropic Gaussian kernels:
          sum wts[i] * exp(- ||x - y||^2 / (2 * sigma2s[i]))

        sigma2s: a list/array of squared bandwidths
        wts: a list/array of weights. Defaults to equal weights summing to 1.
        """
        self.sigma2s = sigma2s = np.asarray(sigma2s)
        assert len(sigma2s) > 0

        if wts is None:
            self.wts = wts = np.full(len(sigma2s), 1/len(sigma2s))
        else:
            self.wts = wts = np.asarray(wts)
            assert len(wts) == len(sigma2s)
            assert all(w >= 0 for w in wts) 
Example #3
Source File: tm.py    From autohmm with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def _set_precision_prior(self, precision_prior):
        if precision_prior is None:
            self._precision_prior_ = \
            np.zeros((self.n_components, self.n_features, self.n_features))
        else:
            precision_prior = np.asarray(precision_prior)
            if len(precision_prior) == 1:
                self._precision_prior_ = np.tile(precision_prior,
                (self.n_components, self.n_features, self.n_features))
            elif \
            (precision_prior.reshape(self.n_unique, self.n_features, self.n_features)).shape \
            == (self.n_unique, self.n_features, self.n_features):
                self._precision_prior_ = \
                np.zeros((self.n_components, self.n_features, self.n_features))
                for u in range(self.n_unique):
                    for t in range(self.n_chain):
                        self._precision_prior_[u*(self.n_chain)+t] = precision_prior[u].copy()
            else:
                raise ValueError("cannot match shape of precision_prior") 
Example #4
Source File: tm.py    From autohmm with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def _set_startprob(self, startprob):
        if startprob is None:
            startprob = np.tile(1.0 / self.n_components, self.n_components)
        else:
            startprob = np.asarray(startprob, dtype=np.float)

            normalize(startprob)

            if len(startprob) != self.n_components:
                if len(startprob) == self.n_unique:
                    startprob_split = np.copy(startprob) / (1.0+self.n_tied)
                    startprob = np.zeros(self.n_components)
                    for u in range(self.n_unique):
                        for t in range(self.n_chain):
                            startprob[u*(self.n_chain)+t] = \
                                startprob_split[u].copy()
                else:
                    raise ValueError("cannot match shape of startprob")

        if not np.allclose(np.sum(startprob), 1.0):
            raise ValueError('startprob must sum to 1.0')

        self._log_startprob = np.log(np.asarray(startprob).copy()) 
Example #5
Source File: tm.py    From autohmm with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def _set_transmat(self, transmat_val):
        if transmat_val is None:
            transmat = np.tile(1.0 / self.n_components,
                               (self.n_components, self.n_components))
        else:
            transmat_val[np.isnan(transmat_val)] = 0.0
            normalize(transmat_val, axis=1)

            if (np.asarray(transmat_val).shape == (self.n_components,
                                                   self.n_components)):
                transmat = np.copy(transmat_val)
            elif transmat_val.shape[0] == self.n_unique:
                transmat = self._ntied_transmat(transmat_val)
            else:
                raise ValueError("cannot match shape of transmat")

        if not np.all(np.allclose(np.sum(transmat, axis=1), 1.0)):
            raise ValueError('Rows of transmat must sum to 1.0')
        self._log_transmat = np.log(np.asarray(transmat).copy())
        underflow_idx = np.isnan(self._log_transmat)
        self._log_transmat[underflow_idx] = NEGINF 
Example #6
Source File: fft.py    From scarlet with MIT License 5 votes vote down vote up
def _centered(arr, newshape):
    """Return the center newshape portion of the array.

    This function is used by `fft_convolve` to remove
    the zero padded region of the convolution.

    Note: If the array shape is odd and the target is even,
    the center of `arr` is shifted to the center-right
    pixel position.
    This is slightly different than the scipy implementation,
    which uses the center-left pixel for the array center.
    The reason for the difference is that we have
    adopted the convention of `np.fft.fftshift` in order
    to make sure that changing back and forth from
    fft standard order (0 frequency and position is
    in the bottom left) to 0 position in the center.
    """
    newshape = np.asarray(newshape)
    currshape = np.array(arr.shape)

    if not np.all(newshape <= currshape):
        msg = (
            "arr must be larger than newshape in both dimensions, received {0}, and {1}"
        )
        raise ValueError(msg.format(arr.shape, newshape))

    startind = (currshape - newshape + 1) // 2
    endind = startind + newshape
    myslice = [slice(startind[k], endind[k]) for k in range(len(endind))]

    return arr[tuple(myslice)] 
Example #7
Source File: fft.py    From scarlet with MIT License 5 votes vote down vote up
def _pad(arr, newshape, axes=None, mode="constant", constant_values=0):
    """Pad an array to fit into newshape

    Pad `arr` with zeros to fit into newshape,
    which uses the `np.fft.fftshift` convention of moving
    the center pixel of `arr` (if `arr.shape` is odd) to
    the center-right pixel in an even shaped `newshape`.
    """
    if axes is None:
        newshape = np.asarray(newshape)
        currshape = np.array(arr.shape)
        dS = newshape - currshape
        startind = (dS + 1) // 2
        endind = dS - startind
        pad_width = list(zip(startind, endind))
    else:
        # only pad the axes that will be transformed
        pad_width = [(0, 0) for axis in arr.shape]
        try:
            len(axes)
        except TypeError:
            axes = [axes]
        for a, axis in enumerate(axes):
            dS = newshape[a] - arr.shape[axis]
            startind = (dS + 1) // 2
            endind = dS - startind
            pad_width[axis] = (startind, endind)
    if mode == "constant" and constant_values == 0:
        result = fast_zero_pad(arr, pad_width)
    else:
        result = np.pad(arr, pad_width, mode=mode)
    return result 
Example #8
Source File: parameter.py    From scarlet with MIT License 5 votes vote down vote up
def __new__(
        cls,
        array,
        name="unnamed",
        prior=None,
        constraint=None,
        step=0,
        std=None,
        m=None,
        v=None,
        vhat=None,
        fixed=False,
    ):
        obj = np.asarray(array, dtype=array.dtype).view(cls)
        obj.name = name
        if prior is not None:
            assert isinstance(prior, Prior)
        obj.prior = prior
        if constraint is not None:
            assert isinstance(constraint, Constraint) or isinstance(
                constraint, ConstraintChain
            )
        obj.constraint = constraint
        obj.step = step
        obj.std = std
        obj.m = m
        obj.v = v
        obj.vhat = vhat
        obj.fixed = fixed
        return obj 
Example #9
Source File: model.py    From tree-regularization-public with MIT License 5 votes vote down vote up
def make_grad_softplus(ans, x):
    x = np.asarray(x)
    def gradient_product(g):
        return np.full(x.shape, g) * np.exp(x - ans)
    return gradient_product 
Example #10
Source File: rnn.py    From autograd with MIT License 5 votes vote down vote up
def print_training_prediction(weights):
        print("Training text                         Predicted text")
        logprobs = np.asarray(rnn_predict(weights, train_inputs))
        for t in range(logprobs.shape[1]):
            training_text  = one_hot_to_string(train_inputs[:,t,:])
            predicted_text = one_hot_to_string(logprobs[:,t,:])
            print(training_text.replace('\n', ' ') + "|" +
                  predicted_text.replace('\n', ' ')) 
Example #11
Source File: lstm.py    From autograd with MIT License 5 votes vote down vote up
def print_training_prediction(weights):
        print("Training text                         Predicted text")
        logprobs = np.asarray(lstm_predict(weights, train_inputs))
        for t in range(logprobs.shape[1]):
            training_text  = one_hot_to_string(train_inputs[:,t,:])
            predicted_text = one_hot_to_string(logprobs[:,t,:])
            print(training_text.replace('\n', ' ') + "|" +
                  predicted_text.replace('\n', ' ')) 
Example #12
Source File: kernel.py    From kernel-gof with MIT License 5 votes vote down vote up
def __init__(self, ks, wts=None):
        self.ks = ks
        if wts is None:
            self.wts = np.full(len(ks), 1/len(ks))
        else:
            self.wts = np.asarray(wts) 
Example #13
Source File: student.py    From autohmm with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def multivariate_t_rvs(self, m, S, random_state = None):
            '''generate random variables of multivariate t distribution
            Parameters
            ----------
            m : array_like
                mean of random variable, length determines dimension of random variable
            S : array_like
                square array of covariance  matrix
            df : int or float
                degrees of freedom
            n : int
                number of observations, return random array will be (n, len(m))
            random_state : int
                           seed
            Returns
            -------
            rvs : ndarray, (n, len(m))
                each row is an independent draw of a multivariate t distributed
                random variable
            '''
            np.random.rand(9)
            m = np.asarray(m)
            d = self.n_features
            df = self.degree_freedom
            n = 1
            if df == np.inf:
                x = 1.
            else:
                x = random_state.chisquare(df, n)/df
            np.random.rand(90)

            z = random_state.multivariate_normal(np.zeros(d),S,(n,))
            return m + z/np.sqrt(x)[:,None]
            # same output format as random.multivariate_normal 
Example #14
Source File: tm.py    From autohmm with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _set_mu_prior(self, mu_prior):
        if mu_prior is None:
            self._mu_prior_ = np.zeros((self.n_components, self.n_features))
        else:
            mu_prior = np.asarray(mu_prior)
            mu_prior = mu_prior.reshape(self.n_unique, self.n_features)
            if mu_prior.shape == (self.n_unique, self.n_features):
                for u in range(self.n_unique):
                    for t in range(self.n_chain):
                        self._mu_prior[u*(self.n_chain)+t] = mu_prior[u].copy()

            else:
                raise ValueError("cannot match shape of mu_prior") 
Example #15
Source File: tm.py    From autohmm with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _set_var_prior(self, var_prior):
        var_prior = np.asarray(var_prior)
        if self.n_features == 1:
            self._set_precision_prior(1.0 / var_prior)
        else:
            self._set_precision_prior(np.linalg.inv(var_prior)) 
Example #16
Source File: fft.py    From scarlet with MIT License 4 votes vote down vote up
def _get_fft_shape(im_or_shape1, im_or_shape2, padding=3, axes=None, max=False):
    """Return the fast fft shapes for each spatial axis

    Calculate the fast fft shape for each dimension in
    axes.
    """
    if hasattr(im_or_shape1, "shape"):
        shape1 = np.asarray(im_or_shape1.shape)
    else:
        shape1 = np.asarray(im_or_shape1)
    if hasattr(im_or_shape2, "shape"):
        shape2 = np.asarray(im_or_shape2.shape)
    else:
        shape2 = np.asarray(im_or_shape2)
    # Make sure the shapes are the same size
    if len(shape1) != len(shape2):
        msg = (
            "img1 and img2 must have the same number of dimensions, but got {0} and {1}"
        )
        raise ValueError(msg.format(len(shape1), len(shape2)))
    # Set the combined shape based on the total dimensions
    if axes is None:
        if max:
            shape = np.max([shape1, shape2], axis=1)
        else:
            shape = shape1 + shape2
    else:
        shape = np.zeros(len(axes), dtype='int')
        try:
            len(axes)
        except TypeError:
            axes = [axes]
        for n, ax in enumerate(axes):
            shape[n] = shape1[ax] + shape2[ax]
            if max == True:
                shape[n] = np.max([shape1[ax], shape2[ax]])

    shape += padding
    # Use the next fastest shape in each dimension
    shape = [fftpack.helper.next_fast_len(s) for s in shape]
    # autograd.numpy.fft does not currently work
    # if the last dimension is odd
    while shape[-1] % 2 != 0:
        shape[-1] += 1
        shape[-1] = fftpack.helper.next_fast_len(shape[-1])
    if shape2[-2] % 2 == 0:
        while shape[-2] % 2 != 0:
            shape[-2] += 1
            shape[-2] = fftpack.helper.next_fast_len(shape[-2])

    return shape