首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用TensorFlow只分解张量中的某一列线

用TensorFlow只分解张量中的某一列线
EN

Stack Overflow用户
提问于 2022-10-18 13:09:48
回答 1查看 37关注 0票数 0

我有以下数组:-

代码语言:javascript
复制
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]])>

这就分散了整个张量。我想知道是否有一种方法可以让第二个数组在张量中离散。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-10-19 16:24:02

我们可以根据需要离散化的数组的索引创建一个掩码:

代码语言:javascript
复制
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)

打电话

代码语言:javascript
复制
> 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,它返回:

代码语言:javascript
复制
array([[-1.5,  1. ,  3.4,  0.5],
       [ 0. ,  1. ,  1. ,  0. ]]

上面的内容应该适用于任何数组和任何数组索引来离散化。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74111551

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档