Skip to content

Commit 04dc3f2

Browse files
authored
Merge branch 'main' into isunordered/abey1
2 parents 707ee3d + 1b69ce4 commit 04dc3f2

File tree

2 files changed

+217
-0
lines changed

2 files changed

+217
-0
lines changed
Lines changed: 117 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,117 @@
1+
---
2+
Title: 'byteswap()'
3+
Description: 'Swaps the byte order of each element in a NumPy ndarray.'
4+
Subjects:
5+
- 'Computer Science'
6+
- 'Data Science'
7+
Tags:
8+
- 'Array'
9+
- 'Data'
10+
- 'NumPy'
11+
CatalogContent:
12+
- 'learn-python-3'
13+
- 'paths/data-science'
14+
---
15+
16+
The **`byteswap()`** method reverses the byte order of every element in a NumPy array. This is used when converting data between systems with different endianness (byte-ordering conventions). The operation either returns a new array or modifies the original one in place when `inplace=True`.
17+
18+
## Syntax
19+
20+
```pseudo
21+
ndarray.byteswap(inplace=False)
22+
```
23+
24+
**Parameters:**
25+
26+
- `inplace` (optional): When set to `True`, the byte order of the existing array is swapped in place. When `False`, a new array with swapped bytes is returned.
27+
28+
**Return value:**
29+
30+
Returns a new ndarray with swapped byte order, unless `inplace=True`, in which case the original array is modified and returned.
31+
32+
## Example 1
33+
34+
In this example, the array's byte order is swapped to convert the data into the opposite endianness:
35+
36+
```py
37+
import numpy as np
38+
39+
arr = np.array([1, 256, 1024], dtype=np.int32)
40+
41+
print("Original array:")
42+
print(arr)
43+
print("Original dtype:", arr.dtype)
44+
45+
swapped = arr.byteswap()
46+
47+
print("\nAfter byteswap():")
48+
print(swapped)
49+
print("Swapped dtype:", swapped.dtype)
50+
```
51+
52+
The output of this code is:
53+
54+
```shell
55+
Original array:
56+
[ 1 256 1024]
57+
Original dtype: int32
58+
59+
After byteswap():
60+
[16777216 65536 262144]
61+
Swapped dtype: int32
62+
```
63+
64+
## Example 2
65+
66+
This example demonstrates `byteswap(inplace=True)` and shows how the original data is altered directly:
67+
68+
```py
69+
import numpy as np
70+
71+
arr = np.array([100, 200, 300], dtype=np.int32)
72+
73+
print("Before inplace byteswap:", arr)
74+
75+
arr.byteswap(inplace=True)
76+
77+
print("After inplace byteswap:", arr)
78+
```
79+
80+
The output of this code is:
81+
82+
```shell
83+
Before inplace byteswap: [100 200 300]
84+
After inplace byteswap: [1677721600 -939524096 738263040]
85+
```
86+
87+
## Codebyte Example
88+
89+
Use the codebyte below to inspect how `byteswap()` affects a 2-D array and observe the internal memory representation change:
90+
91+
```codebyte/python
92+
import numpy as np
93+
94+
matrix = np.array([[1, 2], [3, 4]], dtype=np.int16)
95+
96+
print("Original:")
97+
print(matrix)
98+
99+
swapped = matrix.byteswap()
100+
101+
print("\nByteswapped:")
102+
print(swapped)
103+
```
104+
105+
## Frequently Asked Questions
106+
107+
### 1. What is the function of byteswap() in Python?
108+
109+
The `byteswap()` method reverses the byte order of every element in a NumPy array. It is commonly used when preparing data for systems with different endianness or when interpreting binary data from external sources.
110+
111+
### 2. What are bytes and bytearrays in Python?
112+
113+
A `bytes` object in Python is an immutable sequence of byte values, while a bytearray is a mutable version of the same concept. Both store raw binary data and are often used for file handling, networking, and low-level memory operations.
114+
115+
### 3. How to shuffle a NumPy ndarray?
116+
117+
A NumPy array can be shuffled using `np.random.shuffle()` for in-place row-wise shuffling or `np.random.permutation()` to return a shuffled copy. These functions randomize the order of elements while preserving the array’s structure.
Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,100 @@
1+
---
2+
Title: '.logical_or()'
3+
Description: 'Computes the element-wise logical OR between two tensors.'
4+
Subjects:
5+
- 'Computer Science'
6+
- 'Data Science'
7+
Tags:
8+
- 'Booleans'
9+
- 'PyTorch'
10+
- 'Tensor'
11+
CatalogContent:
12+
- 'learn-python-3'
13+
- 'paths/data-science'
14+
---
15+
16+
The **`.logical_or()`** function performs an element-wise logical OR operation between two [tensors](https://www.codecademy.com/resources/docs/pytorch/tensors). Each input value is converted to a Boolean value (zero → `False`, non-zero → `True`) before the operation. The output is a Boolean tensor where each element is `True` if at least one of the corresponding input elements is `True`.
17+
18+
## Syntax
19+
20+
```pseudo
21+
torch.logical_or(input, other, out)
22+
```
23+
24+
**Parameters:**
25+
26+
- `input`: A tensor whose elements are treated as Boolean.
27+
- `other`: A tensor broadcastable with input.
28+
- `out` (optional): A tensor to store the result.
29+
30+
**Return value:**
31+
32+
Returns a Boolean tensor where each element is `True` if at least one of the corresponding input elements is `True`.
33+
34+
## Example 1
35+
36+
In this example, `.logical_or()` evaluates pairs of values from two 2-D tensors and returns a Boolean matrix showing which positions satisfy the OR condition:
37+
38+
```py
39+
import torch
40+
41+
a = torch.tensor([[0, 1], [2, 0]])
42+
b = torch.tensor([[3, 0], [0, 5]])
43+
44+
result = torch.logical_or(a, b)
45+
46+
print("Tensor A:\n", a)
47+
print("\nTensor B:\n", b)
48+
print("\nA OR B:\n", result)
49+
```
50+
51+
The output of this code is:
52+
53+
```shell
54+
Tensor A:
55+
tensor([[0, 1],
56+
[2, 0]])
57+
58+
Tensor B:
59+
tensor([[3, 0],
60+
[0, 5]])
61+
62+
A OR B:
63+
tensor([[True, True],
64+
[True, True]])
65+
```
66+
67+
## Example 2
68+
69+
In this example, a 1-D tensor is combined with a scalar using broadcasting to show how `.logical_or()` can apply a Boolean condition efficiently across all elements:
70+
71+
```py
72+
import torch
73+
74+
x = torch.tensor([0, 4, 0, 7])
75+
y = torch.tensor(1) # scalar
76+
77+
result = torch.logical_or(x, y)
78+
79+
print(result)
80+
```
81+
82+
The output of this code is:
83+
84+
```shell
85+
tensor([True, True, True, True])
86+
```
87+
88+
## Frequently Asked Questions
89+
90+
### 1. What are the tensor operations in PyTorch?
91+
92+
Tensor operations in PyTorch include arithmetic, logical operations, reductions, reshaping, indexing, broadcasting, and matrix operations. These operations run efficiently on CPU or GPU and form the core building blocks of neural network workflows.
93+
94+
### 2. Why use tensor instead of NumPy?
95+
96+
Tensors support automatic differentiation and execute seamlessly on GPUs, which makes them suited for deep learning workloads. They also integrate tightly with PyTorch's computation graph, while NumPy arrays operate only on the CPU and lack gradient support.
97+
98+
### 3. What does cpu() do in PyTorch?
99+
100+
The `.cpu()` method moves a tensor or model from a GPU device to the system’s CPU. This is useful for running operations on hardware without CUDA support or preparing data for libraries that operate only on CPU-based arrays.

0 commit comments

Comments
 (0)