我目前正在致力于实现牛顿-拉夫森算法来解决统计问题。但是,我遇到了矩阵乘法的问题,导致以下错误: TypeError: 'numpy.ndarray' object is not callable.
我使用的代码是:
def U_score(x, theta):
a = theta[0]
b = theta[1]
n = len(x)
d_a = -sp.digamma(a) + sp.digamma(a + b) + sum(np.log(x)) / n
d_b = -sp.digamma(b) + sp.digamma(a + b) + sum(np.log(1 - x)) / n
return np.array([d_a, d_b])
def Hessiana(x, theta):
a = theta[0]
b = theta[1]
h11 = sp.polygamma(1, a + b) - sp.polygamma(1, a)
h12 = sp.polygamma(1, a + b)
h21 = sp.polygamma(1, a + b) - sp.polygamma(1, b)
h22 = sp.polygamma(1, a + b)
return np.array([[h11, h12], [h21, h22]])
def H_inv(x, theta):
H = Hessiana(x, theta)
ridge = 1e-6 # Small constant
H_ridge = H + ridge * np.eye(H.shape[0])
return np.linalg.inv(H_ridge)
def max_likelihood(x, theta, tol):
theta_new = np.array([0, 0])
while np.linalg.norm(theta_new - theta) > tol:
theta_new = theta - H_inv(x, theta) @ U_score(x, theta)
return theta_new
x = np.random.beta(2, 5, 100)
theta = np.array([1,1])
U = U_score(x, theta)
H = Hessiana(x, theta)
H_inv = H_inv(x, theta)
emv = max_likelihood(x, theta, 1e-5)
print(emv)
错误是:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[80], line 1
----> 1 emv = max_likelihood(x, theta, 1e-5)
2 print(emv)
Cell In[78], line 4
2 theta_new = np.array([0, 0])
3 while np.linalg.norm(theta_new - theta) > tol:
----> 4 theta_new = theta - H_inv(x, theta) @ U_score(x, theta)
5 return theta_new
TypeError: 'numpy.ndarray' object is not callable
您创建了一个名为
H_inv
的变量,它是 H_inv
函数的返回值(此结果是一个 numpy 数组),并且这样做会覆盖该函数。
H_inv = H_inv(x, theta)
当您在覆盖
max_likelihood
后调用 H_inv
时,Python 在全局范围内找到 H_inv
,但现在这是一个 numpy 数组而不是函数。
一个选项:将函数重命名为
get_H_inv
或类似名称,这样就不会将变量(函数的结果)与函数本身混淆。