NumPy Square: Understanding np.square()

The np.square() function returns the element-wise square of its input:

import numpy as np

x = np.array([1, 2, 3])
np.square(x)

# Expected result
# array([1, 4, 9])

The function accepts any array-like input. If the input is a scalar, it will return a scalar. If the input is an array, it will return an array. It will also convert Python sequences to np.ndarray if necessary.

But note: although similar in most cases, this operatoin is not exactly the same as x ** 2. When x is a np.ndarray, then np.square() is indeed equivalent to x ** 2, but when x is a np.matrix, then x ** 2 will actually be the matrix multiplied by itself with matrix multiplication:

x_matrix = np.matrix(np.stack([x] * 3))
x_matrix

# Expected result
# matrix([[1, 2, 3],
#         [1, 2, 3],
#         [1, 2, 3]])

np.square(x_matrix)

# Expected result
# matrix([[1, 4, 9],
#         [1, 4, 9],
#         [1, 4, 9]])

x_matrix ** 2

# Expected result
# matrix([[ 6, 12, 18],
#         [ 6, 12, 18],
#         [ 6, 12, 18]])

A couple other notes about np.square()

  • Data type will be left alone by the operation. If you input integer types you’ll get integer types out.
  • It works on complex NumPy types.

Hello, my name is Ben Cook

I help data scientists deploy their code. If there's any way I can serve you, don't hestitate to reach out. You can also find out a little more about me or download my free guide: 8 Best Practices for Building Machine Learning Pipelines.

Thanks for stopping by!

Contact

Get in touch

Connect

Free Guide

Download my free guide: 8 Best Practices for Building Machine Learning Pipelines