Elementwise multiplication of a scipy.sparse matrix by a broadcasted dense 1d array

Learn, how to elementwise-multiply a scipy.sparse matrix by a broadcasted dense 1d array in Python? By Pranit Sharma Last updated : December 23, 2023

NumPy is an abbreviated form of Numerical Python. It is used for different types of scientific operations in python. Numpy is a vast library in python which is used for almost every kind of scientific or mathematical operation. It is itself an array which is a collection of various methods and functions for processing the arrays.

Scipy

Scipy is an abbreviated form of Scientific Python. It is a scientific computation library that provides utility functions and offers more optimization and signal processing. Scipy is an open-source library that can be used freely. Scipy uses Numpy to run its added optimized functions in the field of Data Science.

Broadcasting

The term broadcasting describes how NumPy treats arrays with different shapes during arithmetic operations. Broadcasting provides a means of vectorizing array operations so that looping occurs in C instead of Python.

Problem statement

Suppose that we are given a 2D sparse array and a dense 1D array with all the non-zero elements. We need to compute the elementwise multiplication of arr1 and dense array using the usual broadcasting semantics of numpy.

Elementwise-multiplying a scipy.sparse matrix by a broadcasted dense 1d array

For this purpose, we can turn the vector into a sparse diagonal matrix and then use matrix multiplication (with *) to do the same thing as broadcasting.

Let us understand with the help of an example,

Python code for elementwise multiplication of a scipy.sparse matrix by a broadcasted dense 1d array

# Importing scipy sparse
import scipy.sparse as ssp

# Import numpy
import numpy as np

# Creating a scipy sparse matrix
mat = ssp.lil_matrix((5,3))

# Giving elements
mat[1,2] = 5
mat[4,1] = 10

# Display matrix
print("Matrix:\n",mat,"\n")

# Creating a dense array
den = ssp.lil_matrix((3,3))
den.setdiag(np.ones(3)*3)

# Multiplying array with dense array 
# and converting it into dense matrix
res = (mat*den).todense()

# Display result
print("Result:\n",res)

Output

Example: Elementwise multiplication of a scipy.sparse matrix by a broadcasted dense 1d array

Python NumPy Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.