#python #scipy #newtons-method
#python #scipy #метод ньютонов
Вопрос:
Вот мой код:
def obj_function(x):
val= 8*(x[0]**4) 3*(x[1]**2)- 6*x[0]*x[1] 2*x[1]
return np.asmatrix(val)
def obj_function_prime(x):
val=[32*(x[0]**3)-6*x[1], 6*x[1]-6*x[0] 2]
return np.asmatrix(val)
def hess_obj_function(x):
a= 96*(x[0]**2)
b= -6
c= -6
d= 6
val=[[a,b], [c,d]]
return np.asmatrix(val)
tol= 10**(-6)
mu= 0.2
xk= np.asmatrix([1,1])
xold= np.asmatrix([0,0])
while np.linalg.norm(obj_function_prime(xk))> tol:
xold=xk
alpha=1.0
while obj_function(xk- alpha*obj_function_prime(xk))> (obj_function(xk)- mu*alpha*np.dot(obj_function_prime(xk), obj_function(xk))):
alpha=0.5* alpha
xk= xk-alpha*obj_function_prime(xk)
print(" The minimum of the function occurs at", xk)
И это выдает мне ошибку:
*
Трассировка LinAlgError (последний последний вызов
)
в
20 xold= np.matrix([0,0])
21
—> 22 в то время как np.linalg.norm(obj_function_prime(xk))> tol:
23 xold= xk
24 альфа = 1.0<ipython-input-3-c0704e734bdd> in obj_function_prime(x) 4 5 def obj_function_prime(x): ----> 6 val=[32*(x[0]**3)-6*x[1], 6*x[1]-6*x[0] 2] 7 return np.matrix(val) 8 ~anaconda3libsite-packagesnumpymatrixlibdefmatrix.py in __pow__(self, other) 231 232 def __pow__(self, other): --> 233 return matrix_power(self, other) 234 235 def __ipow__(self, other): <__array_function__ internals> in matrix_power(*args, **kwargs) ~anaconda3libsite-packagesnumpylinalglinalg.py in matrix_power(a, n) 620 a = asanyarray(a) 621 _assert_stacked_2d(a) --> 622 _assert_stacked_square(a) 623 624 try: ~anaconda3libsite-packagesnumpylinalglinalg.py in _assert_stacked_square(*arrays) 211 m, n = a.shape[-2:] 212 if m != n: --> 213 raise LinAlgError('Last 2 dimensions of the array must be square') 214 215 def _assert_finite(*arrays): LinAlgError: Last 2 dimensions of the array must be square
Что означает эта ошибка и как я могу ее устранить? Как мне преобразовать матрицу в квадратную, если она не определена таким образом?
Комментарии:
1. Это означает, что последние два измерения должны быть одинаковыми. Полная трассировка может помочь точно определить, в чем проблема. Кроме того, я бы посоветовал избавиться от
asmatrixвызовов. Попробуйте заставить это работать с обычными массивами numpy (они могут быть 2d, как np.matrix).2. @hpaulj Я отредактировал вопрос и добавил трассировку стека. Пожалуйста, проверьте, спасибо!
3. Что
x[0]**3предполагается делать? Как вы думаетеx[0], что такое (форма, тип, dtype?). Соответствует ли это тому, что есть на самом деле?
Ответ №1:
Использование np.matrix вызывает проблемы.
Давайте создадим небольшую матрицу:
In [273]: x = np.asmatrix([0,0])
In [274]: x
Out[274]: matrix([[0, 0]])
обратите внимание, что при индексации оно не меняется. Он выбирает первую «строку», но being np.matrix по-прежнему 2d.
In [275]: x[0]
Out[275]: matrix([[0, 0]])
И ** np.matrix , по сути, матрица квадратная x@x .
In [276]: x[0]**2
Traceback (most recent call last):
File "<ipython-input-276-3908b7334115>", line 1, in <module>
x[0]**2
File "/usr/local/lib/python3.8/dist-packages/numpy/matrixlib/defmatrix.py", line 231, in __pow__
return matrix_power(self, other)
File "<__array_function__ internals>", line 5, in matrix_power
File "/usr/local/lib/python3.8/dist-packages/numpy/linalg/linalg.py", line 621, in matrix_power
_assert_stacked_square(a)
File "/usr/local/lib/python3.8/dist-packages/numpy/linalg/linalg.py", line 204, in _assert_stacked_square
raise LinAlgError('Last 2 dimensions of the array must be square')
LinAlgError: Last 2 dimensions of the array must be square
Я не собираюсь пытаться выяснить, что вы пытаетесь сделать, но очевидно, что использование asmatrix — это не путь — по крайней мере, не понимая, как ведет себя такой массив.
Alternatively, the default kpss test is able to test stationarity on your training set without any problems:
In [99]: smodel = pm.auto_arima(Train['Count'], start_p=1, start_q=1, ...: test='kpss', ...: max_p=3, max_q=3, m=52, ...: start_P=0, seasonal=True, ...: d=None, D=1, trace=True, ...: error_action='ignore', ...: suppress_warnings=True, ...: stepwise=True) Performing stepwise search to minimize aic Fit ARIMA(1,0,1)x(0,1,1,52) [intercept=True]; AIC=nan, BIC=nan, Time=nan seconds Fit ARIMA(0,0,0)x(0,1,0,52) [intercept=True]; AIC=52.914, BIC=51.687, Time=0.085 seconds Fit ARIMA(1,0,0)x(1,1,0,52) [intercept=True]; AIC=56.852, BIC=54.398, Time=2.361 seconds Near non-invertible roots for order (1, 0, 0)(1, 1, 0, 52); setting score to inf (at least one inverse root too close to the border of the unit circle: 0.999) Fit ARIMA(0,0,1)x(0,1,1,52) [intercept=True]; AIC=nan, BIC=nan, Time=3.042 seconds Fit ARIMA(0,0,0)x(0,1,0,52) [intercept=False]; AIC=51.935, BIC=51.321, Time=0.249 seconds Fit ARIMA(0,0,0)x(1,1,0,52) [intercept=True]; AIC=54.913, BIC=53.072, Time=0.770 seconds Fit ARIMA(0,0,0)x(0,1,1,52) [intercept=True]; AIC=54.885, BIC=53.044, Time=2.421 seconds Near non-invertible roots for order (0, 0, 0)(0, 1, 1, 52); setting score to inf (at least one inverse root too close to the border of the unit circle: 0.997) Fit ARIMA(0,0,0)x(1,1,1,52) [intercept=True]; AIC=56.884, BIC=54.429, Time=4.564 seconds Near non-invertible roots for order (0, 0, 0)(1, 1, 1, 52); setting score to inf (at least one inverse root too close to the border of the unit circle: 0.999) Fit ARIMA(1,0,0)x(0,1,0,52) [intercept=True]; AIC=54.905, BIC=53.064, Time=0.581 seconds Fit ARIMA(0,0,1)x(0,1,0,52) [intercept=True]; AIC=nan, BIC=nan, Time=0.500 seconds Fit ARIMA(1,0,1)x(0,1,0,52) [intercept=True]; AIC=nan, BIC=nan, Time=0.653 seconds Total fit time: 24.058 seconds
Error in Python matrix calculation
In this case, if the matrix is not a square matrix, the following error will appear:

