Asked
Viewed
75k times
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.
- python
- numpy
strpeter
2,5623 gold badges27 silver badges48 bronze badges
asked Dec 10, 2012 at 5:47
KaliMaKaliMa
1,9706 gold badges26 silver badges51 bronze badges
1
-
If you have a singular matrix, then it might indicate that you have some mistake in your matrix filling routine. If your matrix really is singular, then you may get some useful information about it using singular value decomposition. However in this case you need to have a good understanding of linear algebra and numerical computing concepts.
Dec 14, 2012 at 4:56
2 Answers
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
-
By «no unique solution» do you mean it may have multiple solutions?
Dec 10, 2012 at 6:37
-
@KaliMa That is what I mean.
Dec 10, 2012 at 7:28
-
@MichaelJBarber Is there a way to get it to return all possible solutions? Is that what linalg.lstsq does?
Dec 10, 2012 at 14:07
-
@KaliMa When a system of equations is singular, it either has infinitely many solutions, or none — so no, in general you can’t retrieve them all. Linalg.lstsq just returns one of those solutions — even if there is none: in that case, it returns the ‘best’ solution (in a least squares sense); but then, too, there are infinitely many other ‘best’ solutions. For further reading: en.wikipedia.org/wiki/System_of_linear_equations
Dec 10, 2012 at 18:32
-
@KaliMa You can use a
try: ... except: ...
block to catch the error; to deal with the singularity, you have to come up with a solution yourself …Or use
lstsq
: that won’t crash, and leaves you at least with one solution …Dec 10, 2012 at 18:43
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
1011 silver badge7 bronze badges
- The Overflow Blog
- Featured on Meta
Linked
Related
Hot Network Questions
-
Does a slippery liquid leak through pipe fittings?
-
Which is your favourite X or what is your favourite X?
-
How can a cybersecurity team mitigate internal customer complaints that real time user training is too intrusive?
-
Lithium ion BMS bypass (or hack)
-
Troubleshooting an Electrical Circuit — Is This an Expected Voltage Drop?
-
Usage of 贵方 in real-life conversation
-
The world’s smallest square maze?
-
Manager wants to hire an additional resource with experience in a skill that I do not have
-
Deutschlandticket to Dutch border stations — how to pass the ticket gates?
-
How to safely pose this Mary Sue character?
-
Has this USAF flight violated russian airspace?
-
Book about a giant spaceship that passes through the solar system
-
How does the Way of Mercy monk’s ability Physician’s Touch work exactly?
-
Lavan the son of whom?
-
Significance of trail of pebbles vs breadcrumbs?
-
What level should this version of Warp Mind be?
-
How can I find out what % of the health insurance premium my employer pays?
-
Computer Modern font: Is CM 12pt an exact scaled version of 10pt? If not, how to scale?
-
Why is WR124 not brighter?
-
Why study finite topological spaces?
-
Transcript of discussion between Elon Musk and Israeli PM Benyamin Netanyahu on 18 Sep 2023?
-
Can 21 sports kits be visually distinct?
-
Are these roof members structural support?
-
Filter a list of strings to create a separate list of those that match a given prefix
more hot questions
Question feed
Your privacy
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
Asked
Viewed
75k times
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.
- python
- numpy
strpeter
2,5623 gold badges27 silver badges48 bronze badges
asked Dec 10, 2012 at 5:47
KaliMaKaliMa
1,9706 gold badges26 silver badges51 bronze badges
1
-
If you have a singular matrix, then it might indicate that you have some mistake in your matrix filling routine. If your matrix really is singular, then you may get some useful information about it using singular value decomposition. However in this case you need to have a good understanding of linear algebra and numerical computing concepts.
Dec 14, 2012 at 4:56
2 Answers
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
-
By «no unique solution» do you mean it may have multiple solutions?
Dec 10, 2012 at 6:37
-
@KaliMa That is what I mean.
Dec 10, 2012 at 7:28
-
@MichaelJBarber Is there a way to get it to return all possible solutions? Is that what linalg.lstsq does?
Dec 10, 2012 at 14:07
-
@KaliMa When a system of equations is singular, it either has infinitely many solutions, or none — so no, in general you can’t retrieve them all. Linalg.lstsq just returns one of those solutions — even if there is none: in that case, it returns the ‘best’ solution (in a least squares sense); but then, too, there are infinitely many other ‘best’ solutions. For further reading: en.wikipedia.org/wiki/System_of_linear_equations
Dec 10, 2012 at 18:32
-
@KaliMa You can use a
try: ... except: ...
block to catch the error; to deal with the singularity, you have to come up with a solution yourself …Or use
lstsq
: that won’t crash, and leaves you at least with one solution …Dec 10, 2012 at 18:43
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
1011 silver badge7 bronze badges
- The Overflow Blog
- Featured on Meta
Linked
Related
Hot Network Questions
-
Are these roof members structural support?
-
Horizontal version of Print[]
-
Conjecture about partitions of the powerset without the empty set
-
Why is WR124 not brighter?
-
Manager wants to hire an additional resource with experience in a skill that I do not have
-
What do you call this old-time style of door knob/lock? How can I replace it?
-
Troubleshooting an Electrical Circuit — Is This an Expected Voltage Drop?
-
What caused the deterioration of relations between Poland and Ukraine?
-
Is there a possibility when calling .ToUpper() that the new string requires more memory?
-
How to tell Google Maps to avoid bad neighborhoods in San Francisco?
-
Japan e-Visa system cannot read my passport, and embassy have no slot for in-person application, what should I do?
-
Which is your favourite X or what is your favourite X?
-
Usage of 贵方 in real-life conversation
-
Left a PhD for a second one from which I got fired. What to write in the CV?
-
given 2 lowpass digital IIR filters find bandpass coefficients
-
Find the largest sum such that no two elements are touching
-
What do you call a nearly vertical step on a ridge?
-
Has this USAF flight violated russian airspace?
-
Difference between «Extending LilyPond» and «Scheme (in LilyPond)»
-
Isn’t it convenient to pronounce «-man» in «salesman» and «-men» in «salesmen» differently as you do it in «man [mæn]» and «men [men]»?
-
Lavan the son of whom?
-
Double sharp: how to analyse a chord in Moonlight Sonata 3rd movement?
-
String containing characters in the same order as other string
-
Dropship scammer hasn’t billed yet — what’s going on here?
more hot questions
Question feed
Your privacy
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
читать 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
-
[Solved] typeerror: unsupported format string passed to list.__format__
●May 31, 2023
-
Solving ‘Remote End Closed Connection’ in Python!
by Namrata Gulati●May 31, 2023
-
[Fixed] io.unsupportedoperation: not Writable in Python
by Namrata Gulati●May 31, 2023
-
[Fixing] Invalid ISOformat Strings in Python!
by Namrata Gulati●May 31, 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