创建类对象时出现类型错误

2024-05-20 10:10:24 发布

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

我在研究神经网络。当我在NNetwork内部使用函数时,它会引发:

Traceback (most recent call last):
  File "C:\Python27\MyPython\MyNeuralNetwork.py", line 72, in <module>
    NeuralNet.train([[3,5,2],[10,8,1],[35,3,6],[345,3,32]])
  File "C:\Python27\MyPython\MyNeuralNetwork.py", line 67, in train
    self.train331()
  File "C:\Python27\MyPython\MyNeuralNetwork.py", line 44, in train331
    x1 = self.UseNN(N1,x)
TypeError: UseNN() takes exactly 1 argument (3 given)

我的代码是:

import math, time

class Neuron():
    def __init__(self,weight,thresh, alpha=.1):
        self.thresh = thresh
        self.weight = weight
        self.alpha = alpha
    def use(self,Input):
        x = Input[0]*self.weight
        y = Input[1]*self.weight;
        z = Input[2]*self.weight;
        return[(x+y+z)]

    def adjustWeight(subtract = False):
        if subtract == False: self.weight += alpha
        else: self.weight -= alpha

class NNetwork():
     def __init__(self,alpha = .1):
         self.alpha = alpha
     def UseNN((NN,InputList)):
         x = NN.use(InputList)
         if x[0] > x[1]: return x[0]
         else: return 0
     def train331(self):
         #Creates the Neurons, assigning the weights, threshholds, and alpha
         N1 = Neuron(3,7,.1)
         N2 = Neuron(7,3,.1)
         N3 = Neuron(3,9,.1)
         #NextLevel
         N4 = Neuron(-6,0,.1)
         N5 = Neuron(10,4,.1)
         N6 = Neuron(1,6,.1)
         #OutputLevel
         O1 = Neuron(0,0,.1)
        am = 1
        for amount in self.trainset:

            #It runs each neuron through an algorithm, 
            #then collects each result into a list
            x = self.trainset[am]
            print  "First layer: ",x
            x1 = self.UseNN(N1,x)
            x2 = self.UseNN(N2,x)
            x3 = self.UseNN(N3,x)

            y = [x1, x2, x3]
            print "Second layer: ",y
            y1 = self.UseNN(N4,y)
            y2 = self.UseNN(N5,y)
            y3 = self.UseNN(N6,y)

            z = [y1,y2,y3]

            z1 = self.UseNN(O1,z)
            am += 1
        print "Output layer: ",z1

    def train(self,trainingSet,epochs=100):

        self.epochs = epochs
        self.trainset = trainingSet
        self.train331()



NeuralNet = NNetwork()
NeuralNet.train([[3,5,2],[10,8,1],[35,3,6],[345,3,32]])

需要改变什么?你知道吗


Tags: inselfalphainputdeftrainfilepython27
2条回答

一个问题是您忘了在UseNN中添加self作为第一个参数。你知道吗

这里的另一个问题是(NN, InputList)周围的括号,这使得函数需要一个参数,一个元组。你知道吗

得到你想要的东西的正确方法是:

def UseNN(self, NN,InputList):

这会解决的。另外,应该避免对函数和变量使用CamelCase。它通常用于类,用来区分它们。你知道吗

希望有帮助!你知道吗

除非类方法用@classmethod修饰,否则第一个参数总是用self(实例本身)预先填充。因此,通过将UseNN的签名从

def UseNN((NN,InputList)):  # accepts self (NN), and 1 more argument

def UseNN(self, NN, InputList):  # accepts self, and 2 more arguments

问题会解决的。你知道吗

相关问题 更多 >