python类divide()的实例源码

deformable_registration.py 文件源码 项目:pycpd 作者: siavashk 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def EStep(self):
    P = np.zeros((self.M, self.N))

    for i in range(0, self.M):
      diff     = self.X - np.tile(self.TY[i, :], (self.N, 1))
      diff    = np.multiply(diff, diff)
      P[i, :] = P[i, :] + np.sum(diff, axis=1)

    c = (2 * np.pi * self.sigma2) ** (self.D / 2)
    c = c * self.w / (1 - self.w)
    c = c * self.M / self.N

    P = np.exp(-P / (2 * self.sigma2))
    den = np.sum(P, axis=0)
    den = np.tile(den, (self.M, 1))
    den[den==0] = np.finfo(float).eps

    self.P   = np.divide(P, den)
    self.Pt1 = np.sum(self.P, axis=0)
    self.P1  = np.sum(self.P, axis=1)
    self.Np  = np.sum(self.P1)
Routines.py 文件源码 项目:structured-output-ae 作者: sbelharbi 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def reproject_one_shape( self, shape, bbox, window, nfids):
            '''Re-project a shape to the original plan.

            '''

            shape_re = shape
            std_w, std_h = window
            x = bbox[0]
            y = bbox[1]
            w = bbox[2]
            h = bbox[3]
            center_x = x + np.divide(w, 2)
            center_y = y + np.divide(h, 2)

            X = shape[0:nfids]
            Y = shape[nfids:]    
            # reprojecting ...
            X = X * (std_w / 2.) + center_x
            Y = Y * (std_h / 2.) + center_y
            shape_re = np.concatenate((X,Y))

            return shape_re
image_utils.py 文件源码 项目:acdc_segmenter 作者: baumgach 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def normalise_images(X):
    '''
    Helper for making the images zero mean and unit standard deviation i.e. `white`
    '''

    X_white = np.zeros(X.shape, dtype=np.float32)

    for ii in range(X.shape[0]):

        Xc = X[ii,:,:,:]
        mc = Xc.mean()
        sc = Xc.std()

        Xc_white = np.divide((Xc - mc), sc)

        X_white[ii,:,:,:] = Xc_white

    return X_white.astype(np.float32)
masking_methods.py 文件源码 项目:mss_pytorch 作者: Js-Mim 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def IAM(self):
        """
            Computation of Ideal Amplitude Mask. As appears in :
            H. Erdogan, J. R. Hershey, S. Watanabe, and J. Le Roux,
            "Phase-sensitive and recognition-boosted speech separation using deep recurrent neural networks,"
            in ICASSP 2015, Brisbane, April, 2015.
        Args:
            sTarget:   (2D ndarray) Magnitude Spectrogram of the target component
            nResidual: (2D ndarray) Magnitude Spectrogram of the residual component
                                    (In this case the observed mixture should be placed)
        Returns:
            mask:      (2D ndarray) Array that contains time frequency gain values

        """
        print('Ideal Amplitude Mask')
        self._mask = np.divide(self._sTarget, (self._eps + self._nResidual))
masking_methods.py 文件源码 项目:mss_pytorch 作者: Js-Mim 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def ExpM(self):
        """
            Approximate a signal via element-wise exponentiation. As appears in :
            S.I. Mimilakis, K. Drossos, T. Virtanen, and G. Schuller,
            "Deep Neural Networks for Dynamic Range Compression in Mastering Applications,"
            in proc. of the 140th Audio Engineering Society Convention, Paris, 2016.
        Args:
            sTarget:   (2D ndarray) Magnitude Spectrogram of the target component
            nResidual: (2D ndarray) Magnitude Spectrogram of the residual component
        Returns:
            mask:      (2D ndarray) Array that contains time frequency gain values

        """
        print('Exponential mask')
        self._mask = np.divide(np.log(self._sTarget.clip(self._eps, np.inf)**self._alpha),\
                               np.log(self._nResidual.clip(self._eps, np.inf)**self._alpha))
