Working with Python Lil_Matrix Scipy

This tutorial will teach us about the “Python Lil_Matrix Scipy” which is another kind of sparse matrix but efficient in use or nature.

So here we will create the Lil Matrix and sum or compute the mean of the elements within the matrix, also performing several operations like resizing or copying the matrix, etc. Additionally, cover the following topics.

  • What is Lil Matrix in Scipy?
  • How to create a Lil_Matrix using Python Scipy
  • How to sum the Lil_Matrix elements along the specific axis.
  • How to find indices of nonzero elements in Scipy Lil_Matrix
  • How to resize the Scipy Lil_Matrix
  • How to create a copy of the Scipy Lil_Matrix
  • How to check the data type of Scipy Lil_Matrix
  • How to find the average of the Scipy Lil_Matrix
  • How to transpose the Scipy Lil_Matrix

What is Lil Matrix in Scipy?

Lil Matrix is a sparse matrix with a row-based list of lists. The structure is given in the next subsection which can be used to incrementally build sparse matrices.

Make sure the elements are pre-sorted by index, per row, when building a matrix because, in the worst-case scenario, inserting only one item can take linear time.

The arithmetic operations subtraction, addition, multiplication, division, and matrix power are supported by sparse matrices.

  • The LIL format’s benefit is to allow for flexible slicing and the matrix sparsity structure is efficiently modified.
  • The LIL format has drawbacks of LIL + LIL is a slow addition process (consider CSR or CSC), slowly slicing columns (consider CSC), and inefficient matrix-vector products (consider CSR or CSC).

Purpose of Use: The LIL format makes it simple to create sparse matrices. For quick arithmetic and matrix-vector operations, convert a matrix to CSR or CSC format once it has been created. When creating huge matrices, take into account choosing the COO format.

Read: Python Scipy Sparse Csr_matrix

Python Lil_Matrix Scipy

The class lil_matrix() of Python Scipy that exists in a module scipy.sparse for sparse matrix based on rows of lists.

The syntax is given below.

class scipy.sparse.lil_matrix(arg1, shape=None, dtype=None, copy=False)

There are various ways to instantiate this:

  • lil_matrix(D) with a rank 2 ndarray D or a dense matrix.
  • lil_matrix(S) with a different sparse matrix S.
  • To create an empty matrix with the shape (M, N), use the syntax “lil matrix((M, N), [dtype])”. Dtype is optional and defaults to dtype=’d’.

Let’s create the Lil matrix by following the below steps:

Import the required libraries or methods using the below python code.

import numpy as np
from scipy.sparse import lil_matrix

Create a rank-2 matrix that contains the USA cities code using the below code.

usa_city_code = np.array([[334, 251, 205, 256, 907, 480], [602, 209, 213, 661, 707, 741],\
 [925, 949, 303, 719, 203, 860]])

Pass the above matrix to lil_matrix() using the below code.

lil_matrix(usa_city_code).toarray()

Run the below code to check whether it is Lil matrix or not.

lil_matrix(usa_city_code)
Python Lil_Matrix Scipy
Python Lil_Matrix Scipy

This is how to generate or create the Lil matrix using the method lil_matrix() of Python Scipy.

Read: Python Scipy IIR Filter

Python Lil_Matrix Scipy Sum

The method lil_matrix.sum of Python Scipy add up each matrix member along a specific axis.

The syntax is given below.

lil_matrix.sum(axis=None, dtype=None, out=None)

Where parameters are:

  • axis({-2, -1, 0, 1} ): Axis that is used to compute the sum. By default, the sum of each matrix element is calculated and returned as a scalar (i.e., axis = None).
  • dtype: The kind of accumulator used to add the components together and the type of the returning matrix. Unless a has an integer dtype with a lower degree of precision than the platform integer, the dtype of an is utilized by default. The platform integer is used in this situation if an is signed, while an unsigned integer with the same precision is used if an is unsigned.
  • out(np.matrix): Alternative output matrixes are available for the outcome. It must be the same shape as the desired output, but if necessary, the type of output values will be cast.

The method lil_matrix.sum returns sum_along_axis (an identical-to-self matrix that lacks the desired axis).

Let’s take the same example that we have used in the above subsection to compute the sum of elements along the axis by following the below steps:

Import the required libraries or methods using the below python code.

import numpy as np
from scipy.sparse import lil_matrix

Create a rank-2 matrix that contains the USA cities code using the below code.

