Numpy Operations – numpy.sum() , numpy.subtract() , numpy.multiply() , numpy.dot() , numpy.divide()

Numpy Operations - numpy.sum() , numpy.subtract() , numpy.multiply() , numpy.dot() , numpy.divide()

In this article, we will be learning how we can perform basic mathematical operations using Numpy. Our aim for this article is to learn about numpy.sum(), numpy.subtract(), numpy.multiply(), numpy.dot() and numpy.divide(). So as you can see these numpy functions are used to do basic operations of mathematics that are needed in machine learning or data science projects.

Let’s learn about them but before that, let us import the numpy library.

import numpy as np

We will start this tutorial with sum function

Numpy Sum : np.sum()

As you would have understood that numpy sum function is used to add the values which are present in the array.

Now, let’s look at what are the parameters that the numpy sum function includes and how we can use it.

Syntax

np.sum(a, axis=None, dtype=None, out=None, keepdims=some_value, initial=some_value, where=some_value)

As we can see there are seven parameters used in np.sum() or numpy.sum() operation. They are described as follows:

a : array_like – This is the array that is passed to the function, the elements of this array are added.

axis : None or int or tuple of ints (optional) – Axis or axes along which a sum is performed. This parameter can have either int or tuple of ints as its value

dtype : dtype (optional) – This tells us about the type of array returned by np.sum() function

out : ndarray (optional) – Alternative output array in which to place the result.

keepdims : bool (optional) – This parameter takes a boolean value. If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.

initial : scalar (optional) – Starting value for the sum, this value is assumed for sum at the beginning of execution.

where : array_like of bool (optional) – This is the last parameter of np.sum() or numpy.sum() function, it tells which elements to include in the sum.

Example 1:

In this example, we can see that two values in an array are provided which results in an array with the final result.
In [2]:
np.sum([36, 25])
Out[2]:
61

Example 2: Understanding the use of axis parameter

Here we have provided the value of the axis parameter as ‘0’. So the values 4 & 8 and 9 & 7 are added.
In [3]:
np.sum([[4, 9], [8, 7]], axis=0)
Out[3]:
array([12, 16])

Example 3: Understanding the use of axis parameter

Here we have provided the value of the axis parameter as ‘1’. So the array values 4 & 9 and 8 & 7 are added.

In [4]:
np.sum([[4, 9], [8, 7]], axis=1)
Out[4]:
array([13, 15])

Example 4: Using “Initial” Parameter

In this example of np.sum(), we have initialized the sum array with a value of 43, this is why we have a result as 52.
In [5]:
np.sum([9], initial=43)
Out[5]:
52

Example 5: Performing sum operation using ‘+’ operator

We can also perform addition operation by using ‘+’ operator, apart from using numpy sum()

In [6]:
a = np.array([5,2])
a
Out[6]:
array([5, 2])
In [7]:
b = np.array([2,7])
b
Out[7]:
array([2, 7])
In [8]:
a + b 
Out[8]:
array([7, 9])

Continuing this tutorial, let’s learn about how subtract operation works.

Numpy Subtract : np.subtract()

For performing subtract operation, we use numpy.subtract() or np.subtract() function.

Syntax

np.subtract(x1,x2,out=some_value,where=some_value,kwargs)

x1, x2 : array_like – The arrays to be subtracted from each other. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

out : ndarray, None, or tuple of ndarray and None (optional) – A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned.

where : array_like – (optional) – This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value.

kwargs – This parameter is used for other keyword arguments

The final output of numpy.subtract() or np.subtract() function is y : ndarray, this array gives difference of x1 and x2, element-wise.

Example 1:

Here in this first example, we have provided x1=7.0 and x2=4.0

In [9]:
np.subtract(7.0, 4.0)
Out[9]:
3.0

Example 2:

This example of np.subtract() shows how we use np.arange() function for reshaping the array and then the results are further used for input to np.subtract() function

In [10]:
x1 = np.arange(9.0)
x1
Out[10]:
array([0., 1., 2., 3., 4., 5., 6., 7., 8.])
In [11]:
x1  = np.arange(9.0).reshape((3, 3))
x1
Out[11]:
array([[0., 1., 2.],
       [3., 4., 5.],
       [6., 7., 8.]])
In [12]:
x2 = np.arange(3.0)
x2
Out[12]:
array([0., 1., 2.])

Now, the x2 array is subtracted from x1 array below.

In [13]:
np.subtract(x1, x2)
Out[13]:
array([[0., 0., 0.],
       [3., 3., 3.],
       [6., 6., 6.]])

Example 3: Performing subtraction using ‘-‘ operator

We can also perform subtraction operation by using ‘-‘ operator, apart from using numpy subtract()

In [14]:
a = np.array([9,1])
b = np.array([2,8])
a - b 
Out[14]:
array([ 7, -7])

[adrotate banner=”3″]

Moving on now to the multiply operation using numpy.

Numpy Multiply : np.multiply()

The multiply operation is performed with the help of numpy.multiply()

In this syntax of np.multiply(), we will look at the parameters used in this function

Syntax

numpy.multiply(x1, x2, /, out=None, , where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[, signature, extobj])

x1, x2 : array_like – The arrays to be subtracted from each other. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

out : ndarray, None, or tuple of ndarray and None (optional) – A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned.

where : array_like – (optional) – This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value.

kwargs – This parameter is used for other keyword arguments