masking_methods.py 文件源码 项目:mss_pytorch 作者: Js-Mim 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def IBM(self):
        """
            Computation of Ideal Binary Mask.
        Args:
            sTarget:   (2D ndarray) Magnitude Spectrogram of the target component
            nResidual: (2D ndarray) Magnitude Spectrogram of the residual component
        Returns:
            mask:      (2D ndarray) Array that contains time frequency gain values

        """
        print('Ideal Binary Mask')
        theta = 0.5
        mask = np.divide(self._sTarget ** self._alpha, (self._eps + self._nResidual ** self._alpha))
        bg = np.where(mask >= theta)
        sm = np.where(mask < theta)
        mask[bg[0],bg[1]] = 1.
        mask[sm[0], sm[1]] = 0.
        self._mask = mask
masking_methods.py 文件源码 项目:mss_pytorch 作者: Js-Mim 项目源码 文件源码 阅读 36 收藏 0 点赞 0 评论 0
def UBBM(self):
        """
            Computation of Upper Bound Binary Mask. As appears in :
            - J.J. Burred, "From Sparse Models to Timbre Learning: New Methods for Musical Source Separation", PhD Thesis,
            TU Berlin, 2009.

        Args:
            sTarget:   (2D ndarray) Magnitude Spectrogram of the target component
            nResidual: (2D ndarray) Magnitude Spectrogram of the residual component (Should not contain target source!)
        Returns:
            mask:      (2D ndarray) Array that contains time frequency gain values
        """
        print('Upper Bound Binary Mask')
        mask = 20. * np.log(self._eps + np.divide((self._eps + (self._sTarget ** self._alpha)),
                                      ((self._eps + (self._nResidual ** self._alpha)))))
        bg = np.where(mask >= 0)
        sm = np.where(mask < 0)
        mask[bg[0],bg[1]] = 1.
        mask[sm[0], sm[1]] = 0.
        self._mask = mask
masking_methods.py 文件源码 项目:mss_pytorch 作者: Js-Mim 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def alphaHarmonizableProcess(self):
        """
            Computation of Wiener like mask using fractional power spectrograms. As appears in :
            A. Liutkus, R. Badeau, "Generalized Wiener filtering with fractional power spectrograms",
            40th International Conference on Acoustics, Speech and Signal Processing (ICASSP),
            Apr 2015, Brisbane, Australia.
        Args:
            sTarget:   (2D ndarray) Magnitude Spectrogram of the target component
            nResidual: (2D ndarray) Magnitude Spectrogram of the residual component or a list 
                                    of 2D ndarrays which will be added together
        Returns:
            mask:      (2D ndarray) Array that contains time frequency gain values

        """
        print('Harmonizable Process with alpha:', str(self._alpha))
        localsTarget = self._sTarget ** self._alpha
        numElements = len(self._nResidual)
        if numElements > 1:
            localnResidual = self._nResidual[0] ** self._alpha + localsTarget
            for indx in range(1, numElements):
                localnResidual += self._nResidual[indx] ** self._alpha
        else :
            localnResidual = self._nResidual[0] ** self._alpha + localsTarget

        self._mask = np.divide((localsTarget + self._eps), (self._eps + localnResidual))
masking_methods.py 文件源码 项目:mss_pytorch 作者: Js-Mim 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def phaseSensitive(self):
        """
            Computation of Phase Sensitive Mask. As appears in :
            H Erdogan, John R. Hershey, Shinji Watanabe, and Jonathan Le Roux,
            "Phase-sensitive and recognition-boosted speech separation using deep recurrent neural networks,"
            in ICASSP 2015, Brisbane, April, 2015.

        Args:
            mTarget:   (2D ndarray) Magnitude Spectrogram of the target component
            pTarget:   (2D ndarray) Phase Spectrogram of the output component
            mY:        (2D ndarray) Magnitude Spectrogram of the residual component
            pY:        (2D ndarray) Phase Spectrogram of the residual component
        Returns:
            mask:      (2D ndarray) Array that contains time frequency gain values

        """
        print('Phase Sensitive Masking.')
        # Compute Phase Difference
        Theta = (self._pTarget - self._pY)
        self._mask = 2./ (1. + np.exp(-np.multiply(np.divide(self._sTarget, self._eps + self._nResidual), np.cos(Theta)))) - 1.
