2013-10-19 3 views
1

박사 학위 과정에서 우리는 파이썬 스크립트로 OR, AND, XOR 연산을 계산하는 단일 뉴런 신경 회로망을 할당 받았다. 내 코드에서 나를 미치게 만드는 아주 이상한 오류가있다. 모든명백한 이유없이 변하는 변수

먼저 내가 Vector 클래스가 있습니다 둘째

class Vector3D:                   # Defines the Vector3D class 
    def __init__(self,bias,x,y):               # Defines the variables for the Vector3D class 
     self.bias = bias 
     self.x = x 
     self.y = y 
    def __add__(self,other):                # Defines the built-in "add" ("+") operation for Vector3D 
     return Vector3D(self.bias+other.bias,self.x+other.x,self.y+other.y) 
    def __mul__(self,other):                # Defines the built-in "multipication" ("*") operation for Vector3D 
     if(isinstance(other,int)): 
      return Vector3D(self.bias * other, self.x * other, self.y * other) 
     else: 
      return Vector3D(self.bias * other.bias, self.x * other.x, self.y * other.y) 
    def __str__(self):                  # Defines the built-in string return value for Vector3D 
     return "Vector(%f,%f,%f)" % (self.bias, self.x, self.y) 
    def UpdateWeights(self,eta, targetOutput, currentOutput, valueX, valueY, valueBias): # Function for updating the weights 
     self.bias = self.bias + (eta * (targetOutput - currentOutput) * valueBias) 
     self.x = self.x + (eta * (targetOutput - currentOutput) * valueX) 
     self.y = self.y + (eta * (targetOutput - currentOutput) * valueY) 
     return Vector3D(self.bias,self.x, self.y) 
    def getX(self):                  # Function for getting the x value of a vector 
     return self.x 
    def getY(self):                  # Function for getting the y value of a vector 
     return self.y 
    def getBias(self):                  # Function for getting the bias value of a vector 
     return self.bias 

을, 나는 신경 클래스가 있습니다

class Neuron:                     # Defines the Neuron class 
    def __init__(self, dataTable, eta, theta, targetArrayOr, targetArrayAnd, targetArrayXor): # Function for defining the variables for initialization 
     self.dataTable = dataTable 

     self.eta = eta 
     self.theta = theta 

     self.targetArrayOr = targetArrayOr 
     self.targetArrayAnd = targetArrayAnd 
     self.targetArrayXor = targetArrayXor 

     self.wVbias = random.uniform(-0.2, 0.2) 
     self.wVX = random.uniform(-0.2, 0.2) 
     self.wVY = random.uniform(-0.2, 0.2) 
     self.weightVector = Vector3D(self.wVbias,self.wVX,self.wVY) 

     self.weightVectorOr = Vector3D(0,0,0) 
     self.weightVectorAnd = Vector3D(0,0,0) 
     self.weightVectorXor = Vector3D(0,0,0) 

    def TrainForOr(self) :                  # Function training the weight vector for OR operation 
     iteration = 0                   # Number of iterations 
     check = 0                    # Initial value of the while loop 
     finalCheck = 200                   # Final value of the while loop 
     targetReached = False                 # Boolean variable for if the target is reached 
     rowNb = 0                    # Initial value of the index number in the data table 
     weightVector = self.weightVector            # Initial weight vector 
     print(self.weightVector) 
     while check < finalCheck :                # Makes sure that the entire loop runs 200 times for accuracy 
      while rowNb < len(self.dataTable) :             # Makes sure every row is iterated 
       while targetReached == False: 
        D1dotW = DotProduct(self.dataTable[rowNb],weightVector)      # Dot product of the input vector and the weight vector 
        if(D1dotW > self.theta): 
         currentOutput = 1 
        elif(D1dotW <= self.theta): 
         currentOutput = 0 
        if(currentOutput == self.targetArrayOr[rowNb]): 
         targetReached = True 
        else: 
         iteration = iteration + 1 
         print(self.weightVector) 
         weightVector = weightVector.UpdateWeights(self.eta,self.targetArrayOr[rowNb], currentOutput, self.dataTable[rowNb].getX(), self.dataTable[rowNb].getY(), self.dataTable[rowNb].getBias()) 
         print(self.weightVector) 
         targetReached = False 


       targetReached = False 
       rowNb = rowNb + 1 

      check = check + 1 
      rowNb = 0 
     self.weightVectorOr = weightVector              # Sets the OR weight vector 
     return "OR - Final weight vector is " + str(weightVector) + " " + "("+ str(iteration) + " iteration(s))" 

