如何使用类方法作为可调用函数

2024-09-30 09:24:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我在Python中运行渐变检查,如下所示:

class NeuralNetwork:
    def gradient_checking(self):
        m = 5
        theta1 = debuginitializeweights(self.size[1], self.size[0])
        theta2 = debuginitializeweights(self.size[2], self.size[1])
        thetas = vectorize([theta1, theta2], self.size)

        X = debuginitializeweights(m, self.size[0] - 1)
        y = 1 + np.mod(np.array(range(m)), 3)

        return scipy.optimize.check_grad(self.cost, self.grad, thetas, [X, y])  

其中类方法的签名为:

def cost(self, thetas, X, label):   
def grad(self, thetas, X, label):

但是,当运行梯度检查时,它是这样说的

File "/home/andrey/Data/Hacking/ML/Coursera_Andrew/neuralnetwork.py", line 142, in gradient_checking
    return check_grad(self.cost, self.grad, thetas, [X, y])
  File "/usr/local/lib/python2.7/dist-packages/scipy/optimize/optimize.py", line 656, in check_grad
    return sqrt(sum((grad(x0, *args) -
TypeError: grad() takes exactly 4 arguments (3 given)

如何修复此错误?你知道吗


Tags: selfsizereturndefchecknpoptimizecost
2条回答

堆栈跟踪准确地告诉您需要知道的内容:

TypeError: grad() takes exactly 4 arguments (3 given)

您的grad签名反映了4个参数要求:

def grad(self, thetas, X, label):

我看到您试图在对grad()的调用中使用元组解包:

return sqrt(sum((grad(x0, *args))))

调用grad()时传递的隐式self将位于参数列表中的self位置,x0将位于thetas位置,留下Xlabel*args填充。尝试打印args或用PDB检查它以确认它包含两个项目。由于您在尝试解包不可iterable时没有得到ValueError,因此它可能是正确的类型。听起来它可能没有你所期望的两个项目。你知道吗

原来这只是可选的参数问题。下面是一个简单的例子:

 from scipy.optimize import check_grad
class NeuralNetwork:
    def cost(self, x, A, b):
        return x[0] ** 2 - 0.5 * x[1] ** 3 + A * b

    def grad(self, x, A, b):
        return [2 * x[0] + A, -1.5 * x[1]**2 +b]

a = NeuralNetwork()
print a.cost([1.5, -1.5], 10, 1)
print check_grad(a.cost, a.grad, [1.5, -1.5], 10, 1)

以前我做过:

 check_grad(a.cost, a.grad, [1.5, -1.5], (10, 1))

这就是为什么它总是漏掉论点。你知道吗

相关问题 更多 >

    热门问题