“ TypeError:'numpy.ndarray'对象不可调用”-numpy错误

时间:2019-12-10 23:19:11

标签: python python-3.x numpy matrix-multiplication

这是我的代码。

def h(x, theta):                      # this is probability/hypotheses
    return np.dot(x, theta)


def cost(x, y, theta):                    # this is cost function
    m = x.shape[0]
    hypothesis = h(x, theta)
    error = hypothesis - y
    return 1 / (2 * m) * (np.dot(error.T, error))    # (1/2m)*sum[(error)^2]

我有一个函数“ h”,它计算2个矩阵的点积。并且它按预期工作。 我测试了,这里是输出

print("x.shape = ", x.shape)                         # x.shape =  (97, 2)
print("theta.shape =", theta.shape)                  # theta.shape = (2, 1)
print("my_hypothesis.shape =",  my_hypothesis.shape) # my_hypothesis.shape = (97, 1)

但是当我从内置的“ cost”函数中调用函数“ h”时。 假设= h(x,theta) 我遇到错误:

TypeError: 'numpy.ndarray' object is not callable

如果我用假设= np.dot(x,theta)代替线假设= h(x,theta),那么它工作正常。

请让我做什么错了?

1 个答案:

答案 0 :(得分:0)

我已经解决了这个问题,我只说了这句话

return (alpha * (1 / m) * (np.dot(error.T, x))).T

下面是工作代码的链接。

https://github.com/amitsuneja/MachineLeaning/blob/master/AndrewNG/Week2/Excercise01/Week2-LinearRegressionSingleVariable.py