usa_city_code = np.array([[334, 251, 205, 256, 907, 480], [602, 209, 213, 661, 707, 741],\
 [925, 949, 303, 719, 203, 860]])

Pass the above matrix to lil_matrix() using the below code.

lil_matrix(usa_city_code).toarray()

The above code shows how the Lil matrix looks, now use the below code to sum the elements along the axis equal to zero.

s = lil_matrix(usa_city_code).sum(0)
print(s)
Python Lil_Matrix Scipy Sum
Python Lil_Matrix Scipy Sum

This is how to sum the elements of the Lil matrix along the specified axis using the method lil_matrix.sum() of Python Scipy.

Read: Python Scipy Stats Fit

Python Lil_Matrix Scipy Nonzero

There is a method lil_matrix.nonzero() in a module scipy.sparse to return an array tuple (row, col) holding the indices of the matrix’s non-zero entries.

Let’s take an example to understand how to get the indices of non-zero elements within the Lil matrix by following the below steps:

Import the required libraries or methods using the below python code.

import numpy as np
from scipy.sparse import lil_matrix

Use the code below to create a rank-2 matrix.

mat_data = np.array([[3, 2, 0, 2, 9, 8], [0, 0, 2, 6, 0, 4],\
 [2, 9, 3, 1, 3, 6]])

Create a Lil matrix and check the matrix using the below code.

lil_mat = lil_matrix(mat_data)
lil_mat.toarray()

Apply the method nonzero() on the Lil, matrix to find the indices of the nonzero elements using the below code.

lil_mat.nonzero()
Python Lil_Matrix Scipy Nonzero
Python Lil_Matrix Scipy Nonzero

The above output shows the indices of the nonzero elements within the Lil matrix such as (0,0) = 3, (0,1)=2 and (0,3) =2 so on.

Read: Python Scipy ttest_ind

Python Lil_Matrix Scipy Resize

The Python Scipy module scipy.sparse has a method lil_matrix.resize() to resize the matrix to the dimensions specified by the shape. Non-zero elements outside the new shape are eliminated, while elements inside the new shape will keep their current indices.

The syntax is given below.

lil_matrix.resize(*shape)

Where parameter shape(int, int): the new matrix’s rows and columns number.

As demonstrated below using an example of how to resize the Lil matrix with the help of the same example that we have done in the next subsection.

Import the required libraries or methods using the below python code.

import numpy as np
from scipy.sparse import lil_matrix

Use the code below to create a rank-2 matrix.

data = np.array([[34, 251, 20, 26, 97, 48], [60, 20, 21, 66, 70, 74],\
 [92, 94, 30, 19, 30, 60]])

Create a Lil matrix and check the shape of the matrix using the below code.

lil_mat = lil_matrix(data)
print(lil_mat.shape)
lil_mat.toarray()

Now change the shape of the Lil matrix to 3 by 2 using the below code.

lil_mat.resize(3,2)

Check the resized matrix shape using the below code.

print(lil_mat.shape)
lil_mat.toarray()
Python Lil_Matrix Scipy Resize
Python Lil_Matrix Scipy Resize

This is how to resize the Lil matrix using the method lil_matrix.resize() of Python Scipy.

Read: Python Scipy Gamma

Python Lil_Matrix Scipy Copy

The method lil_matrix.copy() of Python Scipy in a module scipy.sparse copy this matrix and returns it. There will be no data or index sharing between the current matrix and the returning value.

Let’s take an example and copy the Lil matrix by following the below steps:

Import the required libraries or methods using the below python code.

import numpy as np
from scipy.sparse import lil_matrix

Use the code below to create a rank-2 matrix.

data = np.array([[34, 251, 20, 26, 97, 48], [60, 20, 21, 66, 70, 74],\
 [92, 94, 30, 19, 30, 60]])

Create a Lil matrix using the below code.

lil_mat = lil_matrix(data)
lil_mat.toarray()

Now copy the above-created Lil matrix lil_mat using the method copy().

copy_lilmat = lil_mat.copy()
copy_lilmat.toarray()
Python Lil_Matrix Scipy Copy
Python Lil_Matrix Scipy Copy

This is how to copy the Lil matrix using the method lil_matrix.copy() of Python Scipy.

Read: Python Scipy Normal Test

Python Lil_Matrix Scipy Dtype

Lil matrix has an attribute dtype to knowing the data type of the elements that exist within the Lil matrix.

Let’s take the same example that we have used in the above subsections of this tutorial.

