当前位置: 首页>>代码示例>>Python>>正文


Python numpy.histogram2d方法代码示例

本文整理汇总了Python中numpy.histogram2d方法的典型用法代码示例。如果您正苦于以下问题:Python numpy.histogram2d方法的具体用法?Python numpy.histogram2d怎么用?Python numpy.histogram2d使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在numpy的用法示例。


在下文中一共展示了numpy.histogram2d方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: hist

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import histogram2d [as 别名]
def hist(self, nplan, xedges, yedges):
        """Returns completeness histogram for Monte Carlo simulation
        
        This function uses the inherited Planet Population module.
        
        Args:
            nplan (float):
                number of planets used
            xedges (float ndarray):
                x edge of 2d histogram (separation)
            yedges (float ndarray):
                y edge of 2d histogram (dMag)
        
        Returns:
            h (ndarray):
                2D numpy ndarray containing completeness histogram
        
        """
        
        s, dMag = self.genplans(nplan)
        # get histogram
        h, yedges, xedges = np.histogram2d(dMag, s.to('AU').value, bins=1000,
                range=[[yedges.min(), yedges.max()], [xedges.min(), xedges.max()]])
        
        return h, xedges, yedges 
开发者ID:dsavransky,项目名称:EXOSIMS,代码行数:27,代码来源:SS_det_only.py

示例2: hist

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import histogram2d [as 别名]
def hist(self, nplan, xedges, yedges):
        """Returns completeness histogram for Monte Carlo simulation
        
        This function uses the inherited Planet Population module.
        
        Args:
            nplan (float):
                number of planets used
            xedges (float ndarray):
                x edge of 2d histogram (separation)
            yedges (float ndarray):
                y edge of 2d histogram (dMag)
        
        Returns:
            float ndarray:
                2D numpy ndarray containing completeness frequencies
        
        """
        
        s, dMag = self.genplans(nplan)
        # get histogram
        h, yedges, xedges = np.histogram2d(dMag, s.to('AU').value, bins=1000,
                range=[[yedges.min(), yedges.max()], [xedges.min(), xedges.max()]])
        
        return h, xedges, yedges 
开发者ID:dsavransky,项目名称:EXOSIMS,代码行数:27,代码来源:BrownCompleteness.py

示例3: _mutual_information_varoquaux

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import histogram2d [as 别名]
def _mutual_information_varoquaux(x, y, bins=256, sigma=1, normalized=True):
    """Based on Gael Varoquaux's implementation: https://gist.github.com/GaelVaroquaux/ead9898bd3c973c40429."""
    jh = np.histogram2d(x, y, bins=bins)[0]

    # smooth the jh with a gaussian filter of given sigma
    scipy.ndimage.gaussian_filter(jh, sigma=sigma, mode="constant", output=jh)

    # compute marginal histograms
    jh = jh + np.finfo(float).eps
    sh = np.sum(jh)
    jh = jh / sh
    s1 = np.sum(jh, axis=0).reshape((-1, jh.shape[0]))
    s2 = np.sum(jh, axis=1).reshape((jh.shape[1], -1))

    if normalized:
        mi = ((np.sum(s1 * np.log(s1)) + np.sum(s2 * np.log(s2))) / np.sum(jh * np.log(jh))) - 1
    else:
        mi = np.sum(jh * np.log(jh)) - np.sum(s1 * np.log(s1)) - np.sum(s2 * np.log(s2))

    return mi 
开发者ID:neuropsychology,项目名称:NeuroKit,代码行数:22,代码来源:mutual_information.py

示例4: fit

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import histogram2d [as 别名]
def fit(self, magnitude, time, dt_bins, dm_bins):
        def delta_calc(idx):
            t0 = time[idx]
            m0 = magnitude[idx]
            deltat = time[idx + 1 :] - t0
            deltam = magnitude[idx + 1 :] - m0

            deltat[np.where(deltat < 0)] *= -1
            deltam[np.where(deltat < 0)] *= -1

            return np.column_stack((deltat, deltam))

        lc_len = len(time)
        n_vals = int(0.5 * lc_len * (lc_len - 1))

        deltas = np.vstack(tuple(delta_calc(idx) for idx in range(lc_len - 1)))

        deltat = deltas[:, 0]
        deltam = deltas[:, 1]

        bins = [dt_bins, dm_bins]
        counts = np.histogram2d(deltat, deltam, bins=bins, normed=False)[0]
        result = np.fix(255.0 * counts / n_vals + 0.999).astype(int)

        return {"DMDT": result} 
开发者ID:quatrope,项目名称:feets,代码行数:27,代码来源:ext_dmdt.py

