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


Python numpy.cov方法代码示例

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


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

示例1: PCA_components

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import cov [as 别名]
def PCA_components(x):
    """
    Principal Component Analysis helper to check out eigenvalues of components.

    **Args:**

    * `x` : input matrix (2d array), every row represents new sample

    **Returns:**
    
    * `components`: sorted array of principal components eigenvalues 
        
    """ 
    # validate inputs
    try:    
        x = np.array(x)
    except:
        raise ValueError('Impossible to convert x to a numpy array.')
    # eigen values and eigen vectors of data covariance matrix
    eigen_values, eigen_vectors = np.linalg.eig(np.cov(x.T))
    # sort eigen vectors according biggest eigen value
    eigen_order = eigen_vectors.T[(-eigen_values).argsort()]
    # form output - order the eigenvalues
    return eigen_values[(-eigen_values).argsort()] 
开发者ID:matousc89,项目名称:padasip,代码行数:26,代码来源:pca.py

示例2: get_ma_dist

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import cov [as 别名]
def get_ma_dist(A, B):
    Y = A.copy()
    X = B.copy()
    
    S = np.cov(X.T)
    try:
        SI = np.linalg.inv(S)
    except:
        print("Singular Matrix: using np.linalg.pinv")
        SI = np.linalg.pinv(S)
    mu = np.mean(X, axis=0)
    
    diff = Y - mu
    Dct_c = np.diag(diff @ SI @ diff.T)
    
    return Dct_c 
开发者ID:jindongwang,项目名称:transferlearning,代码行数:18,代码来源:EasyTL.py

示例3: calculate_activation_statistics

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import cov [as 别名]
def calculate_activation_statistics(pointclouds, model, batch_size=100,
                                    dims=1808, device=None, verbose=False):
    """Calculation of the statistics used by the FID.
    Params:
    -- pointcloud       : pytorch Tensor of pointclouds.
    -- model       : Instance of inception model
    -- batch_size  : The images numpy array is split into batches with
                     batch size batch_size. A reasonable batch size
                     depends on the hardware.
    -- dims        : Dimensionality of features returned by Inception
    -- device      : If set to device, use GPU
    -- verbose     : If set to True and parameter out_step is given, the
                     number of calculated batches is reported.
    Returns:
    -- mu    : The mean over samples of the activations of the pool_3 layer of
               the inception model.
    -- sigma : The covariance matrix of the activations of the pool_3 layer of
               the inception model.
    """
    act = get_activations(pointclouds, model, batch_size, dims, device, verbose)
    mu = np.mean(act, axis=0)
    sigma = np.cov(act, rowvar=False)
    return mu, sigma 
开发者ID:seowok,项目名称:TreeGAN,代码行数:25,代码来源:FPD.py

示例4: test_1d_with_missing

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import cov [as 别名]
def test_1d_with_missing(self):
        # Test cov 1 1D variable w/missing values
        x = self.data
        x[-1] = masked
        x -= x.mean()
        nx = x.compressed()
        assert_almost_equal(np.cov(nx), cov(x))
        assert_almost_equal(np.cov(nx, rowvar=False), cov(x, rowvar=False))
        assert_almost_equal(np.cov(nx, rowvar=False, bias=True),
                            cov(x, rowvar=False, bias=True))
        #
        try:
            cov(x, allow_masked=False)
        except ValueError:
            pass
        #
        # 2 1D variables w/ missing values
        nx = x[1:-1]
        assert_almost_equal(np.cov(nx, nx[::-1]), cov(x, x[::-1]))
        assert_almost_equal(np.cov(nx, nx[::-1], rowvar=False),
                            cov(x, x[::-1], rowvar=False))
        assert_almost_equal(np.cov(nx, nx[::-1], rowvar=False, bias=True),
                            cov(x, x[::-1], rowvar=False, bias=True)) 
开发者ID:Frank-qlu,项目名称:recruit,代码行数:25,代码来源:test_extras.py

