我需要生成一个不同阶跃函数的二维张量,其中
shape (20) with k=5
的阶跃函数是以下张量
[1,1,1,1,1,0,0,...0]
(k是个数)
我的张量的每个阶跃函数都具有不同的k,目前我迭代生成2d输出过滤器
这是我的代码:
# built 20 step functions, each with 10 variables, initializing k=5
weight_param = tf.Variable(np.full((20), 5), dtype=tf.int32)
kernel_filter = tf.Variable(tf.zeros((10,20),trainable=False)
for i in range(20):
shape_ones = 20 - weight_param[i]
shape_zeros = weight_param[i]
kernel_filter[:, i] = kernel_filter[:, i].assign(tf.concat([tf.ones(shape_ones, dtype=tf.float32), tf.zeros(shape_zeros, dtype=tf.float32)], axis=-1))
答案 0 :(得分:2)
您可以使用tf.sequence_mask
来实现。它返回代表每个单元格前N个位置的掩码张量。
import tensorflow as tf
import numpy as np
weight_param = tf.Variable(np.random.randint(0,20,size=20), dtype=tf.int32)
kernel_filter = tf.sequence_mask(20-weight_param, 10,dtype=tf.int32)
kernel_filter = tf.transpose(kernel_filter)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
print(sess.run(weight_param))
print(sess.run(kernel_filter))
#print
[17 2 13 9 15 19 19 8 19 0 14 1 12 5 5 13 16 6 10 0]
[[1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1]
[1 1 1 1 1 0 0 1 0 1 1 1 1 1 1 1 1 1 1 1]
[1 1 1 1 1 0 0 1 0 1 1 1 1 1 1 1 1 1 1 1]
[0 1 1 1 1 0 0 1 0 1 1 1 1 1 1 1 1 1 1 1]
[0 1 1 1 1 0 0 1 0 1 1 1 1 1 1 1 0 1 1 1]
[0 1 1 1 0 0 0 1 0 1 1 1 1 1 1 1 0 1 1 1]
[0 1 1 1 0 0 0 1 0 1 0 1 1 1 1 1 0 1 1 1]
[0 1 0 1 0 0 0 1 0 1 0 1 1 1 1 0 0 1 1 1]
[0 1 0 1 0 0 0 1 0 1 0 1 0 1 1 0 0 1 1 1]
[0 1 0 1 0 0 0 1 0 1 0 1 0 1 1 0 0 1 1 1]]