示例5: gridded_mean

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import histogram2d [as 别名]
def gridded_mean(lat, lon, data, grid):
    """Grid data along latitudes and longitudes

    Args:
        lat: Grid points along latitudes as 1xN dimensional array.
        lon: Grid points along longitudes as 1xM dimensional array.
        data: The data as NxM numpy array.
        grid: A tuple with two numpy arrays, consisting of latitude and
            longitude grid points.

    Returns:
        Two matrices in grid form: the mean and the number of points of `data`.
    """
    grid_sum, _, _ = np.histogram2d(lat, lon, grid, weights=data)
    grid_number, _, _ = np.histogram2d(lat, lon, grid)

    return grid_sum / grid_number, grid_number 
开发者ID:atmtools,项目名称:typhon,代码行数:19,代码来源:geographical.py

示例6: morista_index

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import histogram2d [as 别名]
def morista_index(points):
    # Morisita Index of Dispersion

    N = points.shape[1]

    ims = []
    for i in range(1, N):
        bins, _, _ = np.histogram2d(points[0], points[1], i)

        # I_M  = Q * (\sum_{k=1}^{Q}{n_k * (n_k - 1)})/(N * (N _ 1))
        Q = len(bins)  # num_quadrants

        # Eqn 1.
        I_M = Q * np.sum(np.ravel(bins) * (np.ravel(bins) - 1)) / (N * (N - 1))
        ims.append([i, I_M])


    return np.array(ims).T[1].max() 
开发者ID:JasonKessler,项目名称:scattertext,代码行数:20,代码来源:OptimalProjection.py

示例7: pred_table

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import histogram2d [as 别名]
def pred_table(self, threshold=.5):
        """
        Prediction table

        Parameters
        ----------
        threshold : scalar
            Number between 0 and 1. Threshold above which a prediction is
            considered 1 and below which a prediction is considered 0.

        Notes
        ------
        pred_table[i,j] refers to the number of times "i" was observed and
        the model predicted "j". Correct predictions are along the diagonal.
        """
        model = self.model
        actual = model.endog
        pred = np.array(self.predict() > threshold, dtype=float)
        bins = np.array([0, 0.5, 1])
        return np.histogram2d(actual, pred, bins=bins)[0] 
开发者ID:birforce,项目名称:vnpy_crypto,代码行数:22,代码来源:discrete_model.py

示例8: pix_histogram

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import histogram2d [as 别名]
def pix_histogram(self, mask, lbl):
    '''
      get individual mask and label and create 2d hist
    '''
    # flatten mask and cast
    flat_mask = mask.flatten().astype(np.uint32)
    # flatten label and cast
    flat_label = lbl.flatten().astype(np.uint32)
    # get the histogram
    histrange = np.array([[-0.5, self.num_classes - 0.5],
                          [-0.5, self.num_classes - 0.5]], dtype='float64')
    h_now, _, _ = np.histogram2d(np.array(flat_mask),
                                 np.array(flat_label),
                                 bins=self.num_classes,
                                 range=histrange)
    return h_now 
开发者ID:PRBonn,项目名称:bonnet,代码行数:18,代码来源:abstract_net.py

示例9: mutual_information

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import histogram2d [as 别名]
def mutual_information(x, y, nbins=32, normalized=False):
    """
    Compute mutual information
    :param x: 1D numpy.array : flatten data from an image
    :param y: 1D numpy.array : flatten data from an image
    :param nbins: number of bins to compute the contingency matrix (only used if normalized=False)
    :return: float non negative value : mutual information
    """
    import sklearn.metrics
    if normalized:
        mi = sklearn.metrics.normalized_mutual_info_score(x, y)
    else:
        c_xy = np.histogram2d(x, y, nbins)[0]
        mi = sklearn.metrics.mutual_info_score(None, None, contingency=c_xy)
    # mi = adjusted_mutual_info_score(None, None, contingency=c_xy)
    return mi 
开发者ID:neuropoly,项目名称:spinalcordtoolbox,代码行数:18,代码来源:sct_maths.py

示例10: test_displaced_two_mode_state_hafnian

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import histogram2d [as 别名]
def test_displaced_two_mode_state_hafnian(self, sample_func):
        """Test the sampling routines by comparing the photon number frequencies and the exact
        probability distribution of a two mode coherent state
        """
        n_samples = 1000
        n_cut = 6
        sigma = np.identity(4)
        mean = 5 * np.array([0.1, 0.25, 0.1, 0.25])
        samples = sample_func(sigma, samples=n_samples, mean=mean, cutoff=n_cut)
        # samples = hafnian_sample_classical_state(sigma, mean = mean, samples = n_samples)
        probs = np.real_if_close(
            np.array(
                [
                    [density_matrix_element(mean, sigma, [i, j], [i, j]) for i in range(n_cut)]
                    for j in range(n_cut)
                ]
            )
        )
        freq, _, _ = np.histogram2d(samples[:, 1], samples[:, 0], bins=np.arange(0, n_cut + 1))
        rel_freq = freq / n_samples

        assert np.allclose(
            rel_freq, probs, rtol=rel_tol / np.sqrt(n_samples), atol=rel_tol / np.sqrt(n_samples)
        ) 
