我有以下数组:-
import numpy as np
import tensorflow as tf
input = np.array([[-1.5, 1.0, 3.4, .5], [0.0, 3.0, 1.3, 0.0]])
layer = tf.keras.layers.Discretization(num_bins=2, epsilon=0.01)
layer.adapt(input)
layer(input)
<tf.Tensor: shape=(2, 4), dtype=int64, numpy=
array([[0, 1, 1, 1],
[0, 1, 1, 0]])>这就分散了整个张量。我想知道是否有一种方法可以让第二个数组在张量中离散。
发布于 2022-10-19 16:24:02
我们可以根据需要离散化的数组的索引创建一个掩码:
def get_mask(x, array_index):
x = tf.Variable(tf.ones_like(input, dtype=tf.float32))
indices = tf.Variable(array_index, dtype=tf.int32)
updates = tf.Variable(tf.zeros( (indices.shape[0], x.shape[1])), dtype=tf.float32)
return tf.compat.v1.scatter_nd_update(x, indices, updates)打电话
> mask = get_mask(input, np.array([[1]])) #second array
>
> returns the mask of:
array([[1., 1., 1., 1.],
[0., 0., 0., 0.]])然后我们可以应用掩码:tf.cast(layer(input), tf.float32) * (1-mask) + input*mask,它返回:
array([[-1.5, 1. , 3.4, 0.5],
[ 0. , 1. , 1. , 0. ]]上面的内容应该适用于任何数组和任何数组索引来离散化。
https://stackoverflow.com/questions/74111551
复制相似问题