Import the required libraries or methods using the below python code.

import numpy as np
from scipy.sparse import lil_matrix

Use the code below to create a rank-2 matrix that includes the USA cities’ codes.

usa_city_code = np.array([[334, 251, 205, 256, 907, 480], [602, 209, 213, 661, 707, 741],\
 [925, 949, 303, 719, 203, 860]])

Use the following code to pass the aforementioned matrix to lil_matrix() and access the attribute dtype to know the data type of the Lil matrix.

lil_matrix(usa_city_code).dtype
Python Lil_Matrix Scipy Dtype
Python Lil_Matrix Scipy Dtype

This is how to check the data type of the Lil matrix using the attribute dtype of Lil Matrix.

Read: Python Scipy Stats Skew

Python Lil_Matrix Scipy Mean

The method lil_matrix.mean() of Python Scipy returns the matrix’s average value. By default, the average is calculated over all matrix elements; if not, it is calculated across the selected axis. Integer inputs use float64 as the intermediate and return values.

The syntax is given below.

lil_matrix.mean(axis=None, dtype=None, out=None)

Where parameters are:

  • axis(1,0,-1,-2): Axis that is used to compute the mean. The default setting (i.e., axis = None) computes the mean of every member in the matrix.
  • dtype: Utilize this type for calculating the mean. The default value for floating-point inputs is equal to the input dtype, while it is float64 for integer inputs.
  • out(np.matrix): A different output matrix should be used to store the outcome. The output values’ types may be cast if necessary, but they must have the same shape as the expected output.

Import the required libraries or methods using the below python code.

import numpy as np
from scipy.sparse import lil_matrix

Use the code below to create a rank-2 matrix.

mat_data = np.array([[3, 2, 0, 2, 9, 8], [0, 0, 2, 6, 0, 4],\
 [2, 9, 3, 1, 3, 6]])

Create a Lil matrix and check the matrix using the below code.

lil_mat = lil_matrix(mat_data)
lil_mat.toarray()

Apply the method mean() on the Lil, matrix to find the mean of the Lil matrix alone the axis = 0 using the below code.

lil_mat.mean(0)
Python Lil_Matrix Scipy Mean
Python Lil_Matrix Scipy Mean

From the above output that contains the mean of the elements within the Lil matrix along the axis = 0.

Read: Python Scipy Kdtree

Python Lil_matrix Scipy Transpose

The method lil_matrix.transpose() of Python Scipy in a module scipy.sparse reverses the sparse matrix’s dimensions.

The syntax is given below.

lil_matrix.transpose(axes=None, copy=False)

Where parameters are:

axes: The only reason this argument is in the signature is to ensure NumPy compatibility. Nothing else should be entered besides the default value.

copy(boolean): Whether or not self-attributes should be imitated wherever possible. Depending on the kind of sparse matrix being utilized, different attributes are duplicated to varying degrees.

The method lil_matrix.transpose() returns p.

Let’s take an example and transpose the Lil matrix by following the below steps:

Import the required libraries or methods using the below python code.

import numpy as np
from scipy.sparse import lil_matrix

Use the code below to create a rank-2 matrix.

mat_data = np.array([[3, 2, 0, 2, 9, 8], [0, 0, 2, 6, 0, 4],\
 [2, 9, 3, 1, 3, 6]])

Create a Lil matrix and check the matrix using the below code.

lil_mat = lil_matrix(mat_data)
lil_mat.toarray()

Apply the method transpose() on the Lil, matrix to swap the rows into columns or columns into rows the Lil matrix using the below code.

lil_mat.transpose().toarray()
Python Lil_matrix Scipy Transpose
Python Lil_matrix Scipy Transpose

This is how to transpose the Lil matrix using the method lil_matrix.transpose() of Python Scipy.

Also, take a look at some more Python Scipy tutorials.

We have learned about how to create a Lil matrix and also compute the sum, found the indices of nonzero elements, copied, and transposed the elements of the Lil matrix, etc.

  • What is Lil Matrix in Scipy?
  • How to create a Lil_Matrix using Python Scipy
  • How to sum the Lil_Matrix elements along the specific axis.
  • How to find indices of nonzero elements in Scipy Lil_Matrix
  • How to resize the Scipy Lil_Matrix
  • How to create a copy of the Scipy Lil_Matrix
  • How to check the data type of Scipy Lil_Matrix
  • How to find the average of the Scipy Lil_Matrix
  • How to transpose the Scipy Lil_Matrix