如何修复:'TypeError:'numpy.ndarray'对象无法在scipy fmin_bfgs中调用

时间:2019-04-26 16:23:57

标签: python-3.x machine-learning optimization scipy callable-object

我正在尝试用Python而不是matlab解决Andrew NG的第3周课程分配问题,我发现fmin_bfgs与ex2.m文件中的fminunc类似。

问题是,当我尝试输入cost函数和将梯度计算为fmin_bfgs的函数时,它返回一个回溯,内容为: TypeError:“ numpy.ndarray”对象不可调用。 我在尝试调试问题时遇到了困难,因此将不胜感激

# code that produces the error:

results = opt.fmin_bfgs(costFunction.cost_function(weights, data_input, desired_output), weights,
                        fprime=costFunction.compute_grad(weights, data_input, desired_output), maxiter=400)

#the costFunction module:

import numpy as np
import sigmoid


def cost_function(theta, x, y):
    size = np.shape(x)
    z = np.dot(x, theta)
    h = sigmoid.sigmoid(z)
    j = (1 / size[0]) * (np.dot(-y, np.log(h)) - np.dot((1 - y), np.log(1 - h)))
    return j


def compute_grad(theta, x, y):
    size = np.shape(x)
    z = np.dot(x, theta)
    h = sigmoid.sigmoid(z)
    error = np.subtract(h, y)
    grad = (1 / size[0]) * np.dot(np.transpose(error), x)
    return grad

0 个答案:

没有答案