我已经创建了一个计算QR分解和测试.It包含几个不同功能的模块。我已将此文件保存为Numla.py。我想在木星笔记本中导入这些函数,但是我一直有这个错误。我还尝试过其他导入方法,例如从Numla进口qr、从Numla import *、导入Numla as num。但我一直在说同一个名字的错误。
进口Numla Numla.qr(A)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Input In [11], in <cell line: 2>()
1 import Numla
----> 2 Numla.qr(A)
NameError: name 'A' is not definedimport numpy as np
def qr(A):
#source: #https://rosettacode.org/wiki/QR_decomposition#Python
m, n = A.shape
Q = np.eye(m)
for i in range(n - (m == n)):
H = np.eye(m)
#calculates Householder matrix i: rows and i: columns from A i: rows and ith column
H[i:, i:] = make_householder(A[i:, i])
Q = Q@H
A = H@A
return Q, A
def make_householder(a):
#finds orthogonal vector to mirror
u = a / (a[0] + np.copysign(np.linalg.norm(a), a[0]))
u[0] = 1
H = np.eye(a.shape[0])
#finds Householder projection
H -= (2 / np.dot(u, u)) * u[:, None] @ u[None, :]
return H
def compose(qr, make_householder):
def comp(arg):
return qr()(make_householder(arg))
return comp
def test_compose(qr, make_householder):
m=3
n=3
A = np.random.rand(m, n)
Q, R = qr(A)
Q.round(3)
R.round(3)
Q_np, R_np=np.linalg.qr(A)
np.allclose(Q, Q_np)
np.allclose(R, R_np)
print (" QR-Decomposition and test ")
print ('\n')
print ("Q vs Q_np")
print (Q.round(8))
print (Q_np)
print ('\n')
print ("R vs R_np")
print (R.round(8))
print (R_np)
print ('\n')
if np.allclose(Q, Q_np) == True:
print('ok')
if np.allclose(R, R_np) == True:
print ('ok')
print('\n')
return
#test_compose(qr, make_householder)
def back_substitution(U, y):
n = U.shape[0]
x = np.zeros_like(y, dtype=np.double);
x[-1] = y[-1] / U[-1, -1]
for i in range(n-2, -1, -1):
x[i] = (y[i] - np.dot(U[i,i:], x[i:])) / U[i,i]
return x
def linsolve_qr():
#QR decomposition with qr function
Q, R = np.linalg.qr(A)
y = Q.T @ B
#solve for x using back substitution method
K=back_substitution(R, y)
#using np solver to prove back substitution+QR method works
L=np.linalg.solve(R, y)
return
def test_linsolve_qr():
A = np.array([
[6., 7., 8.],
[2., 4., 3.],
[8., 1., 2]])
B = np.array([1., -2., 3.])
#QR decomposition with qr function
Q, R = np.linalg.qr(A)
y = Q.T @ B
K=back_substitution(R, y)
L=np.linalg.solve(R, y)
print (" QR-Decomposition implementation to solve LGS ")
print ('\n')
print (back_substitution(R, y))
print (np.linalg.solve(R, y))
if np.allclose(K, L) == True:
print('ok')
return
#test_linsolve_qr()
if __name__ == "__main__":
test_compose(qr, make_householder)
test_linsolve_qr()发布于 2022-11-05 23:22:21
要导入函数,只需使用函数名而不带参数:
from Numla import qr然后,您可以在笔记本中使用函数qr。
我已经在本地测试过了,而且效果很好。只要Numla.py位于Python中的一个目录中,它就能正常工作。如果您继续与Colab有问题,您可能需要咨询this answer。
https://stackoverflow.com/questions/74331982
复制相似问题