Linalgerror singular matrix ошибка

  • Редакция Кодкампа

17 авг. 2022 г.
читать 1 мин


Одна ошибка, с которой вы можете столкнуться в Python:

numpy.linalg.LinAlgError: Singular matrix

Эта ошибка возникает, когда вы пытаетесь инвертировать сингулярную матрицу, которая по определению является матрицей с нулевым определителем и не может быть инвертирована.

В этом руководстве рассказывается, как устранить эту ошибку на практике.

Как воспроизвести ошибку

Предположим, мы создаем следующую матрицу с помощью NumPy:

import numpy as np

#create 2x2 matrix
my_matrix = np.array([[1., 1.], [1., 1.]])

#display matrix
print(my_matrix)

[[1. 1.]
 [1. 1.]]

Теперь предположим, что мы пытаемся использовать функцию inv() из NumPy для вычисления обратной матрицы:

from numpy import inv

#attempt to invert matrix
inv(my_matrix)

numpy.linalg.LinAlgError: Singular matrix

Мы получаем ошибку, потому что созданная нами матрица не имеет обратной матрицы.

Примечание.Ознакомьтесь с этой страницей Wolfram MathWorld, на которой показаны 10 различных примеров матриц, не имеющих обратной матрицы.

По определению матрица сингулярна и не может быть обращена, если ее определитель равен нулю.

Вы можете использовать функцию det() из NumPy для вычисления определителя данной матрицы, прежде чем пытаться ее инвертировать:

from numpy import det

#calculate determinant of matrix
det(my_matrix)

0.0

Определитель нашей матрицы равен нулю, что объясняет, почему мы сталкиваемся с ошибкой.

Как исправить ошибку

Единственный способ обойти эту ошибку — просто создать невырожденную матрицу.

Например, предположим, что мы используем функцию inv() для инвертирования следующей матрицы:

import numpy as np
from numpy. linalg import inv, det

#create 2x2 matrix that is not singular
my_matrix = np.array([[1., 7.], [4., 2.]])

#display matrix
print(my_matrix)

[[1. 7.]
 [4. 2.]]

#calculate determinant of matrix
print(det(my_matrix))

-25.9999999993

#calculate inverse of matrix
print(inv(my_matrix))

[[-0.07692308 0.26923077]
 [ 0.15384615 -0.03846154]]

Мы не получаем никакой ошибки при инвертировании матрицы, потому что матрица не является единственной.

Дополнительные ресурсы

В следующих руководствах объясняется, как исправить другие распространенные ошибки в Python:

Как исправить: объект numpy.float64 не вызывается
Как исправить: объект ‘numpy.ndarray’ не вызывается
Как исправить: объект numpy.float64 не может быть интерпретирован как целое число

import numpy as np

A = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
B = np.array([[1, 2], [3, 4], [5, 6], [7, 8]])
C = np.array([[1, 2, 3], [4, 5, 6]])
D = np.array([[1], [2], [3]])

prod_AB = np.matmul(A, B)
E = np.matmul(prod_AB, C)

x = np.linalg.solve(E, D)

Traceback (most recent call last):
  File "C:/Users/Owner.ASUS-DESKTOP/Documents/ENGR 102/Lab 10/test.py", line 11, in <module>
    x = np.linalg.solve(E, D)
  File "<__array_function__ internals>", line 5, in solve
  File "C:UsersOwner.ASUS-DESKTOPAppDataLocalProgramsPythonPython38libsite-packagesnumpylinalglinalg.py", line 394, in solve
    r = gufunc(a, b, signature=signature, extobj=extobj)
  File "C:UsersOwner.ASUS-DESKTOPAppDataLocalProgramsPythonPython38libsite-packagesnumpylinalglinalg.py", line 88, in _raise_linalgerror_singular
    raise LinAlgError("Singular matrix")
numpy.linalg.LinAlgError: Singular matrix

Why is this throwing an error? My colleagues used a different IDE (I am using PyCharm and they are using Anaconda) and there program ran no problem. Is this error IDE dependant?

