I’m currently working on implementing a Newton-Raphson algorithm to solve a statistical problem. However, I’m encountering an issue with matrix multiplication that is resulting in the following error: TypeError: ‘numpy.ndarray’ object is not callable.
The code i’m using is:
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)
and the error is:
---------------------------------------------------------------------------
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
0
You created a variable named H_inv
which is the return of the H_inv
function (this result is a numpy array) and doing that overwrites the function.
H_inv = H_inv(x, theta) # <- Overwrites the name of the function with its result
When you then call max_likelihood
after H_inv
(the function) has been overwritten, Python finds the H_inv
in the global scope, but this is now a numpy array and not a function.
One option: rename your function to get_H_inv
or something like that so you don’t confuse the variable (result of the function) with the function itself.