TensorFlow ``bitwise_and`` 按位与函数使用


发布日期 : 2024-10-28 03:20:43 UTC

访问量: 10 次浏览

Python – Tensorflow bitwise.bitwise\_and() 方法

Tensorflow bitwise.bitwise\_and() 方法执行 bitwise\_and 操作,并返回那些在a和b中都被设置(1)的位。

该方法属于比特模块。

语法:

tf.bitwise.bitwise_and( a, b, name=None)

参数

  • a:这必须是一个张量。它应该是以下类型之一:int8, int16, int32, int64, uint8, uint16, uint32, uint64。
  • b:这也应该是一个张量,类型与a相同。
  • name: 这是一个可选的参数,这是操作的名称。

返回:
它返回一个与a和b具有相同类型的张量。

让我们借助几个例子来看看这个概念。

示例 1:

# Importing the Tensorflow library 
import tensorflow as tf 

# A constant a and b
a = tf.constant(4, dtype = tf.int32)
b = tf.constant(6, dtype = tf.int32)  

# Applying the bitwise_and() function 
# storing the result in 'c' 
c = tf.bitwise.bitwise_and(a, b) 

# Initiating a Tensorflow session 
with tf.Session() as sess:
    print("Input 1", a)
    print(sess.run(a))
    print("Input 2", b)
    print(sess.run(b))
    print("Output: ", c)
    print(sess.run(c))

输出:

Input 1 Tensor("Const_41:0", shape=(), dtype=int32)
4
Input 2 Tensor("Const_42:0", shape=(), dtype=int32)
6
Output: Tensor("BitwiseAnd_5:0", shape=(), dtype=int32)
4

示例 2:

# Importing the Tensorflow library 
import tensorflow as tf 

# A constant a and b
a = tf.constant([1, 2, 7], dtype = tf.int32)
b = tf.constant([1, 5, 8], dtype = tf.int32)  

# Applying the bitwise_and() function 
# storing the result in 'c' 
c = tf.bitwise.bitwise_and(a, b) 

# Initiating a Tensorflow session 
with tf.Session() as sess:
    print("Input 1", a)
    print(sess.run(a))
    print("Input 2", b)
    print(sess.run(b))
    print("Output: ", c)
    print(sess.run(c))

输出:

Input 1 Tensor("Const_43:0", shape=(3, ), dtype=int32)
[1 2 7]
Input 2 Tensor("Const_44:0", shape=(3, ), dtype=int32)
[1 5 8]
Output: Tensor("BitwiseAnd_6:0", shape=(3, ), dtype=int32)
[1 0 0]