data.py 文件源码 项目:melanoma-transfer 作者: learningtitans 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def load_augment(fname, w, h, aug_params=no_augmentation_params,
                 transform=None, sigma=0.0, color_vec=None):
    """Load augmented image with output shape (w, h).

    Default arguments return non augmented image of shape (w, h).
    To apply a fixed transform (color augmentation) specify transform
    (color_vec).
    To generate a random augmentation specify aug_params and sigma.
    """
    img = load_image(fname)
    img = perturb(img, augmentation_params=aug_params, target_shape=(w, h))
    #if transform is None:
    #    img = perturb(img, augmentation_params=aug_params, target_shape=(w, h))
    #else:
    #    img = perturb_fixed(img, tform_augment=transform, target_shape=(w, h))

    #randString = str(np.random.normal(0,1,1))
    #im = Image.fromarray(img.transpose(1,2,0).astype('uint8'))
    #figName = fname.split("/")[-1]
    #im.save("imgs/"+figName+randString+".jpg")

    np.subtract(img, MEAN[:, np.newaxis, np.newaxis], out=img)
    #np.divide(img, STD[:, np.newaxis, np.newaxis], out=img)
    #img = augment_color(img, sigma=sigma, color_vec=color_vec)
    return img
test_core.py 文件源码 项目:radar 作者: amoose136 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def setUp(self):
        # Base data definition.
        x = np.array([1., 1., 1., -2., pi/2.0, 4., 5., -10., 10., 1., 2., 3.])
        y = np.array([5., 0., 3., 2., -1., -4., 0., -10., 10., 1., 0., 3.])
        a10 = 10.
        m1 = [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0]
        m2 = [0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1]
        xm = masked_array(x, mask=m1)
        ym = masked_array(y, mask=m2)
        z = np.array([-.5, 0., .5, .8])
        zm = masked_array(z, mask=[0, 1, 0, 0])
        xf = np.where(m1, 1e+20, x)
        xm.set_fill_value(1e+20)
        self.d = (x, y, a10, m1, m2, xm, ym, z, zm, xf)
        self.err_status = np.geterr()
        np.seterr(divide='ignore', invalid='ignore')
core.py 文件源码 项目:radar 作者: amoose136 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def __ifloordiv__(self, other):
        """
        Floor divide self by other in-place.

        """
        other_data = getdata(other)
        dom_mask = _DomainSafeDivide().__call__(self._data, other_data)
        other_mask = getmask(other)
        new_mask = mask_or(other_mask, dom_mask)
        # The following 3 lines control the domain filling
        if dom_mask.any():
            (_, fval) = ufunc_fills[np.floor_divide]
            other_data = np.where(dom_mask, fval, other_data)
        self._mask |= new_mask
        self._data.__ifloordiv__(np.where(self._mask, self.dtype.type(1),
                                          other_data))
        return self
core.py 文件源码 项目:radar 作者: amoose136 项目源码 文件源码 阅读 38 收藏 0 点赞 0 评论 0
def __itruediv__(self, other):
        """
        True divide self by other in-place.

        """
        other_data = getdata(other)
        dom_mask = _DomainSafeDivide().__call__(self._data, other_data)
        other_mask = getmask(other)
        new_mask = mask_or(other_mask, dom_mask)
        # The following 3 lines control the domain filling
        if dom_mask.any():
            (_, fval) = ufunc_fills[np.true_divide]
            other_data = np.where(dom_mask, fval, other_data)
        self._mask |= new_mask
        self._data.__itruediv__(np.where(self._mask, self.dtype.type(1),
                                         other_data))
        return self
core.py 文件源码 项目:radar 作者: amoose136 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
def __ipow__(self, other):
        """
        Raise self to the power other, in place.

        """
        other_data = getdata(other)
        other_mask = getmask(other)
        with np.errstate(divide='ignore', invalid='ignore'):
            self._data.__ipow__(np.where(self._mask, self.dtype.type(1),
                                         other_data))
        invalid = np.logical_not(np.isfinite(self._data))
        if invalid.any():
            if self._mask is not nomask:
                self._mask |= invalid
            else:
                self._mask = invalid
            np.copyto(self._data, self.fill_value, where=invalid)
        new_mask = mask_or(other_mask, invalid)
        self._mask = mask_or(self._mask, new_mask)
        return self
