简体   繁体   English

在TensorFlow中以0和1交替初始化矩阵

[英]Initializing a matrix with alternating 0s and 1s in TensorFlow

I am trying to create an n-by-m matrix of 0s and 1s with a very simple structure: 我试图用一个非常简单的结构创建一个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]]

However, I don't want to start writing loops as this is probably achievable using something built in: A = tf.constant(???,shape(n,m)) 但是,我不想开始编写循环,因为使用内置的东西可能可以实现: A = tf.constant(???,shape(n,m))

Note that after the first 3 rows there is simply a repetition of four 1s, followed by m-3 0s, until the last 3 rows. 请注意,在前3行之后,仅重复了4个1,接着是m-3 0,直到最后3行。

So I am thinking something along the lines of a repeat of repeat, but I have no idea what syntax to use. 所以我在考虑重复重复的过程,但是我不知道要使用什么语法。

You're looking for tf.matrix_band_part() . 您正在寻找tf.matrix_band_part() As per the manual, it's function is to 按照手册,它的功能是

Copy a tensor setting everything outside a central band in each innermost matrix to zero. 复制一个张量,将每个最内部矩阵的中心带之外的所有内容都设置为零。

So in your case you'd create a matrix with ones, and then take a 4-wide band like this: 因此,在您的情况下,您将创建一个带矩阵的矩阵,然后采用如下所示的4倍带宽:

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

Tested code: 经过测试的代码:

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 )

Output: 输出:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM