从另一类的一个类调用函数时发生TypeError

时间:2018-12-05 01:05:00

标签: python

我有一个在其中创建多个函数的类(“ LogicalUnit”)和一个我在其中使用所述函数的类(“ TestModule”)。但是,当我在TestModule中使用LogicalUnit中的函数时,通过调用带有两个参数的numpys点函数,我得到了类型错误(“ *的不支持的操作数类型:'int'和'NoneType'”)。我不确定为什么会出现类型错误,因为我还没有声明参数的类型。

import numpy as np
class LogicalUnit():
    def __init__(self, table):
        self.X = table[:,0:3]
        self.Y = table[:,3:]
        self.w = np.array([0.0,0.0,0.0]).reshape(3,1)
        self.w = self.computeWeights(self.w,self.X,self.Y)
    def computeGradient(self,w, X, Y):
        pred = np.dot(self.X,self.w)
        pred = self.sigma(pred)
        gradient = np.dot(self.X.T, (pred-self.Y))
        return gradient/len(Y)
    def computeWeights(self,w,X,Y):
        for i in range(iterations):
            temp = lr * self.computeGradient(self.w,self.X,self.Y)
            w-=temp

import LogicalUnit as lu
import numpy as np
orData = np.array([...])
orUnit = lu.LogicalUnit(orData)
print("orUnit ", orUnit.getCurrentWeights())

错误:

runfile('C:/Python/TestModule.py', wdir='C:/Python')
Traceback (most recent call last):

  File "<ipython-input-76-30a5f2d92222>", line 1, in <module>
    runfile('C:/Python/TestModule.py', wdir='C:/Python')

  File "C:\Anaconda\envs\Neural\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 704, in runfile
    execfile(filename, namespace)

  File "C:\Anaconda\envs\Neural\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 108, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

  File "C:/Python/TestModule.py", line 10, in <module>
    print("orUnit ", orUnit.getCurrentWeights())

  File "C:\Python\LogicalUnit.py", line 22, in getCurrentWeights
    return self.computeWeights(self.w,self.X,self.Y)

  File "C:\Python\LogicalUnit.py", line 19, in computeWeights
    temp = lr * self.computeGradient(self.w,self.X,self.Y)

  File "C:\Python\LogicalUnit.py", line 13, in computeGradient
    pred = np.dot(self.X,self.w)

TypeError: unsupported operand type(s) for *: 'int' and 'NoneType'

1 个答案:

答案 0 :(得分:0)

更改

    self.w = self.computeWeights(self.w,self.X,self.Y)

收件人

    self.computeWeights(self.X,self.Y)

还有

def computeWeights(self,w,X,Y):
    for i in range(iterations):
        temp = lr * self.computeGradient(self.w,self.X,self.Y)
        w-=temp

收件人

def computeWeights(self,X,Y):
    for i in range(iterations):
        temp = lr * self.computeGradient(self.w,self.X,self.Y)
        self.w-=temp

也许? 您也可以从computeGradient中删除w作为参数。

或者,您也可以从computeWeights之类返回w。

如果您不打算使用除计算机权重之外的w来调用任何这些函数,则可以将其存储在w实例变量中。这样,当您np.dot它时,this.w将具有一个值