tensorflow 取上(下)三角矩阵 tf.linalg.band_part

提示:tensorflow 可从已有矩阵中取三角矩阵,也可用于生成为1的三角矩阵。

函数说明


tf.linalg.band_part(
    input,
    num_lower,
    num_upper,
    name=None
)

作用:
        以对角线为中心,取它的副对角线部分,其他部分用0填充。副对角线,即矩阵中除了            主对角线以外的其它对角线。

参数:

        input:输入的张量。
        num_lower:下三角矩阵保留的副对角线数量,取值为负数时全部保留,为0时全为0。
        num_upper:上三角矩阵保留的副对角线数量,取值为负数时全部保留,为0时全为0。

示例

示例1

==========代码==========
import tensorflow as tf
tf.enable_eager_execution()
a=tf.constant( [[1,  2,  3, 4],
				[5,  6,  7, 8],
				[9, 10,  11,12],
                [13, 14, 15,16]],dtype=tf.float32)
b=tf.linalg.band_part(a,2,0)
print(b)

==========output==========
tf.Tensor(
[[ 1.  0.  0.  0.]
 [ 5.  6.  0.  0.]
 [ 9.  10. 11. 0.]
 [ 0. 14. 15. 16.]], shape=(4, 4), dtype=float32)

示例2

==========代码==========
import tensorflow as tf
tf.enable_eager_execution()
a=tf.constant( [[1,  2,  3, 4],
				[5,  6,  7, 8],
				[9, 10,  11,12],
                [13, 14, 15,16]],dtype=tf.float32)
c=tf.linalg.band_part(a,1,1)
print(c)

==========output==========
tf.Tensor(
[[ 1.  2.  0.  0.]
 [ 5.  6.  7.  0.]
 [ 0.  10. 11. 12.]
 [ 0.  0.  15. 16.]], shape=(4, 4), dtype=float32)

示例3

==========代码==========
import tensorflow as tf
tf.enable_eager_execution()
a=tf.constant( [[1,  2,  3, 4],
				[5,  6,  7, 8],
				[9, 10,  11,12],
                [13, 14, 15,16]],dtype=tf.float32)
d=tf.linalg.band_part(a,-1,0)
print(d)

==========output==========
tf.Tensor(
[[ 1.  0.  0.  0.]
 [ 5.  6.  0.  0.]
 [ 9.  10. 11. 0.]
 [ 13. 14. 15. 16.]], shape=(4, 4), dtype=float32)

示例4

==========代码==========
import tensorflow as tf
e = tf.linalg.band_part(tf.ones((5,5)),-1,0)
print(e)

==========output==========
array([[1., 0., 0., 0., 0.],
       [1., 1., 0., 0., 0.],
       [1., 1., 1., 0., 0.],
       [1., 1., 1., 1., 0.],
       [1., 1., 1., 1., 1.]], dtype=float32)

你可能感兴趣的:(深度学习,python,机器学习,tensorflow,深度学习,矩阵)