當前位置: 首頁>>代碼示例>>Python>>正文


Python numpy.tri方法代碼示例

本文整理匯總了Python中numpy.tri方法的典型用法代碼示例。如果您正苦於以下問題:Python numpy.tri方法的具體用法?Python numpy.tri怎麽用?Python numpy.tri使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在numpy的用法示例。


在下文中一共展示了numpy.tri方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: ones_matrix_band_part

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import tri [as 別名]
def ones_matrix_band_part(rows, cols, num_lower, num_upper, out_shape=None):
  """Matrix band part of ones."""
  if all([isinstance(el, int) for el in [rows, cols, num_lower, num_upper]]):
    # Needed info is constant, so we construct in numpy
    if num_lower < 0:
      num_lower = rows - 1
    if num_upper < 0:
      num_upper = cols - 1
    lower_mask = np.tri(cols, rows, num_lower).T
    upper_mask = np.tri(rows, cols, num_upper)
    band = np.ones((rows, cols)) * lower_mask * upper_mask
    if out_shape:
      band = band.reshape(out_shape)
    band = tf.constant(band, tf.float32)
  else:
    band = tf.matrix_band_part(
        tf.ones([rows, cols]), tf.cast(num_lower, tf.int64),
        tf.cast(num_upper, tf.int64))
    if out_shape:
      band = tf.reshape(band, out_shape)

  return band 
開發者ID:akzaidi,項目名稱:fine-lm,代碼行數:24,代碼來源:common_layers.py

示例2: _ones_matrix_band_part

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import tri [as 別名]
def _ones_matrix_band_part(rows, cols, num_lower, num_upper,
    out_shape=None):
    """Matrix band part of ones.
    """
    if all([isinstance(el, int) for el in [rows, cols, num_lower,
        num_upper]]):
    # Needed info is constant, so we construct in numpy
        if num_lower < 0:
            num_lower = rows - 1
        if num_upper < 0:
            num_upper = cols - 1
        lower_mask = np.tri(cols, rows, num_lower).T
        upper_mask = np.tri(rows, cols, num_upper)
        band = np.ones((rows, cols)) * lower_mask * upper_mask
        if out_shape:
            band = band.reshape(out_shape)
        band = tf.constant(band, tf.float32)
    else:
        band = tf.matrix_band_part(tf.ones([rows, cols]),
                                   tf.cast(num_lower, tf.int64),
                                   tf.cast(num_upper, tf.int64))
        if out_shape:
            band = tf.reshape(band, out_shape)
    return band 
開發者ID:qkaren,項目名稱:Counterfactual-StoryRW,代碼行數:26,代碼來源:transformer_attentions.py

示例3: make_batch_mask

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import tri [as 別名]
def make_batch_mask(mb_size, n_head, max_length_1, max_length_2, 
                    key_seq_lengths=None,
                    future_mask=False,
                    mask_value=-10000):
    
    if future_mask:
        assert max_length_1 == max_length_2
        mask = np.array(
                np.broadcast_to(( (-mask_value) * (np.tri(max_length_1, dtype = np.float32)-1))[None,None,:,:], 
                                (mb_size, n_head, max_length_1, max_length_2))
                )
    else:
        mask = np.zeros((mb_size, n_head, max_length_1, max_length_2), dtype = np.float32)
        
    if key_seq_lengths is not None:
        assert mb_size == len(key_seq_lengths)
        assert min(key_seq_lengths) > 0
        assert max(key_seq_lengths) <= max_length_2
        for num_batch, length in enumerate(key_seq_lengths):
            mask[num_batch, :, :, length:] = mask_value

    return mask 
開發者ID:fabiencro,項目名稱:knmt,代碼行數:24,代碼來源:utils.py

示例4: tri

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import tri [as 別名]
def tri(N, M=None, k=0, dtype=None):  # pylint: disable=invalid-name,missing-docstring
  M = M if M is not None else N
  if dtype is not None:
    dtype = utils.result_type(dtype)
  else:
    dtype = dtypes.default_float_type()

  if k < 0:
    lower = -k - 1
    if lower > N:
      r = tf.zeros([N, M], dtype)
    else:
      # Keep as tf bool, since we create an upper triangular matrix and invert
      # it.
      o = tf.ones([N, M], dtype=tf.bool)
      r = tf.cast(tf.math.logical_not(tf.linalg.band_part(o, lower, -1)), dtype)
  else:
    o = tf.ones([N, M], dtype)
    if k > M:
      r = o
    else:
      r = tf.linalg.band_part(o, -1, k)
  return utils.tensor_to_ndarray(r) 
開發者ID:google,項目名稱:trax,代碼行數:25,代碼來源:array_ops.py