The final output of numpy.multiply() or np.multiply() function is y : ndarray, this array gives product of x1 and x2, element-wise.

Example 1:

In [15]:
np.multiply(7.0, 5.0)
Out[15]:
35.0

Example 2:

This example of np.multiply() shows how we use np.arange() function for reshaping the array and then the results are further used for input to np.multiply() function

In [16]:
x1 = np.arange(9.0)
x1
Out[16]:
array([0., 1., 2., 3., 4., 5., 6., 7., 8.])
In [17]:
x1 = np.arange(9.0).reshape((3, 3))
x1
Out[17]:
array([[0., 1., 2.],
       [3., 4., 5.],
       [6., 7., 8.]])
In [18]:
x2 = np.arange(3.0)
x2
Out[18]:
array([0., 1., 2.])
Now, the x2 array is multiplied with x1 array below.
In [19]:
np.multiply(x1, x2)
Out[19]:
array([[ 0.,  1.,  4.],
       [ 0.,  4., 10.],
       [ 0.,  7., 16.]])

Example 3: Performing multiplication using “*” operator

We can also perform multiplication operation by using ‘*’ operator, apart from using numpy multiply()

In [20]:
a = np.array([8,3])
a
Out[20]:
array([8, 3])
In [21]:
b = np.array([2,17])
b
Out[21]:
array([ 2, 17])
In [22]:
a * b
Out[22]:
array([16, 51])

It’s time to understand how dot operations are executed using numpy

Numpy Dot : np.dot()

The numpy.dot() operation helps in executing dot operations. It can help in performing various kinds of dot operations.

Syntax

numpy.dot(a, b, out=None)

a : array_like – This argument provides the first array for the dot operations to execute.

b : array_like – This argument provides the second array for the dot operations to execute.

out : ndarray (optional) – Output argument. This must have the exact kind that would be returned if it was not used.

It also has the feature of raising value error if the last dimension of a is not the same size as the second-to-last dimension of b.

Example 1: Using Single Dimension Array

Here in this first example, the two values are provided.

In [23]:
np.dot(3, 4)
Out[23]:
12

Example 2: Using 2-Dimensional Array

In the case of 2-D arrays, we perform matrix multiplication. The output is the same as input arrays.
In [23]:
a = [[1, 0], [0, 1]]
a
Out[23]:
[[1, 0], [0, 1]]
In [24]:
b = [[4, 1], [2, 2]]
b
Out[24]:
[[4, 1], [2, 2]]
In [25]:
np.dot(a, b)
Out[25]:
array([[4, 1],
       [2, 2]])

Lastly, we have the divide mathematical operation using numpy

Numpy Divide : np.divide()

The divide operation is performed through np.divide() function. This division function Returns a true division of the inputs, element-wise.

Instead of the Python traditional ‘floor division’, this returns a true division. True division adjusts the output type to present the best answer, regardless of input types.

Syntax

numpy.divide(x1, x2, /, out=None, *, where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[, signature, extobj])

x1 : array_like – This argument provides the dividend array.

x2 : array_like – This argument is Divisor array. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).

out : ndarray, None, or tuple of ndarray and None (optional) – A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned.

where : array_like – (optional) – This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value.

kwargs – This parameter is used for other keyword arguments

The floor division operator // was added in Python 2.2 making // and / equivalent operators. The default floor division operation of / can be replaced by true division with from future import division.

In Python 3.0, // is the floor division operator and / the true division operator. The true_divide(x1, x2) function is equivalent to true division in Python.

Example 1 : Using true_divide() function for obtaining results as float values

In [26]:
x = np.arange(15)
x
Out[26]:
array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14])
In [27]:
np.true_divide(x,4)
Out[27]:
array([0.  , 0.25, 0.5 , 0.75, 1.  , 1.25, 1.5 , 1.75, 2.  , 2.25, 2.5 ,
       2.75, 3.  , 3.25, 3.5 ])
In [28]:
np.divide(x,4)
Out[28]:
array([0.  , 0.25, 0.5 , 0.75, 1.  , 1.25, 1.5 , 1.75, 2.  , 2.25, 2.5 ,
       2.75, 3.  , 3.25, 3.5 ])

Here true_divide() and divide function produces same results, divide() function was used in previous versions of python. From 3.0 python version, we use true_divide() to get float results.

Example 2: Obtaining float values as results i.e. true division results using ‘ / ‘

In [29]:
from __future__ import division

x = np.arange(20)
x/4
Out[29]:
array([0.  , 0.25, 0.5 , 0.75, 1.  , 1.25, 1.5 , 1.75, 2.  , 2.25, 2.5 ,
       2.75, 3.  , 3.25, 3.5 , 3.75, 4.  , 4.25, 4.5 , 4.75])

Example 3: Obtaining whole numbers as results i.e. floor division results using double slash symbol

In [30]:
x//4
Out[30]:
array([0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4],
      dtype=int32)

Conclusion

Reaching the last stage of this article, we have learned about the syntax of np.sum(), np.subtract(), np.multiply(), np.dot() and np.divide() functions which are helpful in executing basic mathematical operations with the help of numpy. We also understood how we can use these functions like numpy sum, numpy subtract, numpy multiply, numpy dot and numpy divide with different examples.

Click Here To Download This Tutorial in Interactive Jupyter Notebook

 

Reference-  https://numpy.org/doc/

Follow Us

Leave a Reply

Your email address will not be published. Required fields are marked *