开发者ID:XanaduAI,项目名称:thewalrus,代码行数:26,代码来源:test_samples.py

示例11: hist2d

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import histogram2d [as 别名]
def hist2d(self, x, y, weights, bins):   #bins[nx,ny]
        ### generates a 2d hist from input 1d axis for x,y. repeats them to match shape of weights X*Y (data points)
        ### x will be 0-100%
        freqs = np.repeat(np.array([y], dtype=np.float64), len(x), axis=0)
        throts = np.repeat(np.array([x], dtype=np.float64), len(y), axis=0).transpose()
        throt_hist_avr, throt_scale_avr = np.histogram(x, 101, [0, 100])

        hist2d = np.histogram2d(throts.flatten(), freqs.flatten(),
                                range=[[0, 100], [y[0], y[-1]]],
                                bins=bins, weights=weights.flatten(), normed=False)[0].transpose()

        hist2d = np.array(abs(hist2d), dtype=np.float64)
        hist2d_norm = np.copy(hist2d)
        hist2d_norm /=  (throt_hist_avr + 1e-9)

        return {'hist2d_norm':hist2d_norm, 'hist2d':hist2d, 'throt_hist':throt_hist_avr,'throt_scale':throt_scale_avr} 
开发者ID:PX4,项目名称:flight_review,代码行数:18,代码来源:pid_analysis.py

示例12: test_gate_fraction_2_error_large_gate_fraction

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import histogram2d [as 别名]
def test_gate_fraction_2_error_large_gate_fraction(self):
        bins = [-0.5, 0.5, 1.5, 2.5, 3.5, 4.5]
        self.assertRaises(
            ValueError,
            FlowCal.gate.density2d,
            self.pyramid,
            bins=bins,
            gate_fraction=1.1,
            sigma=0.0,
            )

    # Test implicit gating (when values exist outside specified bins)
    #
    # The expected behavior is that density2d() should mimic
    # np.histogram2d()'s behavior: values outside the specified bins are
    # ignored (in the context of a gate function, this means they are
    # implicitly gated out). 
开发者ID:taborlab,项目名称:FlowCal,代码行数:19,代码来源:test_gate.py

示例13: test_sub_bin_1_mask

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import histogram2d [as 别名]
def test_sub_bin_1_mask(self):
        bins = [0.5, 2.5, 4.5]
        np.testing.assert_array_equal(
            FlowCal.gate.density2d(
                self.slope, bins=bins, gate_fraction=13.0/30, sigma=0.0,
                full_output=True).mask,
            np.array([0,0,0,0,0,0,0,0,0,0,1,1,0,0,1,1,0,0,0,0,1,1,0,1,1,
                1,1,1,1,1], dtype=bool)
            )

    # Test bins edge case (when bin edges = values)
    #
    # Again, the expected behavior is that density2d() should mimic
    # np.histogram2d()'s behavior which will group the right-most two values
    # together in the same bin (since the last bins interval is fully closed,
    # as opposed to all other bins intervals which are half-open). 
开发者ID:taborlab,项目名称:FlowCal,代码行数:18,代码来源:test_gate.py

示例14: spectral_distribution

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import histogram2d [as 别名]
def spectral_distribution(points, cumulative=True):
    """ 
    Returns the distribution of complex values (in r,theta-space).
    """

    points = np.array([(np.abs(z), np.angle(z)) for z in points])
    r, theta = np.split(points, 2, axis=1)

    r = np.array([logr(x, r.max()) for x in r])

    Z, R, THETA = np.histogram2d(
        x=r[:, 0],
        y=theta[:, 0],
        bins=(np.linspace(0, 1, 101), np.linspace(0, np.pi, 101)),
    )

    if cumulative:
        Z = Z.cumsum(axis=0).cumsum(axis=1)
        Z = Z / Z.max()

    return Z.flatten() 
开发者ID:netsiphd,项目名称:netrd,代码行数:23,代码来源:distributional_nbd.py

示例15: test_no_params

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import histogram2d [as 别名]
def test_no_params(self):
        x = np.array([1, 2, 3, 4, 5])
        y = np.array([5, 7, 1, 5, 9])
        with self.assertWarns(PrivacyLeakWarning):
            res = histogram2d(x, y)
        self.assertIsNotNone(res) 
开发者ID:IBM,项目名称:differential-privacy-library,代码行数:8,代码来源:test_histogram2d.py


注:本文中的numpy.histogram2d方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。