【问题标题】:"TypeError: 'numpy.ndarray' object is not callable " - Numpy Error“TypeError: 'numpy.ndarray' 对象不可调用” - Numpy 错误
【发布时间】:2019-12-10 23:19:11
【问题描述】:

这是我的代码。

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)

但是当我从“成本”函数中调用函数“h”时。 假设 = h(x, theta) 我收到错误:

TypeError: 'numpy.ndarray' object is not callable

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

请告诉我我做错了什么?

【问题讨论】:

  • 您确定没有在代码中的某处重新定义h 吗?这对我来说似乎是一个错字,涉及您未显示的代码。另外,为什么不简单地 h = np.dot ?函数是 Python 中的一等公民——您可以直接将它们分配给变量。
  • 另外,你说“我测试了它[参考h],这里是输出”,然后继续给出三行甚至没有提到h。这 3 行如何构成对h 的测试?请提供minimal reproducible example。您似乎没有向我们展示一些相关的东西。
  • 当我运行 j_list、theta_list、hypothesis = batch_gradient_descent(x, y, theta, alpha) 时,我再次遇到同样的错误

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


【解决方案1】:

我已经解决了这个问题,我只是这个声明

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

下面是工作代码的链接。

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

【讨论】:

    猜你喜欢
    • 2021-12-23
    • 1970-01-01
    • 2020-11-13
    • 2017-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-04
    • 2021-06-11
    相关资源
    最近更新 更多