示例5: tril

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import tri [as 別名]
def tril(m, k=0):  # pylint: disable=missing-docstring
  m = asarray(m).data
  m_shape = m.shape.as_list()

  if len(m_shape) < 2:
    raise ValueError('Argument to tril must have rank at least 2')

  if m_shape[-1] is None or m_shape[-2] is None:
    raise ValueError('Currently, the last two dimensions of the input array '
                     'need to be known.')

  z = tf.constant(0, m.dtype)

  mask = tri(*m_shape[-2:], k=k, dtype=bool)
  return utils.tensor_to_ndarray(
      tf.where(tf.broadcast_to(mask, tf.shape(m)), m, z)) 
開發者ID:google,項目名稱:trax,代碼行數:18,代碼來源:array_ops.py

示例6: triu

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import tri [as 別名]
def triu(m, k=0):  # pylint: disable=missing-docstring
  m = asarray(m).data
  m_shape = m.shape.as_list()

  if len(m_shape) < 2:
    raise ValueError('Argument to triu must have rank at least 2')

  if m_shape[-1] is None or m_shape[-2] is None:
    raise ValueError('Currently, the last two dimensions of the input array '
                     'need to be known.')

  z = tf.constant(0, m.dtype)

  mask = tri(*m_shape[-2:], k=k - 1, dtype=bool)
  return utils.tensor_to_ndarray(
      tf.where(tf.broadcast_to(mask, tf.shape(m)), z, m)) 
開發者ID:google,項目名稱:trax,代碼行數:18,代碼來源:array_ops.py

示例7: tri

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import tri [as 別名]
def tri(N, M=None, k=0, dtype=float):
    """Creates an array with ones at and below the given diagonal.

    Args:
        N (int): Number of rows.
        M (int): Number of columns. M == N by default.
        k (int): The sub-diagonal at and below which the array is filled. Zero
            is the main diagonal, a positive value is above it, and a negative
            value is below.
        dtype: Data type specifier.

    Returns:
        cupy.ndarray: An array with ones at and below the given diagonal.

    .. seealso:: :func:`numpy.tri`

    """
    if M is None:
        M = N
    out = cupy.empty((N, M), dtype=dtype)

    return _tri_kernel(M, k, out) 
開發者ID:cupy,項目名稱:cupy,代碼行數:24,代碼來源:matrix.py

示例8: tril

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import tri [as 別名]
def tril(m, k=0):
    """Returns a lower triangle of an array.

    Args:
        m (array-like): Array or array-like object.
        k (int): The diagonal above which to zero elements. Zero is the main
            diagonal, a positive value is above it, and a negative value is
            below.

    Returns:
        cupy.ndarray: A lower triangle of an array.

    .. seealso:: :func:`numpy.tril`

    """
    m = cupy.asarray(m)
    mask = tri(*m.shape[-2:], k=k, dtype=bool)

    return cupy.where(mask, m, m.dtype.type(0)) 
開發者ID:cupy,項目名稱:cupy,代碼行數:21,代碼來源:matrix.py

示例9: _ones_matrix_band_part

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import tri [as 別名]
def _ones_matrix_band_part(rows: int, cols: int, num_lower: int, num_upper: int,
                           out_shape: Optional[Tuple[int, ...]] = None) \
        -> torch.Tensor:
    r"""Matrix band part of ones.
    """
    if num_lower < 0:
        num_lower = rows - 1
    if num_upper < 0:
        num_upper = cols - 1
    lower_mask = np.tri(cols, rows, num_lower).T
    upper_mask = np.tri(rows, cols, num_upper)
    band = np.ones((rows, cols)) * lower_mask * upper_mask
    if out_shape:
        band = band.reshape(out_shape)
    band = torch.as_tensor(band, dtype=torch.float32)
    return band 
開發者ID:asyml,項目名稱:texar-pytorch,代碼行數:18,代碼來源:transformer_attentions.py

示例10: _ones_matrix_band_part

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import tri [as 別名]
def _ones_matrix_band_part(rows, cols, num_lower, num_upper,
    out_shape=None):
    """Matrix band part of ones.
    """
    if all([isinstance(el, int) for el in [rows, cols, num_lower,
        num_upper]]):
        # Needed info is constant, so we construct in numpy
        if num_lower < 0:
            num_lower = rows - 1
        if num_upper < 0:
            num_upper = cols - 1
        lower_mask = np.tri(cols, rows, num_lower).T
        upper_mask = np.tri(rows, cols, num_upper)
        band = np.ones((rows, cols)) * lower_mask * upper_mask
        if out_shape:
            band = band.reshape(out_shape)
        band = tf.constant(band, tf.float32)
    else:
        band = tf.matrix_band_part(tf.ones([rows, cols]),
                                   tf.cast(num_lower, tf.int64),
                                   tf.cast(num_upper, tf.int64))
        if out_shape:
            band = tf.reshape(band, out_shape)
    return band 
開發者ID:asyml,項目名稱:texar,代碼行數:26,代碼來源:transformer_attentions.py