gromov.py 文件源码 项目:POT 作者: rflamary 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def update_kl_loss(p, lambdas, T, Cs):
    """
    Updates C according to the KL Loss kernel with the S Ts couplings calculated at each iteration


    Parameters
    ----------
    p  : ndarray, shape (N,)
         weights in the targeted barycenter
    lambdas : list of the S spaces' weights
    T : list of S np.ndarray(ns,N)
        the S Ts couplings calculated at each iteration
    Cs : list of S ndarray, shape(ns,ns)
         Metric cost matrices

    Returns
    ----------
    C : ndarray, shape (ns,ns)
        updated C matrix
    """
    tmpsum = sum([lambdas[s] * np.dot(T[s].T, Cs[s]).dot(T[s])
                  for s in range(len(T))])
    ppt = np.outer(p, p)

    return np.exp(np.divide(tmpsum, ppt))
MaskingMethods.py 文件源码 项目:aes_wimp 作者: Js-Mim 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def IBM(self):
        """
            Computation of Ideal Binary Mask.
        Args:
            sTarget:   (2D ndarray) Magnitude Spectrogram of the target component
            nResidual: (2D ndarray) Magnitude Spectrogram of the residual component
        Returns:
            mask:      (2D ndarray) Array that contains time frequency gain values

        """
        print('Ideal Binary Mask')
        theta = 0.5
        mask = np.divide(self._sTarget ** self._alpha, (self._eps + self._nResidual ** self._alpha))
        bg = np.where(mask >= theta)
        sm = np.where(mask < theta)
        mask[bg[0],bg[1]] = 1.
        mask[sm[0], sm[1]] = 0.
        self._mask = mask
MaskingMethods.py 文件源码 项目:aes_wimp 作者: Js-Mim 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def UBBM(self):
        """
            Computation of Upper Bound Binary Mask. As appears in :
            - J.J. Burred, "From Sparse Models to Timbre Learning: New Methods for Musical Source Separation", PhD Thesis,
            TU Berlin, 2009.

        Args:
            sTarget:   (2D ndarray) Magnitude Spectrogram of the target component
            nResidual: (2D ndarray) Magnitude Spectrogram of the residual component (Should not contain target source!)
        Returns:
            mask:      (2D ndarray) Array that contains time frequency gain values
        """
        print('Upper Bound Binary Mask')
        mask = 20. * np.log(self._eps + np.divide((self._eps + (self._sTarget ** self._alpha)),
                                      ((self._eps + (self._nResidual ** self._alpha)))))
        bg = np.where(mask >= 0)
        sm = np.where(mask < 0)
        mask[bg[0],bg[1]] = 1.
        mask[sm[0], sm[1]] = 0.
        self._mask = mask
MaskingMethods.py 文件源码 项目:aes_wimp 作者: Js-Mim 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def Wiener(self):
        """
            Computation of Wiener-like Mask. As appears in :
            H Erdogan, John R. Hershey, Shinji Watanabe, and Jonathan Le Roux,
            "Phase-sensitive and recognition-boosted speech separation using deep recurrent neural networks,"
            in ICASSP 2015, Brisbane, April, 2015.
        Args:
                sTarget:   (2D ndarray) Magnitude Spectrogram of the target component
                nResidual: (2D ndarray) Magnitude Spectrogram of the residual component
        Returns:
                mask:      (2D ndarray) Array that contains time frequency gain values
        """
        print('Wiener-like Mask')
        localsTarget = self._sTarget ** 2.
        numElements = len(self._nResidual)
        if numElements > 1:
            localnResidual = self._nResidual[0] ** 2. + localsTarget
            for indx in range(1, numElements):
                localnResidual += self._nResidual[indx] ** 2.
        else :
            localnResidual = self._nResidual[0] ** 2. + localsTarget

        self._mask = np.divide((localsTarget + self._eps), (self._eps + localnResidual))
