gpt4 book ai didi

python - tensorflow 2中单个矩阵的按位运算

转载 作者:行者123 更新时间:2023-12-01 06:36:04 30 4
gpt4 key购买 nike

假设我有一个矩阵

M = np.array([
[0, 1, 0, 0, 0],
[1, 0, 1, 1, 1],
[1, 1, 1, 1, 1],
[0, 1, 1, 0, 1],
], dtype=np.int32)

我想对所有行进行按位运算(例如 bitwise_and)。

在 numpy 中我可以这样做:

res = np.bitwise_and.reduce(M, axis=1)
print(res)

我怎样才能在 tensorflow 中做同样的事情?目前我是这样做的:

tensor = tf.Variable(M)
res = tensor[:, 0]
for i in range(1, M.shape[1]):
res = tf.bitwise.bitwise_and(res, tensor[:, i])
print(res.numpy())

我想避免这个循环。

最佳答案

您可以通过像tf.reduce_all这样的归约操作来做到这一点:

import tensorflow as tf

tensor = tf.constant([[True, False, True], [False, True, False], [True, True, True]])
res = tf.reduce_all(tensor, axis=1)
print(res.numpy())
# [False False True]
<小时/>

编辑:如果您特别想要按位运算(即您的输入不是二进制),那么我认为没有减少操作,但您可以使用 tf.scan 执行类似的操作(虽然可能不会那么快):

import tensorflow as tf

tensor = tf.constant([
[0, 1, 2],
[3, 6, 7],
], dtype=tf.int32)
# Put reduction dimension first
tensor_t = tf.transpose(tensor)
# Compute cumulative bitwise and
res_cum = tf.scan(tf.bitwise.bitwise_and, tensor_t)
# The last result is the total reduction
res = res_cum[-1]
print(res.numpy())
# [0 2]

关于python - tensorflow 2中单个矩阵的按位运算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59663221/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com