示例5: test_2d_with_missing

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import cov [as 别名]
def test_2d_with_missing(self):
        # Test cov on 2D variable w/ missing value
        x = self.data
        x[-1] = masked
        x = x.reshape(3, 4)
        valid = np.logical_not(getmaskarray(x)).astype(int)
        frac = np.dot(valid, valid.T)
        xf = (x - x.mean(1)[:, None]).filled(0)
        assert_almost_equal(cov(x),
                            np.cov(xf) * (x.shape[1] - 1) / (frac - 1.))
        assert_almost_equal(cov(x, bias=True),
                            np.cov(xf, bias=True) * x.shape[1] / frac)
        frac = np.dot(valid.T, valid)
        xf = (x - x.mean(0)).filled(0)
        assert_almost_equal(cov(x, rowvar=False),
                            (np.cov(xf, rowvar=False) *
                             (x.shape[0] - 1) / (frac - 1.)))
        assert_almost_equal(cov(x, rowvar=False, bias=True),
                            (np.cov(xf, rowvar=False, bias=True) *
                             x.shape[0] / frac)) 
开发者ID:Frank-qlu,项目名称:recruit,代码行数:22,代码来源:test_extras.py

示例6: test_expanding_cov_diff_index

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import cov [as 别名]
def test_expanding_cov_diff_index(self):
        # GH 7512
        s1 = Series([1, 2, 3], index=[0, 1, 2])
        s2 = Series([1, 3], index=[0, 2])
        result = s1.expanding().cov(s2)
        expected = Series([None, None, 2.0])
        tm.assert_series_equal(result, expected)

        s2a = Series([1, None, 3], index=[0, 1, 2])
        result = s1.expanding().cov(s2a)
        tm.assert_series_equal(result, expected)

        s1 = Series([7, 8, 10], index=[0, 1, 3])
        s2 = Series([7, 9, 10], index=[0, 2, 3])
        result = s1.expanding().cov(s2)
        expected = Series([None, None, None, 4.5])
        tm.assert_series_equal(result, expected) 
开发者ID:Frank-qlu,项目名称:recruit,代码行数:19,代码来源:test_window.py

示例7: test_rolling_functions_window_non_shrinkage_binary

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import cov [as 别名]
def test_rolling_functions_window_non_shrinkage_binary(self):

        # corr/cov return a MI DataFrame
        df = DataFrame([[1, 5], [3, 2], [3, 9], [-1, 0]],
                       columns=Index(['A', 'B'], name='foo'),
                       index=Index(range(4), name='bar'))
        df_expected = DataFrame(
            columns=Index(['A', 'B'], name='foo'),
            index=pd.MultiIndex.from_product([df.index, df.columns],
                                             names=['bar', 'foo']),
            dtype='float64')
        functions = [lambda x: (x.rolling(window=10, min_periods=5)
                                .cov(x, pairwise=True)),
                     lambda x: (x.rolling(window=10, min_periods=5)
                                .corr(x, pairwise=True))]
        for f in functions:
            df_result = f(df)
            tm.assert_frame_equal(df_result, df_expected) 
开发者ID:Frank-qlu,项目名称:recruit,代码行数:20,代码来源:test_window.py