MaskingMethods.py 文件源码 项目:aes_wimp 作者: Js-Mim 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def alphaHarmonizableProcess(self):
        """
            Computation of alpha harmonizable Wiener like mask, as appears in :
            A. Liutkus, R. Badeau, "Generalized Wiener filtering with fractional power spectrograms",
            40th International Conference on Acoustics, Speech and Signal Processing (ICASSP),
            Apr 2015, Brisbane, Australia.
        Args:
            sTarget:   (2D ndarray) Magnitude Spectrogram of the target component
            nResidual: (2D ndarray) Magnitude Spectrogram of the residual component or a list 
                                    of 2D ndarrays which will be summed
        Returns:
            mask:      (2D ndarray) Array that contains time frequency gain values

        """
        print('Harmonizable Process with alpha:', str(self._alpha))
        localsTarget = self._sTarget ** self._alpha
        numElements = len(self._nResidual)
        if numElements > 1:
            localnResidual = self._nResidual[0] ** self._alpha + localsTarget
            for indx in range(1, numElements):
                localnResidual += self._nResidual[indx] ** self._alpha
        else :
            localnResidual = self._nResidual[0] ** self._alpha + localsTarget

        self._mask = np.divide((localsTarget + self._eps), (self._eps + localnResidual))
imresize.py 文件源码 项目:matlab_imresize 作者: fatheral 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def contributions(in_length, out_length, scale, kernel, k_width):
    if scale < 1:
        h = lambda x: scale * kernel(scale * x)
        kernel_width = 1.0 * k_width / scale
    else:
        h = kernel
        kernel_width = k_width
    x = np.arange(1, out_length+1).astype(np.float64)
    u = x / scale + 0.5 * (1 - 1 / scale)
    left = np.floor(u - kernel_width / 2)
    P = int(ceil(kernel_width)) + 2
    ind = np.expand_dims(left, axis=1) + np.arange(P) - 1 # -1 because indexing from 0
    indices = ind.astype(np.int32)
    weights = h(np.expand_dims(u, axis=1) - indices - 1) # -1 because indexing from 0
    weights = np.divide(weights, np.expand_dims(np.sum(weights, axis=1), axis=1))
    aux = np.concatenate((np.arange(in_length), np.arange(in_length - 1, -1, step=-1))).astype(np.int32)
    indices = aux[np.mod(indices, aux.size)]
    ind2store = np.nonzero(np.any(weights, axis=0))
    weights = weights[:, ind2store]
    indices = indices[:, ind2store]
    return weights, indices
core.py 文件源码 项目:LocalizationTDOA 作者: kn1m 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def generate_signals(self):
        for i in range(self.Trials):
            x = self.True_position[i, 0]
            y = self.True_position[i, 1]
            z = self.True_position[i, 2]

            mic_data = [numpy.vstack((numpy.zeros((int(round(self.Padding[i, j])), 1)), self.wave)) for j in range(self.N)]
            lenvec = numpy.array([len(mic) for mic in mic_data])
            m = max(lenvec)
            c = numpy.array([m - mic_len for mic_len in lenvec])
            mic_data = [numpy.vstack((current_mic, numpy.zeros((c[idx], 1)))) for idx, current_mic in enumerate(mic_data)]
            mic_data = [numpy.divide(current_mic, self.Distances[i, idx]) for idx, current_mic in enumerate(mic_data)]
            multitrack = numpy.array(mic_data)

            print 'prepared all data.'

            x, y, z = self.locate(self.Sen_position, multitrack)

            self.Est_position[i, 0] = x
            self.Est_position[i, 1] = y
            self.Est_position[i, 2] = z
