张量流2中单个矩阵的按位运算
Bitwise operation on single matrix in tensorflow 2
假设我有一个矩阵
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]
假设我有一个矩阵
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]