示例8: test_expanding_cov_pairwise_diff_length

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import cov [as 别名]
def test_expanding_cov_pairwise_diff_length(self):
        # GH 7512
        df1 = DataFrame([[1, 5], [3, 2], [3, 9]],
                        columns=Index(['A', 'B'], name='foo'))
        df1a = DataFrame([[1, 5], [3, 9]],
                         index=[0, 2],
                         columns=Index(['A', 'B'], name='foo'))
        df2 = DataFrame([[5, 6], [None, None], [2, 1]],
                        columns=Index(['X', 'Y'], name='foo'))
        df2a = DataFrame([[5, 6], [2, 1]],
                         index=[0, 2],
                         columns=Index(['X', 'Y'], name='foo'))
        # TODO: xref gh-15826
        # .loc is not preserving the names
        result1 = df1.expanding().cov(df2a, pairwise=True).loc[2]
        result2 = df1.expanding().cov(df2a, pairwise=True).loc[2]
        result3 = df1a.expanding().cov(df2, pairwise=True).loc[2]
        result4 = df1a.expanding().cov(df2a, pairwise=True).loc[2]
        expected = DataFrame([[-3.0, -6.0], [-5.0, -10.0]],
                             columns=Index(['A', 'B'], name='foo'),
                             index=Index(['X', 'Y'], name='foo'))
        tm.assert_frame_equal(result1, expected)
        tm.assert_frame_equal(result2, expected)
        tm.assert_frame_equal(result3, expected)
        tm.assert_frame_equal(result4, expected) 
开发者ID:Frank-qlu,项目名称:recruit,代码行数:27,代码来源:test_window.py

示例9: test_expanding_corr_cov

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import cov [as 别名]
def test_expanding_corr_cov(self):
        g = self.frame.groupby('A')
        r = g.expanding()

        for f in ['corr', 'cov']:
            result = getattr(r, f)(self.frame)

            def func(x):
                return getattr(x.expanding(), f)(self.frame)
            expected = g.apply(func)
            tm.assert_frame_equal(result, expected)

            result = getattr(r.B, f)(pairwise=True)

            def func(x):
                return getattr(x.B.expanding(), f)(pairwise=True)
            expected = g.apply(func)
            tm.assert_series_equal(result, expected) 
开发者ID:Frank-qlu,项目名称:recruit,代码行数:20,代码来源:test_window.py

示例10: test_rolling_cov_offset

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import cov [as 别名]
def test_rolling_cov_offset(self):
        # GH16058

        idx = pd.date_range('2017-01-01', periods=24, freq='1h')
        ss = Series(np.arange(len(idx)), index=idx)

        result = ss.rolling('2h').cov()
        expected = Series([np.nan] + [0.5] * (len(idx) - 1), index=idx)
        tm.assert_series_equal(result, expected)

        expected2 = ss.rolling(2, min_periods=1).cov()
        tm.assert_series_equal(result, expected2)

        result = ss.rolling('3h').cov()
        expected = Series([np.nan, 0.5] + [1.0] * (len(idx) - 2), index=idx)
        tm.assert_series_equal(result, expected)

        expected2 = ss.rolling(3, min_periods=1).cov()
        tm.assert_series_equal(result, expected2) 
开发者ID:Frank-qlu,项目名称:recruit,代码行数:21,代码来源:test_window.py

示例11: nancov

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import cov [as 别名]
def nancov(a, b, min_periods=None):
    if len(a) != len(b):
        raise AssertionError('Operands to nancov must have same size')

    if min_periods is None:
        min_periods = 1

    valid = notna(a) & notna(b)
    if not valid.all():
        a = a[valid]
        b = b[valid]

    if len(a) < min_periods:
        return np.nan

    return np.cov(a, b)[0, 1] 
开发者ID:Frank-qlu,项目名称:recruit,代码行数:18,代码来源:nanops.py

示例12: test_shape_inference

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import cov [as 别名]
def test_shape_inference(self):
        with self.session(use_gpu=True):
            # Static
            mean = 10 * np.random.normal(size=(10, 11, 2)).astype('d')
            cov = np.zeros((10, 11, 2, 2))
            dst = MultivariateNormalCholesky(
                tf.constant(mean), tf.constant(cov))
            self.assertEqual(dst.get_batch_shape().as_list(), [10, 11])
            self.assertEqual(dst.get_value_shape().as_list(), [2])
            # Dynamic
            unk_mean = tf.placeholder(tf.float32, None)
            unk_cov = tf.placeholder(tf.float32, None)
            dst = MultivariateNormalCholesky(unk_mean, unk_cov)
            self.assertEqual(dst.get_value_shape().as_list(), [None])
            feed_dict = {unk_mean: np.ones(2), unk_cov: np.eye(2)}
            self.assertEqual(list(dst.batch_shape.eval(feed_dict)), [])
            self.assertEqual(list(dst.value_shape.eval(feed_dict)), [2]) 
