在张量f中用0和1交替初始化矩阵

2024-03-29 10:19:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图创建一个0和1的n×m矩阵,结构非常简单:

[[1 0 0 0 0 0 0 ...],
[1 1 0 0 0 0 0 ...],
[1 1 1 0 0 0 0 ...],
[1 1 1 1 0 0 0 ...],
[0 1 1 1 1 0 0 ...],
[0 1 1 1 1 1 0 ...],
...
[... 0 0 0 1 1 1 1],
[... 0 0 0 0 1 1 1],
[... 0 0 0 0 0 1 1],
[... 0 0 0 0 0 0 1]]

但是,我不想开始编写循环,因为这可能是通过使用内置的东西来实现的:A = tf.constant(???,shape(n,m))

请注意,在前3行之后,只需重复4个1,然后是m-30,直到最后3行。你知道吗

所以我在想一些重复的东西,但我不知道该用什么语法。你知道吗


Tags: tf语法矩阵结构内置shapeconstant
1条回答
网友
1楼 · 发布于 2024-03-29 10:19:07

你在找^{}。根据说明书,它的功能是

Copy a tensor setting everything outside a central band in each innermost matrix to zero.

所以在你的例子中,你要用1创建一个矩阵,然后取一个4-宽的频带,像这样:

tf.matrix_band_part( tf.ones( shape = ( 1, n, m ) ), 3, 0 )

测试代码:

import tensorflow as tf

x = tf.ones( shape = ( 1, 9, 6 ) )
y = tf.matrix_band_part( x, 3, 0 )

with tf.Session() as sess:
    res = sess.run( y )
    print ( res )

输出:

[[[1. 0. 0. 0. 0. 0.]
[1. 1. 0. 0. 0. 0.]
[1. 1. 1. 0. 0. 0.]
[1. 1. 1. 1. 0. 0.]
[0. 1. 1. 1. 1. 0.]
[0. 0. 1. 1. 1. 1.]
[0. 0. 0. 1. 1. 1.]
[0. 0. 0. 0. 1. 1.]
[0. 0. 0. 0. 0. 1.]]]

相关问题 更多 >