It is worth noting that when we use it in this way, the program will run normally

It seems that we have obtained the inverse of a non square matrix
Now let’s verify:

If you look at it carefully, it’s not a unit array. I think this method is not feasible, but with the idea of blog rigor, I decided to see the results of the square array

seeing here, I found that the inversion of square matrix also appeared abnormal. I can’t help but look carefully. The original term which should be 0 is very small. Friends who have studied numerical analysis should know that this is a non-zero problem caused by the rounding error of computer, so we can regard both as unit matrix
note: don’t convert the data type at will here, because converting the data type will result in the loss of data accuracy. For example, the unit matrix mentioned above will change when converting the data type, and a bit on the diagonal line may become 0. the unit matrix mentioned above will change when converting the data type
Similar Posts:
Lingerror last 2 dimensions of the array must be square
reason
Because numpy uses X directly= numpy.linalg.solve (a, b) we must make sure that a is a square matrix, but my matrix is not a square matrix
solve
The least square method: C= np.linalg.lstsq (A, B, rcond=None)[0]
problem
It seems to be an equation with infinite solutions, and I don’t know how to output a unique solution in a specific range
Read More:
- Array of PHP_ diff,array_ intersect,array_ merge, in_ Is there a limit on the number of arrays in array?
- If JavaScript exceeds the length of the array, no error will be reported
- The method of constructing even order magic square (n = 4 * m)
- [solved] error: valueerror: expected 2D array, got scalar array instead
- Type error: the JSON object must be STR, bytes or byte array, not ‘textiowrapper’
- “Typeerror: invalid dimensions for image data” in Matplotlib drawing imshow() function
- Python judge perfect square number
- The errors dimensions of materials being qualified are not persistent
- error C2057: expected constant expression (Can the size of an array in C language be defined when the program is running?)
- In R language, for loop or array truncation, the following error occurs only 0’s may be mixed with negative subscripts
- Square root of X (implementation of binary search)
- Error using ones Size inputs must be integers. Error in testdisplay1 (line 38) array=-ones(buf+m*(s
- Two dimensional array and pointer to one dimensional array
- Video prediction beyond mean square error
- Variable type error: error of array occurs when TP5 controller receives the array of post
- Tensorflow: How to use expand_Dim() to add dimensions
- In machine learning, the prediction errors in sklearn, such as mean square error, etc
- Python’s direct method for solving linear equations (5) — square root method for solving linear equations
- After Java application is deployed in Linux environment, Chinese is displayed as square solution
- Quickly convert map to ordered array
Я определил u и v
u = np.array([[1],
[1]])
v = np.array([[1],
[-1]])
И я хочу найти A
Au = np.array([[3],
[2]])
Av = np.array([[-1],
[-2]])
Так что я закодировал вот так
A = np.linalg.solve(u,Au)
A = np.linalg.solve(v,Av)
print(A)
А потом я получил ошибку
LinAlgError Traceback (most recent call last)
<ipython-input-21-416fc4de15b6> in <module>
12 [-2]])
13
---> 14 A = np.linalg.solve(u,Au)
15 A = np.linalg.solve(v,Av)
16 print(A)
<__array_function__ internals> in solve(*args, **kwargs)
~anaconda3libsite-packagesnumpylinalglinalg.py in solve(a, b)
384 a, _ = _makearray(a)
385 _assert_stacked_2d(a)
--> 386 _assert_stacked_square(a)
387 b, wrap = _makearray(b)
388 t, result_t = _commonType(a, b)
~anaconda3libsite-packagesnumpylinalglinalg.py in _assert_stacked_square(*arrays)
211 m, n = a.shape[-2:]
212 if m != n:
--> 213 raise LinAlgError('Last 2 dimensions of the array must be square')
214
215 def _assert_finite(*arrays):
LinAlgError: Last 2 dimensions of the array must be square
Как я могу это исправить?
1 ответ
Лучший ответ
Предполагая, что A одинаково в обоих уравнениях, у вас есть 4 уравнения с 4 неизвестными:
A[0, 0] * u[0] + A[0][1] * u[1] = Au[0]
A[1, 0] * u[0] + A[1][1] * u[1] = Au[1]
A[0, 0] * v[0] + A[0][1] * v[1] = Av[0]
A[1, 0] * v[0] + A[1][1] * v[1] = Av[1]
Это можно перефразировать как матричное уравнение B a = Auv, где
a— значенияAв вектореAuv— конкатенированные векторыAuиAv,Bсодержит значенияuиv.
import numpy as np
u = [1, 1]
v = [1, -1]
Au = [3, 2]
Av = [-1, -2]
B = [
[u[0], u[1], 0, 0],
[0, 0, u[0], u[1]],
[v[0], v[1], 0, 0],
[0, 0, v[0], v[1]]]
Auv = np.concatenate([Au, Av])
A = np.linalg.solve(B, Auv).reshape(2, 2)
print("A:n", A)
Матрица A:
1 2
0 2
0
Igor
12 Сен 2020 в 09:06
Using np.matrix is causing problems.
Lets make a small matrix:
In [273]: x = np.asmatrix([0,0])
In [274]: x
Out[274]: matrix([[0, 0]])
note that when you index it, it doesn’t change. It selects the first ‘row’, but being np.matrix is still 2d.
In [275]: x[0]
Out[275]: matrix([[0, 0]])
And ** of np.matrix is matrix square, effectively [email protected].
In [276]: x[0]**2
Traceback (most recent call last):
File "<ipython-input-276-3908b7334115>", line 1, in <module>
x[0]**2
File "/usr/local/lib/python3.8/dist-packages/numpy/matrixlib/defmatrix.py", line 231, in __pow__
return matrix_power(self, other)
File "<__array_function__ internals>", line 5, in matrix_power
File "/usr/local/lib/python3.8/dist-packages/numpy/linalg/linalg.py", line 621, in matrix_power
_assert_stacked_square(a)
File "/usr/local/lib/python3.8/dist-packages/numpy/linalg/linalg.py", line 204, in _assert_stacked_square
raise LinAlgError('Last 2 dimensions of the array must be square')
LinAlgError: Last 2 dimensions of the array must be square
I’m not going try to figure out what you are trying to do, but clearly using asmatrix is not the way to go — at least not without understanding how such an array behaves.
python – LinAlgError: Last 2 dimensions of the array must be square
In case you still havent found an answer, or in case someone in the future has this question.
To solve Ax=b:
numpy.linalg.solve uses LAPACK gesv. As mentioned in the documentation of LAPACK, gesv requires A to be square:
LA_GESV computes the solution to a real or complex linear system of equations AX = B, where A is a square matrix and X and B are rectangular matrices or vectors. Gaussian elimination with row interchanges is used to factor A as A = PL*U , where P is a permutation matrix, L is unit lower triangular, and U is upper triangular. The factored form of A is then used to solve the above system.
If A matrix is not square, it means that you either have more variables than your equations or the other way around. In these situations, you can have the cases of no solution or infinite number of solutions. What determines the solution space is the rank of the matrix compared to the number of columns. Therefore, you first have to check the rank of the matrix.
That being said, you can use another method to solve your system of linear equations. I suggest having a look at factorization methods like LU or QR or even SVD. In LAPACK you can use getrs, in Python you can different things:
- first do the factorization like QR and then feed the resulting matrices to a method like
scipy.linalg.solve_triangular - solve the least-squares using
numpy.linalg.lstsq
Also have a look here where a simple example is formulated and solved.
A square matrix is a matrix with the same number of rows and columns. The matrix you are doing is a 3 by 2. Add a column of zeroes to fix this problem.
python – LinAlgError: Last 2 dimensions of the array must be square
Related posts on python :
- Plot Ellipse with matplotlib.pyplot (Python)
- List of zeros in python
- python – How do I put a variable’s value inside a string?
- python argparse choices with a default choice
- python – Anaconda failed to create process
- Conversion from JavaScript to Python code?
- python – collapse cell in jupyter notebook
- python – How to use norm.ppf()?
$begingroup$
I’m trying to find the intersection of lines $y=a_1x+b_1$ and $y=a_2x+b_2$ using numpy.linalg.solve(). What I can’t get my head around is how to correctly make $A$ a square matrix for solve() to work. I’m familiar with solving linear equation systems, but there’s something here I don’t get.
What I’d like to do is:
def meeting_lines(a1, b1, a2, b2):
a = np.array([[a1], [a2]])
b = np.array([b1, b2])
return np.linalg.solve(a, b)
def main():
a1=1
b1=4
a2=3
b2=2
y, x = meeting_lines(a1, b1, a2, b2)
Where I expect $y=-3$ and $x=1$. However, this fails with numpy.linalg.LinAlgError: Last 2 dimensions of the array must be square.
Thank you very much for your help, trying to figure this out has messed up my day already!
asked Apr 1, 2019 at 12:47
![]()
$endgroup$
1
$begingroup$
You should formulate your lines as follows to have $(x, y)$ as unknowns:
$$begin{align}
left.begin{matrix}
a_1x-y=-b_1\
a_2x-y=-b_2
end{matrix}right}
rightarrow
overbrace{
begin{bmatrix}
a_1& -1\
a_2& -1
end{bmatrix}
}^{boldsymbol{a}}
overbrace{
begin{bmatrix}
x\
y
end{bmatrix}
}^{boldsymbol{x}}
=
overbrace{
begin{bmatrix}
-b_1\
-b_2
end{bmatrix}
}^{boldsymbol{b}}
end{align}$$
Therefore, the code should be:
import numpy as np
def meeting_lines(a1, b1, a2, b2):
a = np.array([[a1, -1], [a2, -1]])
b = np.array([-b1, -b2])
return np.linalg.solve(a, b)
a1=1
b1=4
a2=3
b2=2
x, y = meeting_lines(a1, b1, a2, b2)
print(x, y)
which outputs:
1.0 5.0
answered Apr 1, 2019 at 13:52
EsmailianEsmailian
8,8672 gold badges27 silver badges45 bronze badges
$endgroup$