Python programming language provides us with various libraries to deal with several numeric, vectorized data and perform operations. Using them prevents us from doing computationally expensive tasks and makes our work easier. One such library is Numpy. It is used to perform mathematical operations on array and matrices. Some of them are cross-multiplication, dot-product, inverse e.t.c. While operating these matrices sometimes, we get errors like LinAlgError Singular Matrix. This article will try to understand the error and find suitable solutions for it.

So, LinAlgError is raised by linear algebra class (named linalg) when some linear algebra function prevents the correct execution of other program parts. The singular matrix is the sub-error raised when we perform incorrect operations on the singular matrix.

What is LinAlgError Singular Matrix Error?

LinAlgError Singular Matrix Error

So, in the above image, you can see that the interpreter threw a LinAlgError: Singular matrix. It means that the error occurred because of some linear algebra operation that is computationally incorrect. Talking more descriptively, we can say that some operations on a singular matrix are because of some operations. The matrix may not support those operations.

Why do I get “LinAlgError Singular Matrix” Error?

The reason to get the error lies because we are doing those operations, which is not computationally possible. In the above case, the reason for the error is we want to inverse the matrix whose determinant is zero. Let’s see that.

Why do I get "LinAlgError Singular Matrix" Error

And when we work on matrices, there are several constraints and rules that we need to follow. Inverting a singular matrix is one of them. Inverting a singular matrix is practically impossible, and hence while applying the inverse function.

Solution to “LinAlgError Singular Matrix” Error

Now, the only solution to these errors is that you should avoid being in such scenarios. You should check the singularity of any matrix before applying any inverse operations on them. Moreover, it would be best never to forget the constraints on matrices while performing any operations on them.

This solution works in several scenarios where we get LinAlgError Singular Matrix-like building machine learning algorithms such as Logistic regression or deep learning model.

Mastering Python Translate: A Beginner’s Guide

Now, more often, when we work on some ML or DL project, we use more than one library simultaneously. Pandas are one of the significant tools in them. While performing some operations on matrix data, we might get LinAlgError Singular Matrix. Now, the reason for the error is the same as above, and we need to apply the same solution there. We choose to work on those data, which lets us avoid getting matrix data.

FAQs

Q1) Does Logit endog requires the y variable to be 0?

The endog y variable needs to be zero, one. However, in other cases, it is possible that the Hessian is not positive definite when we evaluate it far away from the optimum, for example, at bad starting values. Switching to an optimizer that does not use the Hessian often succeeds in those cases. For example, scipy’s ‘bfgs’ is a good optimizer that works in many cases.

Conclusion

Today, in this article, we learned about LinAlgError. We now understand the meaning of error and inspect the scenarios in which the error may occur.

I hope this article has helped you. Thank You.

Trending Right Now

  • [Fixed] SSL module in Python is Not Available

    [Fixed] SSL module in Python is Not Available

    May 30, 2023

  • Mastering Python Translate: A Beginner’s Guide

    Mastering Python Translate: A Beginner’s Guide

    by Namrata GulatiMay 30, 2023

  • Efficiently Organize Your Data with Python Trie

    Efficiently Organize Your Data with Python Trie

    by Namrata GulatiMay 2, 2023

  • [Fixed] modulenotfounderror: no module named ‘_bz2

    [Fixed] modulenotfounderror: no module named ‘_bz2

    by Namrata GulatiMay 2, 2023


One error you may encounter in Python is:

numpy.linalg.LinAlgError: Singular matrix

This error occurs when you attempt to invert a singular matrix, which by definition is a matrix that has a determinant of zero and cannot be inverted.

This tutorial shares how to resolve this error in practice.

How to Reproduce the Error

Suppose we create the following matrix using NumPy:

import numpy as np

#create 2x2 matrix
my_matrix = np.array([[1., 1.], [1., 1.]])

#display matrix
print(my_matrix)

[[1. 1.]
 [1. 1.]]

