调用Neural_Networks.forward(X)时出现sigmoid参数不匹配错误的原因?
Hey there! Let's figure out why you're getting that sigmoid() takes 1 positional argument but 2 were given error.
The main issue here is how you've defined the sigmoid method inside your Neural_Networks class. In Python, all instance methods of a class need to include self as their first parameter—this is how the method knows which instance of the class it's operating on. When you call self.sigmoid(self.z2), Python automatically passes self as the first argument to the function, plus your self.z2 as the second. But your current sigmoid only expects one argument (z), hence the mismatch.
On top of that, there's a tiny typo in your forward method: you assign to self.Z3 (capital Z) but then try to use self.z3 (lowercase z) when calculating yHat—that'll throw an attribute error once you fix the sigmoid issue.
Here's the corrected version of your code with both fixes:
import numpy as np class Neural_Networks(object): def __init__(self): self.inputLayerSize = 2 self.outputLayerSize = 1 self.hiddenLayerSize = 3 # weights self.W1 = np.random.randn(self.inputLayerSize, self.hiddenLayerSize) self.W2 = np.random.randn(self.hiddenLayerSize, self.outputLayerSize) def forward(self,X): # propagates input through network self.z2 = np.dot(X, self.W1) self.a2 = self.sigmoid(self.z2) self.z3 = np.dot(self.a2, self.W2) # Fixed capital Z to lowercase z yHat = self.sigmoid(self.z3) return yHat def sigmoid(self, z): # Added self as first parameter return 1/(1+np.exp(-z))
Let me break down the key fixes:
- Added
selfas the first parameter to thesigmoidmethod, so it properly accepts the instance reference plus your inputz. - Corrected
self.Z3toself.z3in theforwardmethod to match the variable name you use later.
Now when you call yHat = NN.forward(X), the sigmoid calls will work as expected!
内容的提问来源于stack exchange,提问作者Pankaj

