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


Python numpy.allclose方法代码示例

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


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

示例1: _test_hvp

# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import allclose [as 别名]
def _test_hvp(func, optimized):
  np.random.seed(0)
  a = np.random.normal(scale=1, size=(300,)).astype('float32')
  v = a.ravel()

  modes = ['forward', 'reverse']
  for mode1 in modes:
    for mode2 in modes:
      if mode1 == mode2 == 'forward':
        continue
      df = tangent.autodiff(
          func,
          mode=mode1,
          motion='joint',
          optimized=optimized,
          check_dims=False)
      ddf = tangent.autodiff(
          df, mode=mode2, motion='joint', optimized=optimized, check_dims=False)
      dx = ddf(a, 1, v)
      hvp_ag = hessian_vector_product(func)
      dx_ag = hvp_ag(a, v)
      assert np.allclose(dx, dx_ag) 
开发者ID:google,项目名称:tangent,代码行数:24,代码来源:test_hessian_vector_products.py

示例2: check_gradient

# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import allclose [as 别名]
def check_gradient(f, x):
    print(x, "\n", f(x))

    print("# grad2")
    grad2 = Gradient(f)(x)
    print("# building grad1")
    g = grad(f)
    print("# computing grad1")
    grad1 = g(x)

    print("gradient1\n", grad1, "\ngradient2\n", grad2)
    np.allclose(grad1, grad2)

    # check Hessian vector product
    y = np.random.normal(size=x.shape)
    gdot = lambda u: np.dot(g(u), y)
    hess1, hess2 = grad(gdot)(x), Gradient(gdot)(x)
    print("hess1\n", hess1, "\nhess2\n", hess2)
    np.allclose(hess1, hess2) 
开发者ID:popgenmethods,项目名称:momi2,代码行数:21,代码来源:test_autograd.py

示例3: check_random_tensor

# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import allclose [as 别名]
def check_random_tensor(demo, *args, **kwargs):
    leaves = demo.sampled_pops
    ranges = [list(range(n + 1)) for n in demo.sampled_n]

    config_list = momi.data.configurations.build_full_config_list(demo.sampled_pops, demo.sampled_n)

    esfs = expected_sfs(demo, config_list, *args, **kwargs)

    tensor_components = [np.random.normal(size=(1, n + 1)) for n in demo.sampled_n]
    #tensor_components_list = tuple(v[0,:] for _,v in sorted(tensor_components.iteritems()))

    #prod1 = sfs_tensor_prod(dict(list(zip(config_list,esfs))), tensor_components)
    # sfs = momi.site_freq_spectrum(demo.sampled_pops, [dict(zip((tuple(map(tuple,c)) for c in config_list),
    #                                                           esfs))])
    sfs = momi.site_freq_spectrum(demo.sampled_pops,
                                  [{tuple(map(tuple, c)): s for c, s in zip(config_list, esfs)}])
    #assert sfs.get_dict() == {tuple(map(tuple,c)): s for c,s in zip(config_list, esfs)}
    prod1 = sfs_tensor_prod(sfs, tensor_components)
    # prod1 = sfs_tensor_prod({tuple(map(tuple,c)): s for c,s in zip(config_list, esfs)},
    #                        tensor_components)
    prod2 = expected_sfs_tensor_prod(
        tensor_components, demo, sampled_pops=demo.sampled_pops)

    assert np.allclose(prod1, prod2) 
开发者ID:popgenmethods,项目名称:momi2,代码行数:26,代码来源:test_rank1tensor.py

示例4: compute_stats

# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import allclose [as 别名]
def compute_stats(demo, sampled_sfs, true_sfs=None, true_branch_len=None):
    sampled_sfs = momi.site_freq_spectrum(demo.leafs, to_dict(sampled_sfs))
    demo.set_data(sampled_sfs, length=1)
    demo.set_mut_rate(1)

    exp_branch_len = demo.expected_branchlen()
    exp_sfs = demo.expected_sfs()

    configs = sorted([tuple(map(tuple, c)) for c in sampled_sfs.configs])
    exp_sfs = np.array([exp_sfs[c] for c in configs])

    # use ms units
    exp_branch_len = exp_branch_len / 4.0 / demo.N_e
    exp_sfs = exp_sfs / 4.0 / demo.N_e

    if true_sfs is not None:
        assert np.allclose(true_sfs, exp_sfs, rtol=1e-4)
    if true_branch_len is not None:
        assert np.allclose(true_branch_len, exp_branch_len, rtol=1e-4)

    return exp_sfs, exp_branch_len 
开发者ID:popgenmethods,项目名称:momi2,代码行数:23,代码来源:test_sfs.py

示例5: EM

# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import allclose [as 别名]
def EM(init_params, data, callback=None):
    def EM_update(params):
        natural_params = list(map(np.log, params))
        loglike, E_stats = vgrad(log_partition_function)(natural_params, data)  # E step
        if callback: callback(loglike, params)
        return list(map(normalize, E_stats))                                    # M step

    def fixed_point(f, x0):
        x1 = f(x0)
        while different(x0, x1):
            x0, x1 = x1, f(x1)
        return x1

    def different(params1, params2):
        allclose = partial(np.allclose, atol=1e-3, rtol=1e-3)
        return not all(map(allclose, params1, params2))

    return fixed_point(EM_update, init_params) 
开发者ID:HIPS,项目名称:autograd,代码行数:20,代码来源:hmm_em.py

示例6: test_getter

# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import allclose [as 别名]
def test_getter():
    def fun(input_list):
        A = np.sum(input_list[0])
        B = np.sum(input_list[1])
        C = np.sum(input_list[1])
        return A + B + C

    d_fun = grad(fun)
    input_list = [npr.randn(5, 6),
                   npr.randn(4, 3),
                   npr.randn(2, 4)]

    result = d_fun(input_list)
    assert np.allclose(result[0], np.ones((5, 6)))
    assert np.allclose(result[1], 2 * np.ones((4, 3)))
    assert np.allclose(result[2], np.zeros((2, 4))) 
开发者ID:HIPS,项目名称:autograd,代码行数:18,代码来源:test_list.py

示例7: test_getter

# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import allclose [as 别名]
def test_getter():
    def fun(input_tuple):
        A = np.sum(input_tuple[0])
        B = np.sum(input_tuple[1])
        C = np.sum(input_tuple[1])
        return A + B + C

    d_fun = grad(fun)
    input_tuple = (npr.randn(5, 6),
                   npr.randn(4, 3),
                   npr.randn(2, 4))

    result = d_fun(input_tuple)
    assert np.allclose(result[0], np.ones((5, 6)))
    assert np.allclose(result[1], 2 * np.ones((4, 3)))
    assert np.allclose(result[2], np.zeros((2, 4))) 
开发者ID:HIPS,项目名称:autograd,代码行数:18,代码来源:test_tuple.py

示例8: test_getter

# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import allclose [as 别名]
def test_getter():
    def fun(input_dict):
        A = np.sum(input_dict['item_1'])
        B = np.sum(input_dict['item_2'])
        C = np.sum(input_dict['item_2'])
        return A + B + C

    d_fun = grad(fun)
    input_dict = {'item_1' : npr.randn(5, 6),
                  'item_2' : npr.randn(4, 3),
                  'item_X' : npr.randn(2, 4)}

    result = d_fun(input_dict)
    assert np.allclose(result['item_1'], np.ones((5, 6)))
    assert np.allclose(result['item_2'], 2 * np.ones((4, 3)))
    assert np.allclose(result['item_X'], np.zeros((2, 4))) 
开发者ID:HIPS,项目名称:autograd,代码行数:18,代码来源:test_dict.py

示例9: __init__

# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import allclose [as 别名]
def __init__(self, degree=3, gamma=None, coef0=1):
        """
        Polynomial kernel
          (gamma X^T Y + coef0)^degree

        degree: default 3
        gamma: default 1/dim
        coef0: float, default 1
        """
        self.degree = degree
        self.gamma = gamma
        self.coef0 = coef0
        if degree <= 0:
            raise ValueError("KPoly needs positive degree")
        if not np.allclose(degree, int(degree)):
            raise ValueError("KPoly needs integral degree") 
开发者ID:wittawatj,项目名称:kernel-gof,代码行数:18,代码来源:kernel.py

示例10: _set_startprob

# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import allclose [as 别名]
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()) 
开发者ID:mackelab,项目名称:autohmm,代码行数:25,代码来源:tm.py

示例11: _set_transmat

# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import allclose [as 别名]
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 
开发者ID:mackelab,项目名称:autohmm,代码行数:23,代码来源:tm.py

示例12: add_data

# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import allclose [as 别名]
def add_data(self, S, F=None):
        """
        Add a data set to the list of observations.
        First, filter the data with the impulse response basis,
        then instantiate a set of parents for this data set.

        :param S: a TxK matrix of of event counts for each time bin
                  and each process.
        """
        assert isinstance(S, np.ndarray) and S.ndim == 2 and S.shape[1] == self.K \
               and np.amin(S) >= 0 and S.dtype == np.int, \
               "Data must be a TxK array of event counts"

        T = S.shape[0]

        if F is None:
            # Filter the data into a TxKxB array
            Ftens = self.basis.convolve_with_basis(S)

            # Flatten this into a T x (KxB) matrix
            # [F00, F01, F02, F10, F11, ... F(K-1)0, F(K-1)(B-1)]
            F = Ftens.reshape((T, self.K * self.B))
            assert np.allclose(F[:,0], Ftens[:,0,0])
            if self.B > 1:
                assert np.allclose(F[:,1], Ftens[:,0,1])
            if self.K > 1:
                assert np.allclose(F[:,self.B], Ftens[:,1,0])

            # Prepend a column of ones
            F = np.hstack((np.ones((T,1)), F))

        for k,node in enumerate(self.nodes):
            node.add_data(F, S[:,k]) 
开发者ID:slinderman,项目名称:pyhawkes,代码行数:35,代码来源:standard_models.py

示例13: check_symmetric

# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import allclose [as 别名]
def check_symmetric(X):
    Xt = np.transpose(X)
    assert np.allclose(X, Xt)
    return 0.5 * (X + Xt) 
开发者ID:popgenmethods,项目名称:momi2,代码行数:6,代码来源:util.py

示例14: check_psd

# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import allclose [as 别名]
def check_psd(X, **tol_kwargs):
    X = check_symmetric(X)
    d, U = np.linalg.eigh(X)
    d = truncate0(d, **tol_kwargs)
    ret = np.dot(U, np.dot(np.diag(d), np.transpose(U)))
    #assert np.allclose(ret, X)
    return np.array(ret, ndmin=2) 
开发者ID:popgenmethods,项目名称:momi2,代码行数:9,代码来源:util.py

示例15: check_probs_matrix

# 需要导入模块: from autograd import numpy [as 别名]
# 或者: from autograd.numpy import allclose [as 别名]
def check_probs_matrix(x):
    x = truncate0(x)
    rowsums = np.sum(x, axis=1)
    assert np.allclose(rowsums, 1.0)
    return np.einsum('ij,i->ij', x, 1.0 / rowsums) 
开发者ID:popgenmethods,项目名称:momi2,代码行数:7,代码来源:util.py


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