torch.logical_not
function logical_not<S extends Shape, D extends DType = DType, Dev extends DeviceType = DeviceType>(input: Tensor<S, D, Dev>): Tensor<S, 'bool', Dev>Computes the element-wise logical NOT (negation).
Inverts boolean values: true becomes false, false becomes true. Any non-zero value is treated as true, zero as false. Essential for:
- Inverting masks or conditions (negate a selection mask)
- Filtering: find elements NOT matching a condition
- Boolean algebra: applying De Morgan's laws in complex conditions
- Negating comparison results (opposite of ==, >, <, etc.)
- Conditional logic: implementing "if not" branches
- Masking: finding invalid/missing data (invert valid_mask)
- Boolean output: Always returns boolean dtype regardless of input type
- Zero is false: In numerical tensors, 0.0 is treated as false, any other value as true
- No broadcasting needed: Single-argument operation, same shape as input
- Idempotent: NOT(NOT(x)) = x (double negation cancels)
- Used in masking: Often combined with where() or indexing for conditional selection
- Type coercion: All dtypes converted to boolean - loss of numeric information
- Not differentiable: Boolean operations don't support autograd
Parameters
inputTensor<S, D, Dev>- Input tensor (any dtype and shape; truthy/falsy value conversion applied)
Returns
Tensor<S, 'bool', Dev>– Boolean tensor with same shape as input; True where input is zero/false, False otherwiseExamples
// Basic negation: invert boolean mask
const mask = torch.tensor([true, false, true, false]);
torch.logical_not(mask); // [false, true, false, true]// Invert comparison result
const predictions = torch.tensor([1, 2, 3, 4, 5]);
const is_less_than_3 = torch.lt(predictions, 3); // [true, true, false, false, false]
const is_not_less_than_3 = torch.logical_not(is_less_than_3); // [false, false, true, true, true]// Find invalid/missing data by inverting valid mask
const valid_mask = torch.tensor([true, true, false, true, false]);
const invalid_mask = torch.logical_not(valid_mask); // [false, false, true, false, true]
const invalid_indices = torch.where(invalid_mask); // Get positions of invalid data// Numerical input: non-zero is treated as true
const values = torch.tensor([0, 1, -5, 2.5, 0.0]);
torch.logical_not(values);
// [true, false, false, false, true] - only zeros become true// De Morgan's law: NOT(A OR B) = (NOT A) AND (NOT B)
const a = torch.tensor([true, true, false, false]);
const b = torch.tensor([true, false, true, false]);
const not_a_or_b = torch.logical_not(torch.logical_or(a, b));
const not_a_and_not_b = torch.logical_and(torch.logical_not(a), torch.logical_not(b));
// Both give [false, false, false, true]See Also
- PyTorch torch.logical_not(input)
- where - Conditional selection based on logical results
- logical_and - AND operation for combining conditions
- logical_or - OR operation for combining conditions
- logical_xor - XOR operation for exclusive conditions