pacmeth.py 文件源码 项目:brainpipe 作者: EtienneCmb 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def _kl_hr(pha, amp, nbins):
    nPha, npts, nAmp = *pha.shape, amp.shape[0]
    step = 2*np.pi/nbins
    vecbin = binarize(-np.pi, np.pi+step, step, step)
    if len(vecbin) > nbins:
        vecbin = vecbin[0:-1]

    abin = np.zeros((nAmp, nPha, nbins))
    for k, i in enumerate(vecbin):
        # Find where phase take vecbin values :
        pL, pC = np.where((pha >= i[0]) & (pha < i[1]))

        # Matrix to do amp x binMat :
        binMat = np.zeros((npts, nPha))
        binMat[pC, pL] = 1
        meanMat = np.matlib.repmat(binMat.sum(axis=0), nAmp, 1)
        meanMat[meanMat == 0] = 1

        # Multiply matrix :
        abin[:, :, k] = np.divide(np.dot(amp, binMat), meanMat)
    abinsum = np.array([abin.sum(axis=2) for k in range(nbins)])

    return abin, abinsum
scoring.py 文件源码 项目:bot2017Fin 作者: AllanYiin 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def scoring(predictions_list,answer_list):
    """
    ??????
    ?????????????????????????????????????????????????????????????????
        (1) ???????????????????????????????????????????????????????????????(????????????????????)
        (2) ?????????(??????)?????????????????????????????????????????????
        (3) ?????????(??????)????????????????????????????????????????????
        (4) ????????(?????)?????????????????????????????????????????????????
        (5) ?[???????(2)    ]-[????????(3)]-[??????(4)]??????????
        (6) ????????????????????????????????????
    :param predictions_list:
    :param answer_list:
    :return:
    """
    pred,answer,missing=generate_scoring_array(predictions_list,answer_list)
    # print(pred)
    # print(answer)
    margin1=expect_margin(pred,answer) #???????????
    margin2= expect_margin(answer, answer) #???????????
    price_hit = price_trend_hit(pred, answer)  # ???????????

    margin_rate=np.divide(margin1,margin2)
    score=np.sum(margin_rate)
    return score ,margin_rate, price_hit,missing
competitors.py 文件源码 项目:AND4NMF 作者: PrincetonML 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def train(self):
        eps = 1e-10
        for i in range(self.epo):
            if i % 1 == 0:
                self.show_error()

            A = np.asarray(self.A.copy())
            Z = np.asarray(self.Z.copy())
            start = time.time()
            Z1 = np.multiply(Z, np.asarray(self.A.transpose() * self.Y))
            Z = np.divide(Z1, eps + np.asarray(self.A.transpose() * self.A * self.Z)) # + eps to avoid divided by 0
            self.Z = np.asmatrix(Z)
            A1 = np.multiply(A, np.asarray( self.Y * self.Z.transpose()))
            A = np.divide(A1, eps + np.asarray( self.A * self.Z * self.Z.transpose()))
            end = time.time()
            self.A = np.asmatrix(A)
            self.time = self.time + end - start
utils.py 文件源码 项目:housebot 作者: jbkopecky 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def make_xy_data(csv, drop_nan_columns=None):
    data = pd.read_csv(csv, index_col=0)
    n = len(data)

    if drop_nan_columns:
        data = data.dropna(subset=drop_nan_columns)

    print "[Warning] dropped %s samples because of NaN values" % (n-len(data))

    y = np.divide(data[['prix']].astype(float).values.T,
                  data[['surface_m2']].astype(float).values.T
                  )[0]

    x = data.drop(['prix'], axis=1)

    return x, y
get_centroid.py 文件源码 项目:BioIR 作者: nlpaueb 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def get_centroid_idf(text, emb, idf, stopwords, D):
    # Computing Terms' Frequency
    tf = defaultdict(int)
    tokens = bioclean(text)
    for word in tokens:
        if word in emb and word not in stopwords:
            tf[word] += 1

    # Computing the centroid
    centroid = np.zeros((1, D))
    div = 0

    for word in tf:
        if word in idf:
            p = tf[word] * idf[word]
            centroid = np.add(centroid, emb[word]*p)
            div += p
    if div != 0:
        centroid = np.divide(centroid, div)
    return centroid
