gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 21:29:24 25 4
gpt4 key购买 nike

我有一个在其中创建多个函数的类(“ 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'

最佳答案

更改

    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将具有一个值

关于python - 从另一类的一个类调用函数时发生TypeError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53623707/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com