나는 또한 AND 및 XOR 다른 방법이를하지만 그들은과 동일 사소한 변화와 함께 위.

이제 위의 코드 "오류"로 "작동"은 매우 작고 최종 결과를 변경하지 않습니다. 그러나 나는 그것이 왜 일어나는 지 이해하고 싶다.

weightVector = weightVector.UpdateWeights(self.eta,self.targetArrayOr[rowNb], currentOutput, self.dataTable[rowNb].getX(), self.dataTable[rowNb].getY(), self.dataTable[rowNb].getBias()) 
:

Vector(-0.051856,-0.099352,0.079270) 
Vector(-0.051856,-0.099352,0.079270) 
Vector(-0.001856,-0.099352,0.079270) 
Vector(-0.001856,-0.099352,0.079270) 
Vector(-0.001856,-0.099352,0.079270) 
Vector(-0.001856,-0.099352,0.079270) 
Vector(-0.001856,-0.099352,0.079270) 
Vector(-0.001856,-0.099352,0.079270) 
Vector(-0.001856,-0.099352,0.079270) 
Vector(-0.001856,-0.099352,0.079270) 
Vector(-0.001856,-0.099352,0.079270) 
Vector(-0.001856,-0.099352,0.079270) 
Vector(-0.001856,-0.099352,0.079270) 
Vector(-0.001856,-0.099352,0.079270) 
Vector(-0.001856,-0.099352,0.079270) 
Vector(-0.001856,-0.099352,0.079270) 
Vector(-0.001856,-0.099352,0.079270) 

이 초기 self.weightVector이 라인에서 변화되는 것을 의미한다 : 나는이 (가) GUI 코드의 나머지 부분 등과 함께 위의 코드를 실행하면

, 나는 콘솔 결과를 얻을 수

UpdateWeights 메서드에서 어떤 식 으로든 self.weightVector을 변경하지 않기 때문에이 내용을 이해할 수 없습니다.

누군가가 왜 이런 일이 일어 났는지 설명 할 수 있다면 감사하겠습니다.

+1

"위의 스 니펫을 실행할 때 ..."실제로 인스턴스를 만들고 사용하는 스 니펫이 표시되지 않습니다. 엉덩이. 이걸 포함시켜 주시겠습니까? –

답변

1

UpdateWeights() 메서드는 벡터를 수정합니다. 이것이 UpdateWeights()으로 전화하면 벡터가 바뀌는 이유입니다.

def UpdateWeights(self, eta, targetOutput, currentOutput, 
        valueX, valueY, valueBias): 
    """Returns a new vector with updated weights.""" 
    bias = self.bias + (eta * (targetOutput - currentOutput) * valueBias) 
    x = self.x + (eta * (targetOutput - currentOutput) * valueX) 
    y = self.y + (eta * (targetOutput - currentOutput) * valueY) 
    return Vector3D(bias, x, y) 

추신 : 여기

고정 버전 또한 문서는 주석이 아닌 문서화 문자열에 있어야합니다.

3

이 방법을 살펴 보자.

def UpdateWeights(self,eta, targetOutput, currentOutput, valueX, valueY, valueBias): 
    self.bias = self.bias + (eta * (targetOutput - currentOutput) * valueBias) 
    self.x = self.x + (eta * (targetOutput - currentOutput) * valueX) 
    self.y = self.y + (eta * (targetOutput - currentOutput) * valueY) 
    return Vector3D(self.bias,self.x, self.y) 
그것은 새로운 Vector3D 반환뿐만 아니라

뿐만 아니라 그 자체를 수정 (self) 및 이전 버전 사용자 설정 :

weightVector = self.weightVector 

그래서 weightVector.UpdateWeights를 호출하면 self 변경의 원인이됩니다

관련 문제