img_augmentation.py 文件源码 项目:lasagne_CNN_framework 作者: woshialex 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def load_augment(fname, w, h, aug_params=no_augmentation_params,
                 transform=None, sigma=0.0, color_vec=None):
    """Load augmented image with output shape (w, h).

    Default arguments return non augmented image of shape (w, h).
    To apply a fixed transform (color augmentation) specify transform
    (color_vec). 
    To generate a random augmentation specify aug_params and sigma.
    """
    img = load_image(fname)
    if transform is None:
        img = perturb(img, augmentation_params=aug_params, target_shape=(w, h))
    else:
        img = perturb_fixed(img, tform_augment=transform, target_shape=(w, h))

    np.subtract(img, MEAN[:, np.newaxis, np.newaxis], out=img)
    np.divide(img, STD[:, np.newaxis, np.newaxis], out=img)
    img = augment_color(img, sigma=sigma, color_vec=color_vec)
    return img
volumes.py 文件源码 项目:diluvian 作者: aschampion 项目源码 文件源码 阅读 35 收藏 0 点赞 0 评论 0
def __init__(self, bounds, orig_resolution, tile_width, tile_height, tile_format_url,
                 zoom_level=0, missing_z=None, image_leaf_shape=None):
        self.orig_bounds = bounds
        self.orig_resolution = orig_resolution
        self.tile_width = tile_width
        self.tile_height = tile_height
        self.tile_format_url = tile_format_url

        self.zoom_level = int(zoom_level)
        if missing_z is None:
            missing_z = []
        self.missing_z = frozenset(missing_z)
        if image_leaf_shape is None:
            image_leaf_shape = [10, tile_height, tile_width]

        scale = np.exp2(np.array([0, self.zoom_level, self.zoom_level])).astype(np.int64)

        data_shape = (np.zeros(3), np.divide(bounds, scale).astype(np.int64))
        self.image_data = OctreeVolume(image_leaf_shape,
                                       data_shape,
                                       'float32',
                                       populator=self.image_populator)

        self.label_data = None
batchdispenser.py 文件源码 项目:LSTM_PIT 作者: snsun 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def apply_cmvn(utt, mean, variance, reverse=False):
    """Apply mean and variance normalisation based on previously computed statistics.

    Args:
        utt: The utterance feature numpy matrix.
        stats: A numpy array containing the mean and variance statistics.
            The first row contains the sum of all the fautures and as a last
            element the total numbe of features. The second row contains the
            squared sum of the features and a zero at the end

    Returns:
        A numpy array containing the mean and variance normalized features
    """
    if not reverse:
        #return mean and variance normalised utterance
        return np.divide(np.subtract(utt, mean), np.sqrt(variance))
    else:
        #reversed normalization
        return np.add(np.multiply(utt, np.sqrt(variance)), mean)
controller.py 文件源码 项目:sumo_reinforcement_learning 作者: JDGlick 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def updateQProbs(lastStateID, lastAction):
    # print 'np.sum(QCounts[lastStateID,]) = ', np.sum(QCounts[lastStateID,])
    # print 'np.sum(QCounts[lastStateID,]) = ', np.sum(QCounts[lastStateID,])
    # print 'np.sum(QValues[lastStateID,]) = ', np.sum(QValues[lastStateID,])
    if np.sum(QCounts[lastStateID,]) == 0 or np.sum(QValues[lastStateID,]) == 0:
        tau = 1
    else:
        # print '(-(np.mean(QValues[lastStateID,]))) = ', (-(np.mean(QValues[lastStateID,])))
        # print '(np.mean(QCounts[lastStateID,])) = ', (np.mean(QCounts[lastStateID,]))
        tau = (-(np.mean(QValues[lastStateID,])))/(np.mean(QCounts[lastStateID,]))
    # print 'tau = ', tau
    numerator = np.exp(QValues[lastStateID, ]/tau)
    tempSum = np.sum(numerator)
    denominator = np.array([tempSum, tempSum, tempSum, tempSum, tempSum, tempSum, tempSum, tempSum])
    QProbs[lastStateID, ] = np.divide(numerator, denominator)

# initial dataframes which will be able to store performance data over different days


问题


面经


文章

微信
公众号

扫码关注公众号