SoFunction
Updated on 2024-11-19

Rules for arithmetic between arrays of two different shapes in Python

1 Inter-array operations

Disclaimer: The inter-array operations discussed in this blog refer to the quadratic operations such as: a+b, a-b, a*b, a/b, excluding operations such as (b), etc. Since the same rules are followed in both numpy and tensorflow, numpy is used as an example in this blog.

As we all know, an operation between two arrays of the same shape is the addition of the corresponding elements of the two arrays. We often come across arrays with different shapes.

So, can any two arrays of different shapes be computed? And what are the rules of arithmetic?

shape with dimension:

If a: [1,2,3], then shape=(3, ) with dimension 1; b: [[1,2,3],[4,5,6]], then shape=(2,3) with dimension 2

Operational conditions:

Let a be a low-dimensional array and b be a high-dimensional array, then the sufficient conditions for a and b to be able to operate are [-1] = [-1], [-2] = [-2], ... (a can be an element of b), or =(m,1) (or =(m, )) and =(1,n) (a is a row vector and b is a column vector)

Arithmetic rules:

  • When a is a number, operate a with each element of b. The shape of the operation is the same as b when
  • a can be used as an element of b. Operate a with each child element of the same shape in b. The shape after the operation is the same as b.
  • When a is a row vector and b is a column vector, each element in a is operated separately from each element in b. The operation shape=([1], [0])

To change the shape of the array, call the reshape() function as follows:

a=([[1,1],[2,2],[3,3]])
b=([-1,1]) #=(3,2),=(6,1)

2 Experiments

Arithmetic between arrays and numbers

a=([1,1,1])
b=([[1,1,1],[2,2,2]])
c=a+1
d=b+1
print("c=a+1\n",c)
print("d=b+1\n",d)

exports
c=a+1
 [2 2 2]
d=b+1
 [[2 2 2]
 [3 3 3]]

Add: An array of shape=(1, ) can operate on an array of any shape with the same rules as for numbers and arrays.

Operations between row and column vectors

a=([[1,2,3]]) # or a=([1,2,3])
b=([[1],[2],[3],[4],[5]])
c=a+b
print("c=a+b",c)

exports
c=a+b
[[2 3 4]
 [3 4 5]
 [4 5 6]
 [5 6 7]
 [6 7 8]]

Operations between 1-dimensional and high-dimensional arrays

a=([1,1,1])
b=([[1,1,1],[2,2,2]])
c=([[1,1,1],[2,2,2],[3,3,3]])
d=a+b
e=a+c
print("d=a+b\n",d)
print("e=a+c\n",e)

d=a+b
 [[2 2 2]
 [3 3 3]]
e=a+c
 [[2 2 2]
 [3 3 3]
 [4 4 4]]

Operations between high-dimensional arrays

a=([[1,1,1],[2,2,2]])
b=([[[1,1,1],[2,2,2]],[[3,3,3],[4,4,4]]])
c=a+b
print("c=a+b\n",c)

c=a+b
 [[[2 2 2]
  [4 4 4]]
 [[4 4 4]
  [6 6 6]]]

to this article on the Python arrays of two different shapes between the rules of arithmetic is introduced to this article, more related Python arrays of two different shapes content please search for my previous posts or continue to browse the following related articles I hope you will support me in the future more!