开发者ID:thu-ml,项目名称:zhusuan,代码行数:19,代码来源:test_multivariate.py

示例13: test_sample

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import cov [as 别名]
def test_sample(self):
        with self.fixed_randomness_session(233):
            def test_sample_with(seed):
                mean, cov, cov_chol = self._gen_test_params(seed)
                dst = MultivariateNormalCholesky(
                    tf.constant(mean), tf.constant(cov_chol))
                n_exp = 20000
                samples = dst.sample(n_exp)
                sample_shape = (n_exp, 10, 11, 3)
                self.assertEqual(samples.shape.as_list(), list(sample_shape))
                samples = dst.sample(n_exp).eval()
                self.assertEqual(samples.shape, sample_shape)
                self.assertAllClose(
                    np.mean(samples, axis=0), mean, rtol=5e-2, atol=5e-2)
                for i in range(10):
                    for j in range(11):
                        self.assertAllClose(
                            np.cov(samples[:, i, j, :].T), cov[i, j],
                            rtol=1e-1, atol=1e-1)

            for seed in [23, 233, 2333]:
                test_sample_with(seed) 
开发者ID:thu-ml,项目名称:zhusuan,代码行数:24,代码来源:test_multivariate.py

示例14: test_prob

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import cov [as 别名]
def test_prob(self):
        with self.fixed_randomness_session(233):
            def test_prob_with(seed):
                mean, cov, cov_chol = self._gen_test_params(seed)
                dst = MultivariateNormalCholesky(
                    tf.constant(mean), tf.constant(cov_chol),
                    check_numerics=True)
                n_exp = 200
                samples = dst.sample(n_exp).eval()
                log_pdf = dst.log_prob(tf.constant(samples))
                pdf_shape = (n_exp, 10, 11)
                self.assertEqual(log_pdf.shape.as_list(), list(pdf_shape))
                log_pdf = log_pdf.eval()
                self.assertEqual(log_pdf.shape, pdf_shape)
                for i in range(10):
                    for j in range(11):
                        log_pdf_exact = stats.multivariate_normal.logpdf(
                                samples[:, i, j, :], mean[i, j], cov[i, j])
                        self.assertAllClose(
                            log_pdf_exact, log_pdf[:, i, j])
                self.assertAllClose(
                    np.exp(log_pdf), dst.prob(tf.constant(samples)).eval())

            for seed in [23, 233, 2333]:
                test_prob_with(seed) 
开发者ID:thu-ml,项目名称:zhusuan,代码行数:27,代码来源:test_multivariate.py

示例15: calculate_activation_statistics

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import cov [as 别名]
def calculate_activation_statistics(images, model, batch_size=64, dims=2048, device=None):
    """Calculation of the statistics used by the FID.
    Params:
    -- images      : Numpy array of dimension (n_images, 3, hi, wi). The values
                     must lie between 0 and 1.
    -- model       : Instance of inception model
    -- batch_size  : The images numpy array is split into batches with
                     batch size batch_size. A reasonable batch size
                     depends on the hardware.
    -- dims        : Dimensionality of features returned by Inception
    -- device      : If set to True, use GPU
    -- verbose     : If set to True and parameter out_step is given, the
                     number of calculated batches is reported.
    Returns:
    -- mu    : The mean over samples of the activations of the pool_3 layer of
               the inception model.
    -- sigma : The covariance matrix of the activations of the pool_3 layer of
               the inception model.
    """
    act = get_activations(images, model, batch_size, dims, device)
    mu = np.mean(act, axis=0)
    sigma = np.cov(act, rowvar=False)
    return mu, sigma 
开发者ID:crcrpar,项目名称:pytorch.sngan_projection,代码行数:25,代码来源:fid.py


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