Python函数未定义,只是在类中声明

2024-09-28 19:00:50 发布

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

我在GradientDescent类中声明了一个函数isPrecisied(),并在另一个函数(gd())中调用它。我创建了一个类的实例,然后用它调用一个函数(b.gd()),其中包含isPrecisied()函数,方法如下

        import numpy as np
        import matplotlib.pyplot as plt

        class GradientDescent:
            def __init__(self,x,y,yhat,alpha=0.01,pre=0.1):
                self.x=x # This is the x array
                self.y=y  # y is the array  
                self.yhat=yhat  # yhat is the array
                self.precision=pre
                self.alpha=alpha

            def isPrecisied(self,e):
                if (np.sum(e)/2)>self.precision:
                    return False
                return True

            def gd(self):
                self.beta=[0.0]*len(self.y)
                error=[]
                while True:
                    for j in range(0,len(self.y),1):
                        temp=self.beta[0]+np.sum(np.multiply(self.beta,self.x))
                        error.append(np.square(self.y[j]-temp))
                    t=isPrecisied(error)
                    print(np.sum(error)/2)
                    if t==False:
                        self.beta=np.subtract(self.beta,self.alpha*np.array(self.beta))
                    else:
                        return self.beta


                #take the average precision by 1/2*summition((y-yhat)^2)

                #B0(t+1) = B0(t) – alpha * error(of individual not combined)


        a = GradientDescent([1,2,3,4,5],[10,20,30,40,50],[11,21,30,38,48])
        b=a.gd()

我有个错误:

Traceback (most recent call last):

  File "<ipython-input-10-744f30ba0c28>", line 2, in <module>
    b=a.gd()

  File "<ipython-input-9-13f85a04a1e0>", line 23, in gd
    t=isPrecisied(error)

NameError: name 'isPrecisied' is not defined

请告诉我哪里出错了。你知道吗


Tags: the函数selfalphaisdefnperror