示例11: test_euclidean_pdist

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import tri [as 別名]
def test_euclidean_pdist(self):
        a = np.arange(12, dtype=float).reshape(4, 3)
        out = np.empty((a.shape[0] * (a.shape[0] - 1) // 2,), dtype=a.dtype)
        umt.euclidean_pdist(a, out)
        b = np.sqrt(np.sum((a[:, None] - a)**2, axis=-1))
        b = b[~np.tri(a.shape[0], dtype=bool)]
        assert_almost_equal(out, b)
        # An output array is required to determine p with signature (n,d)->(p)
        assert_raises(ValueError, umt.euclidean_pdist, a) 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:11,代碼來源:test_ufunc.py

示例12: get_corr_columns

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import tri [as 別名]
def get_corr_columns(df: pd.DataFrame, threshold: float = 0.98) -> list:
    c = df.corr().abs()
    c: pd.DataFrame = c * np.tri(c.shape[0], c.shape[1], -1)
    c = c.transpose()
    return [col for col in c.columns if any(c[col] > threshold)] 
開發者ID:IBM,項目名稱:AIX360,代碼行數:7,代碼來源:feature_binarizer_from_trees_demo.py

示例13: test_euclidean_pdist

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import tri [as 別名]
def test_euclidean_pdist(self):
        a = np.arange(12, dtype=np.float).reshape(4, 3)
        out = np.empty((a.shape[0] * (a.shape[0] - 1) // 2,), dtype=a.dtype)
        umt.euclidean_pdist(a, out)
        b = np.sqrt(np.sum((a[:, None] - a)**2, axis=-1))
        b = b[~np.tri(a.shape[0], dtype=bool)]
        assert_almost_equal(out, b)
        # An output array is required to determine p with signature (n,d)->(p)
        assert_raises(ValueError, umt.euclidean_pdist, a) 
開發者ID:abhisuri97,項目名稱:auto-alt-text-lambda-api,代碼行數:11,代碼來源:test_ufunc.py

示例14: ones_matrix_band_part

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import tri [as 別名]
def ones_matrix_band_part(rows, cols, num_lower, num_upper, out_shape=None):
  """Matrix band part of ones.

  Args:
    rows: int determining number of rows in output
    cols: int
    num_lower: int, maximum distance backward. Negative values indicate
      unlimited.
    num_upper: int, maximum distance forward. Negative values indicate
      unlimited.
    out_shape: shape to reshape output by.

  Returns:
    Tensor of size rows * cols reshaped into shape out_shape.
  """
  if all([isinstance(el, int) for el in [rows, cols, num_lower, num_upper]]):
    # Needed info is constant, so we construct in numpy
    if num_lower < 0:
      num_lower = rows - 1
    if num_upper < 0:
      num_upper = cols - 1
    lower_mask = np.tri(cols, rows, num_lower).T
    upper_mask = np.tri(rows, cols, num_upper)
    band = np.ones((rows, cols)) * lower_mask * upper_mask
    if out_shape:
      band = band.reshape(out_shape)
    band = tf.constant(band, tf.float32)
  else:
    band = tf.linalg.band_part(
        tf.ones([rows, cols]), tf.cast(num_lower, tf.int64),
        tf.cast(num_upper, tf.int64))
    if out_shape:
      band = tf.reshape(band, out_shape)

  return band 
開發者ID:tensorflow,項目名稱:tensor2tensor,代碼行數:37,代碼來源:common_layers.py

示例15: ones_matrix_band_part

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import tri [as 別名]
def ones_matrix_band_part(rows, cols, num_lower, num_upper, out_shape=None):
  """Matrix band part of ones.

  Args:
    rows: int determining number of rows in output
    cols: int
    num_lower: int, maximum distance backward. Negative values indicate
      unlimited.
    num_upper: int, maximum distance forward. Negative values indicate
      unlimited.
    out_shape: shape to reshape output by.

  Returns:
    Tensor of size rows * cols reshaped into shape out_shape.
  """
  if all([isinstance(el, int) for el in [rows, cols, num_lower, num_upper]]):
    # Needed info is constant, so we construct in numpy
    if num_lower < 0:
      num_lower = rows - 1
    if num_upper < 0:
      num_upper = cols - 1
    lower_mask = np.tri(cols, rows, num_lower).T
    upper_mask = np.tri(rows, cols, num_upper)
    band = np.ones((rows, cols)) * lower_mask * upper_mask
    if out_shape:
      band = band.reshape(out_shape)
    band = tf.constant(band, tf.float32)
  else:
    band = tf.matrix_band_part(
        tf.ones([rows, cols]), tf.cast(num_lower, tf.int64),
        tf.cast(num_upper, tf.int64))
    if out_shape:
      band = tf.reshape(band, out_shape)

  return band 
開發者ID:yyht,項目名稱:BERT,代碼行數:37,代碼來源:common_layers.py


注:本文中的numpy.tri方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。