Now suppose we attempt to use the inv() function from NumPy to calculate the inverse of the matrix:

from numpy import inv

#attempt to invert matrix
inv(my_matrix)

numpy.linalg.LinAlgError: Singular matrix

We receive an error because the matrix that we created does not have an inverse matrix.

Note: Check out this page from Wolfram MathWorld that shows 10 different examples of matrices that have no inverse matrix.

By definition, a matrix is singular and cannot be inverted if it has a determinant of zero.

You can use the det() function from NumPy to calculate the determinant of a given matrix before you attempt to invert it:

from numpy import det

#calculate determinant of matrix
det(my_matrix)

0.0

The determinant of our matrix is zero, which explains why we run into an error.

How to Fix the Error

The only way to get around this error is to simply create a matrix that is not singular.

For example, suppose we use the inv() function to invert the following matrix:

import numpy as np
from numpy.linalg import inv, det

#create 2x2 matrix that is not singular
my_matrix = np.array([[1., 7.], [4., 2.]])

#display matrix
print(my_matrix)

[[1. 7.]
 [4. 2.]]

#calculate determinant of matrix
print(det(my_matrix))

-25.9999999993

#calculate inverse of matrix
print(inv(my_matrix))

[[-0.07692308  0.26923077]
 [ 0.15384615 -0.03846154]]

We don’t receive any error when inverting the matrix because the matrix is not singular.

Additional Resources

The following tutorials explain how to fix other common errors in Python:

How to Fix: ‘numpy.float64’ object is not callable
How to Fix: ‘numpy.ndarray’ object is not callable
How to Fix: ‘numpy.float64’ object cannot be interpreted as an integer

The numpy.linalg.linalgerror: singular matrix error occurs in Python when you attempt to invert a singular matrix whose determinant is zero that cannot be inverted.

To fix the LinAlgError: Singular matrix error, create a matrix that is not singular, and the determinant is not 0.0.

Python code that generates numpy.linalg.linalgerror: singular matrix

import numpy as np

#create 2x2 matrix
main_matrix = np.array([[21., 21.], [21., 21.]]) 

# attempt to print the inverse of matrix
print(np.linalg.inv(main_matrix))

Output

numpy.linalg.linalgerror - singular matrix

You can see that we got the “LinAlgError: Singular matrix” error because the main_matrix is not invertible. It has the same value in all entries, making it a singular matrix with zero determinant.

The numpy.linalg.LinAlgError is an exception class for general purposes, derived from Python’s exception.

When a Linear Algebra-related condition prevents continued accurate execution of the function, this exception class is raised programmatically in linalg functions.

A matrix is invertible only if its determinant is non-zero.

If the determinant is zero, the matrix is said to be singular and has no inverse.

You can use the np.linalg.det() function from NumPy to calculate the determinant of a given matrix before you try to invert it.

import numpy as np 

# create 2x2 matrix 
main_matrix = np.array([[21., 21.], [21., 21.]]) 

# Printing the determinant
print(np.linalg.det(main_matrix))

Output

You can see that the determinant of the matrix is zero, which explains why we get into the error.

Code that fixes the error

import numpy as np 

# create 2x2 matrix 
main_matrix = np.array([[21., 19.], [19., 21.]]) 

# Printing the inverse of matrix
print(np.linalg.inv(main_matrix))

Output

[[ 0.2625 -0.2375]
 [-0.2375  0.2625]]

You can see that the code worked without errors and will print the inverse of the main_matrix.

In this case, the main_matrix is a 2×2 matrix with a non-zero determinant, which is invertible.

The np.linalg.inv() function from the NumPy library is used to find the inverse of the main_matrix.

I hope this solution will resolve your error.

Понравилась статья? Поделить с друзьями:

Не пропустите эти материалы по теме:

  • Яндекс еда ошибка привязки карты
  • Light needs to be rebuilt ошибка
  • Lin ошибка связи
  • Light control ошибка
  • Limp home ошибка

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии