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

2024-10-02 00:40:56 发布

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

我有一个类(“LogicalUnit”),我在其中创建多个函数,还有一个类(“TestModule”),我在其中使用上述函数。但是,当我在TestModule中使用LogicalUnit中的函数时,调用带有两个参数的numpys dot函数时会出现类型错误(“*:'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'

Tags: 函数inpyself类型nplinedot
1条回答
网友
1楼 · 发布于 2024-10-02 00:40:56

改变

    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

也许吧? 您也可以将w作为paremter从computeGradient中删除

或者,您也可以从computeWeights或其他什么返回w

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

相关问题 更多 >

    热门问题