Python numpy.tri() Examples
The following are 30
code examples of numpy.tri().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
numpy
, or try the search function
.
Example #1
Source File: transformer_attentions.py From Counterfactual-StoryRW with MIT License | 6 votes |
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
Example #2
Source File: utils.py From knmt with GNU General Public License v3.0 | 6 votes |
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
Example #3
Source File: common_layers.py From fine-lm with MIT License | 6 votes |
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
Example #4
Source File: matrix.py From cupy with MIT License | 6 votes |
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))
Example #5
Source File: matrix.py From cupy with MIT License | 6 votes |
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)
Example #6
Source File: transformer_attentions.py From texar-pytorch with Apache License 2.0 | 6 votes |
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
Example #7
Source File: transformer_attentions.py From texar with Apache License 2.0 | 6 votes |
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
Example #8
Source File: array_ops.py From trax with Apache License 2.0 | 6 votes |
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)
Example #9
Source File: array_ops.py From trax with Apache License 2.0 | 6 votes |
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))
Example #10
Source File: array_ops.py From trax with Apache License 2.0 | 6 votes |
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))
Example #11
Source File: model_helper.py From BERT_TF with Apache License 2.0 | 5 votes |
def create_lr_mask(batch_size, input_length): """as input length changes, could not use placeholder to create triangle matrix in tensorflow, cause tensorflow does not support create triangle matrix. """ # triangle_matrix = np.tile( # np.tri(input_length, input_length, 0, dtype=np.float), # [batch_size, 1, 1]) # mask = tf.cast(triangle_matrix, dtype=tf.float32) triangle_matrix = np.tri(input_length, input_length, 0, dtype=np.float) return triangle_matrix
Example #12
Source File: matrix.py From cupy with MIT License | 5 votes |
def triu(m, k=0): """Returns an upper triangle of an array. Args: m (array-like): Array or array-like object. k (int): The diagonal below which to zero elements. Zero is the main diagonal, a positive value is above it, and a negative value is below. Returns: cupy.ndarray: An upper triangle of an array. .. seealso:: :func:`numpy.triu` """ m = cupy.asarray(m) mask = tri(*m.shape[-2:], k=k-1, dtype=bool) return cupy.where(mask, m.dtype.type(0), m) # TODO(okuta): Implement vander # TODO(okuta): Implement mat # TODO(okuta): Implement bmat
Example #13
Source File: utils.py From factor_analyzer with GNU General Public License v2.0 | 5 votes |
def fill_lower_diag(x): """ Fill the lower diagonal of a square matrix, given a 1d input array. Parameters ---------- x : array-like The flattened input matrix that will be used to fill the lower diagonal of the square matrix. Returns ------- out : numpy array The output square matrix, with the lower diagonal filled by x. Reference --------- [1] https://stackoverflow.com/questions/51439271/ convert-1d-array-to-lower-triangular-matrix """ x = np.array(x) x = x if len(x.shape) == 1 else np.squeeze(x, axis=1) n = int(np.sqrt(len(x) * 2)) + 1 out = np.zeros((n, n), dtype=float) out[np.tri(n, dtype=bool, k=-1)] = x return out
Example #14
Source File: test_ufunc.py From elasticintel with GNU General Public License v3.0 | 5 votes |
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)
Example #15
Source File: PSD.py From newton_admm with Apache License 2.0 | 5 votes |
def X_to_vec(X): n = X.shape[0] return X.T[np.tri(n, dtype=np.bool).T]
Example #16
Source File: PSD.py From newton_admm with Apache License 2.0 | 5 votes |
def vec_to_X(v_X): n = int(math.sqrt(2 * len(v_X))) if len(v_X) != n * (n + 1) / 2: raise ValueError( "v_X is not the right shape for a vectorized lower triangular matrix. Tried to turn vector of size {} into matrix with width {} ".format(len(v_X), n)) Y = np.zeros((n, n)) Y[np.tri(n, dtype=np.bool).T] = v_X return Y + np.triu(Y, 1).T
Example #17
Source File: PSD.py From newton_admm with Apache License 2.0 | 5 votes |
def J(v_X): X = vec_to_X(v_X) n = X.shape[0] # perform scaling _i = tuple(range(n)) X[_i, _i] *= _sqrt2 Lam, U = np.linalg.eigh(X) idx = np.argsort(Lam) Lam = Lam[idx] U = U[:, idx] L = np.diag(Lam) L_max = np.maximum(L, 0.0) dU_dX, dL_dX = dU_dL_dX(Lam, U) dL_max_dX = dL_dX.copy() for i, l in enumerate(Lam): if l < 0: dL_max_dX[i, :, :] = 0 t1 = dot(U.dot(L_max), np.rollaxis(dU_dX, 1, 0)) t2 = np.rollaxis(t1, 1, 0) t3 = np.rollaxis(dot(multiply_diag(U, dL_max_dX), U.T, (1, 0)), 3, 1) idx = np.nonzero(np.tri(n, dtype=np.bool).T) W = t1 + t2 + t3 # rescale jacobian W[:, :, _i, _i] *= _sqrt2 W[_i, _i, :, :] /= _sqrt2 return W[idx[0], idx[1]][:, idx[0], idx[1]]
Example #18
Source File: test_ufunc.py From coffeegrindsize with MIT License | 5 votes |
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)
Example #19
Source File: test_distribution_inference.py From gluon-ts with Apache License 2.0 | 5 votes |
def test_multivariate_gaussian(hybridize: bool) -> None: num_samples = 2000 dim = 2 mu = np.arange(0, dim) / float(dim) L_diag = np.ones((dim,)) L_low = 0.1 * np.ones((dim, dim)) * np.tri(dim, k=-1) L = np.diag(L_diag) + L_low Sigma = L.dot(L.transpose()) distr = MultivariateGaussian(mu=mx.nd.array(mu), L=mx.nd.array(L)) samples = distr.sample(num_samples) mu_hat, L_hat = maximum_likelihood_estimate_sgd( MultivariateGaussianOutput(dim=dim), samples, init_biases=None, # todo we would need to rework biases a bit to use it in the multivariate case hybridize=hybridize, learning_rate=PositiveFloat(0.01), num_epochs=PositiveInt(10), ) distr = MultivariateGaussian( mu=mx.nd.array([mu_hat]), L=mx.nd.array([L_hat]) ) Sigma_hat = distr.variance[0].asnumpy() assert np.allclose( mu_hat, mu, atol=0.1, rtol=0.1 ), f"mu did not match: mu = {mu}, mu_hat = {mu_hat}" assert np.allclose( Sigma_hat, Sigma, atol=0.1, rtol=0.1 ), f"Sigma did not match: sigma = {Sigma}, sigma_hat = {Sigma_hat}"
Example #20
Source File: macro_CNN.py From nnabla-examples with Apache License 2.0 | 5 votes |
def arc_to_matrix(connect_patterns): """ Creates matrix which represents the connection info between layers. if the matrix[i,j] = 1, (i - 1)th and jth layers are connected. note that (-1)st layer means stem conv cell. """ mat_size = len(connect_patterns) # use triangular matrix. connection_matrix = np.tri(mat_size, dtype=np.int8) for i in range(mat_size): connect_pattern = connect_patterns[i] connection_matrix[i, :len(connect_pattern)] = connect_pattern return connection_matrix
Example #21
Source File: test_ufunc.py From Serverless-Deep-Learning-with-TensorFlow-and-AWS-Lambda with MIT License | 5 votes |
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)
Example #22
Source File: test_ufunc.py From twitter-stock-recommendation with MIT License | 5 votes |
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)
Example #23
Source File: test_ufunc.py From keras-lambda with MIT License | 5 votes |
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)
Example #24
Source File: bottom_up.py From Bottom-up-Clustering-Person-Re-identification with MIT License | 5 votes |
def calculate_distance(self,u_feas): # calculate distance between features x = torch.from_numpy(u_feas) y = x m = len(u_feas) dists = torch.pow(x, 2).sum(dim=1, keepdim=True).expand(m, m) + \ torch.pow(y, 2).sum(dim=1, keepdim=True).expand(m, m).t() dists.addmm_(1, -2, x, y.t()) return dists # def select_merge_data(self, u_feas, nums_to_merge, label, label_to_images, ratio_n, dists): # #calculate final distance (feature distance + diversity regularization) # tri = np.tri(len(u_feas), dtype=np.float32) # tri = tri * np.iinfo(np.int32).max # tri = tri.astype('float32') # tri = torch.from_numpy(tri) # dists = dists + tri # for idx in range(len(u_feas)): # for j in range(idx + 1, len(u_feas)): # if label[idx] == label[j]: # dists[idx, j] = np.iinfo(np.int32).max # else: # dists[idx][j] = dists[idx][j] + \ # + ratio_n * ((len(label_to_images[label[idx]])) + (len(label_to_images[label[j]]))) # dists = dists.numpy() # ind = np.unravel_index(np.argsort(dists, axis=None), dists.shape) # idx1 = ind[0] # idx2 = ind[1] # return idx1, idx2
Example #25
Source File: common_layers.py From training_results_v0.5 with Apache License 2.0 | 5 votes |
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
Example #26
Source File: test_ufunc.py From recruit with Apache License 2.0 | 5 votes |
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)
Example #27
Source File: feature_binarizer_from_trees_demo.py From AIX360 with Apache License 2.0 | 5 votes |
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)]
Example #28
Source File: test_ufunc.py From auto-alt-text-lambda-api with MIT License | 5 votes |
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)
Example #29
Source File: common_layers.py From tensor2tensor with Apache License 2.0 | 5 votes |
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
Example #30
Source File: test_ufunc.py From vnpy_crypto with MIT License | 5 votes |
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)