當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Python tf.bitwise.invert用法及代碼示例

反轉(翻轉)支持類型的每一位;例如,類型 uint8 值 01010101 變為 10101010。

用法

tf.bitwise.invert(
    x, name=None
)

參數

  • x 一個Tensor。必須是以下類型之一:int8 , int16 , int32 , int64 , uint8 , uint16 , uint32 , uint64
  • name 操作的名稱(可選)。

返回

  • 一個Tensor。具有與 x 相同的類型。

翻轉每一位支持的類型。例如,類型 int8 (decimal 2) binary 00000010 變為 (decimal -3) binary 11111101。此操作對張量參數 x 的每個元素執行。

例子:

import tensorflow as tf
from tensorflow.python.ops import bitwise_ops

# flip 2 (00000010) to -3 (11111101)
tf.assert_equal(-3, bitwise_ops.invert(2))

dtype_list = [dtypes.int8, dtypes.int16, dtypes.int32, dtypes.int64,
              dtypes.uint8, dtypes.uint16, dtypes.uint32, dtypes.uint64]

inputs = [0, 5, 3, 14]
for dtype in dtype_list:
  # Because of issues with negative numbers, let's test this indirectly.
  # 1. invert(a) and a = 0
  # 2. invert(a) or a = invert(0)
  input_tensor = tf.constant([0, 5, 3, 14], dtype=dtype)
  not_a_and_a, not_a_or_a, not_0 = [bitwise_ops.bitwise_and(
                                      input_tensor, bitwise_ops.invert(input_tensor)),
                                    bitwise_ops.bitwise_or(
                                      input_tensor, bitwise_ops.invert(input_tensor)),
                                    bitwise_ops.invert(
                                      tf.constant(0, dtype=dtype))]

  expected = tf.constant([0, 0, 0, 0], dtype=tf.float32)
  tf.assert_equal(tf.cast(not_a_and_a, tf.float32), expected)

  expected = tf.cast([not_0] * 4, tf.float32)
  tf.assert_equal(tf.cast(not_a_or_a, tf.float32), expected)

  # For unsigned dtypes let's also check the result directly.
  if dtype.is_unsigned:
    inverted = bitwise_ops.invert(input_tensor)
    expected = tf.constant([dtype.max - x for x in inputs], dtype=tf.float32)
    tf.assert_equal(tf.cast(inverted, tf.float32), tf.cast(expected, tf.float32))

相關用法


注:本文由純淨天空篩選整理自tensorflow.org大神的英文原創作品 tf.bitwise.invert。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。