尽管我在类方法中拥有 “self”,但我仍然收到“train()需要0个位置参数,但给出了3个”的错误提示。

2024-03-29 07:27:14 发布

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

我在stackoverflow上搜索过这件事,也看到了类似的问题, 但他们没有一个和我有完全相同的问题。你知道吗

我正在尝试运行一个名为train()的类方法,它有3个参数,包括“self”

但我一直有个错误:

train() takes 0 positional arguments but 3 were given

我想知道是怎么回事,怎么解决?你知道吗

下面是我尝试运行的代码:

>>> n = nn.neuralNetwork(3, 3, 3, 0.3)
>>> c = n.train([1.0, 0.5, -1.5], [5,5,5])
Traceback (most recent call last):
  File "<pyshell#35>", line 1, in <module>
    c = n.train([1.0, 0.5, -1.5], [5,5,5])
TypeError: train() takes 0 positional arguments but 3 were given

下面是nn类的样子:

import numpy as np
import scipy.special

#neural network class definition
class neuralNetwork:

    #initialize the neural network
    def __init__(self, inputnodes, hiddennodes, outputnodes, learningrate):
        #set number of nodes in each input, hidden, output layer
        self.inodes = inputnodes
        self.hnodes = hiddennodes
        self.onodes = outputnodes

        self.lr = learningrate

        self.wih = np.random.normal(0.0, pow(self.inodes, -0.5), (self.hnodes, self.inodes))
        self.who = np.random.normal(0.0, pow(self.hnodes, -0.5), (self.onodes, self.hnodes))

        # activation function is the sigmoid function
        self.activation_function = lambda x : scipy.special.expit(x)

        pass



    def train(self, inputs_list, targets_list):

        inputs = np.array(inputs_list, ndmin = 2).T
        targets = np.array(targets_list, ndmin = 2).T


        hidden_inputs = np.dot(self.wih, inputs)

        hidden_outputs = self.activation_function(hidden_inputs)


        final_inputs = np.dot(self.who, hidden_outputs)

        final_outputs = self.activation_function(final_inputs)


        output_errors = targets - final_outputs

        hidden_errors = np.dot(self.who.T, output_errors) 

        self.who += self.lr * numpy.dot((output_errors * final_outputs *
                                        (1.0-final_outputs)), np.transpose(hidden_outputs))

        self.wih += self.lr * numpy.dot((hidden_errors * hidden_outputs *
                                         (1.0-hidden_outputs)), np.transpose(inptus))

Tags: selfoutputnpfunctiontrainoutputsactivationdot
1条回答
网友
1楼 · 发布于 2024-03-29 07:27:14

您可以使用ipython运行它:

In [2]: import nn

In [3]: n = nn.neuralNetwork(3, 3, 3, 0.3)

In [4]: c = n.train([1.0, 0.5, -1.5], [5,5,5])
                                     -
NameError                                 Traceback (most recent call last)
<ipython-input-4-538d3963f639> in <module>()
  > 1 c = n.train([1.0, 0.5, -1.5], [5,5,5])

~/zhidao/nn.py in train(self, inputs_list, targets_list)
     40
     41
 -> 42         output_errors = target - final_outputs
     43
     44         hidden_errors = np.dot(self.who.T, output_errors)

NameError: name 'target' is not defined

In [5]: n.train??  # type double `?` will show the source code of `def train`

相关问题 更多 >