What does the error Numpy error: Matrix is singular
mean specifically (when using the linalg.solve
function)? I have looked on Google but couldn’t find anything that made it clear when this error occurs.
strpeter
2,5023 gold badges26 silver badges48 bronze badges
asked Dec 10, 2012 at 5:47
1
A singular matrix is one that is not invertible. This means that the system of equations you are trying to solve does not have a unique solution; linalg.solve
can’t handle this.
You may find that linalg.lstsq
provides a usable solution.
answered Dec 10, 2012 at 6:09
6
This function inverts singular matrices as well using numpy.linalg.lstsq
:
def inv(m):
a, b = m.shape
if a != b:
raise ValueError("Only square matrices are invertible.")
i = np.eye(a, a)
return np.linalg.lstsq(m, i)[0]
answered May 17, 2017 at 14:02
ProcopeProcope
911 silver badge7 bronze badges
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 не может быть интерпретирован как целое число
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?
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.
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.
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
●May 30, 2023
-
Mastering Python Translate: A Beginner’s Guide
by Namrata Gulati●May 30, 2023
-
Efficiently Organize Your Data with Python Trie
by Namrata Gulati●May 2, 2023
-
[Fixed] modulenotfounderror: no module named ‘_bz2
by Namrata Gulati●May 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
Hi, this is a (simplified) case I encountered while working on seaborn.pairplot
.
data: data.1000.txt
singular.py:
import pandas import seaborn data = pandas.read_table("data.1000.txt", index_col="cell") seaborn.pairplot(data.drop(columns="cluster").iloc[:,0:6], hue="batch")
commands:
~/w/experiments $ python3 --version
Python 3.6.6
~/w/experiments $ pip3 show seaborn
Name: seaborn
Version: 0.9.0
Summary: seaborn: statistical data visualization
Home-page: https://seaborn.pydata.org
Author: Michael Waskom
Author-email: mwaskom@nyu.edu
License: BSD (3-clause)
Location: /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages
Requires: numpy, scipy, pandas, matplotlib
Required-by:
~/w/experiments $ python3 singular.py
Traceback (most recent call last):
File "singular.py", line 4, in <module>
seaborn.pairplot(data.drop(columns="cluster").iloc[:,0:6], hue="batch")
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/seaborn/axisgrid.py", line 2111, in pairplot
grid.map_diag(kdeplot, **diag_kws)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/seaborn/axisgrid.py", line 1399, in map_diag
func(data_k, label=label_k, color=color, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/seaborn/distributions.py", line 691, in kdeplot
cumulative=cumulative, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/seaborn/distributions.py", line 294, in _univariate_kdeplot
x, y = _scipy_univariate_kde(data, bw, gridsize, cut, clip)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/seaborn/distributions.py", line 366, in _scipy_univariate_kde
kde = stats.gaussian_kde(data, bw_method=bw)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/scipy/stats/kde.py", line 172, in __init__
self.set_bandwidth(bw_method=bw_method)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/scipy/stats/kde.py", line 499, in set_bandwidth
self._compute_covariance()
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/scipy/stats/kde.py", line 510, in _compute_covariance
self._data_inv_cov = linalg.inv(self._data_covariance)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/scipy/linalg/basic.py", line 975, in inv
raise LinAlgError("singular matrix")
numpy.linalg.linalg.LinAlgError: singular matrix