Silverback9

#야생으로

Creative Coding 독학 제337일 2025년02월27일(목)

오늘은 베토벤 교향곡 제9번 두 번째 듣는 날~^^* 코딩 공부 정리해서 돌아올게요~^^* 쓩우웅~^^*

네~^^* 어제 우리가 조우했던 Supervised Learning Algorithm에 따라 코드를 만들어 보겠습니다~^^*

1. Provide the perceptron with inputs for which there is a known answer.
2. Ask the perception to guess the answer.
3. Compute the answer. (Did it get anwer right or wrong?)
4. Adjust all the weights according to the answer.
5. Return to Step 1 and repeat!

어제 우리는 가중치 값의 개선 방법을 공부했었는데요~^^*

가중치 변화량 = 새 가중치 - 옛 가중치
Weight Change = New Weight - Old Weight;
=>
새 가중치 = 옛 가중치 + 가중치 변화량
New Weight = Old Weight + Weight Change;

이때 가중치 변화량을 구하는 방법을 구체적으로 확인해 볼게요~^^*

 Weight Change = Error * Input; 

네~^^* 어느 쪽으로 몸을 틀어야 하는지를 알려주는 벡터 (Error)에 얼마만큼의 힘으로 틀어야 하는지를 알려주는 크기 값 Input을 곱하면, 어느 방향으로 얼마만큼의 힘으로 움직여야 하는지를 알려주는 Weight Change 가중치 변화량이 나올 것 같아요~^^*

그런데요~^^*

우리는 조금 조금씩 가중치값을 변화시켜가며 가장 적절한 가중치값을 찾아내면 좋을 것 같아요~^^* 한꺼번에 핸들을 휙~~ 돌리는 것 보다, 조금 조금씩 핸들을 돌려 가장 적절한 각도를 찾아내는 과정이라고 할까요~^^*

그래서요~^^* Supervised Learning 과정에서는, 학습 한 번 할 때 적절할 학습량을 설정해 놓고, 1회 분량 학습량을 반복하여 수행하면 좋을 것 같아요. 그래서 준비해 보았습니다~! 변수 학습률!

var learningRate;

class Perceptron {
  constructor(totalInputs, learningRate) {
   
    this.weights = [];
    this.learningConstant = learningRate;
    
    for (let i = 0; i < totalInputs; i++) {
      this.weights[i] = random(-1, 1);
    }
  }
   .
   .
   .
}
  

그런 후, Supervised Learning 회당 가중치 변화량 계산식에, learningRate 값도 반영해 보면 좋을 것 같아요.

Weight Change = Error * Input * learningRate;
=>
this.weights[i] += error * inputs[i] * this.learningConstant;

자 그럼~^^* 이제 우리~^^* class Perceptron에 Supervised Learning 기능을 장착해 볼까요~?^^*

train(inputs, desired) {
//1. Provide the perceptron with inputs for which there is a known answer. 
//1. known answer 알려진 답인 desired를 parameter로 받습니다.
 

    let guess = this.feedforward(inputs);
    let error = desired - guess;
     //2. Ask the perception to guess the answer.
     //2. feedforward 함수를 호출하여 input 값을 argument로 넘겨주며 답을 추측해 보라고 요구합니다. 
     //3. Compute the answer. (Did it get anwer right or wrong?) 
     //3.알려진 답 desired에서 feedforward 함수가 return해 준 추측값 guess를 뺄셈하여 변수 error에 저장합니다.
     

    for (let i = 0; i < this.weights.length; i++) {
      this.weights[i] += error * inputs[i] * this.learningConstant;
    }
     //4. Adjust all the weights according to the answer.
     //4. error값과 input 값과 learningConstatnt 회당 학습률을 곱하여 새로운 가중치값으로 조정합니다. 
    
  }
  //5. Return to Step 1 and repeat!
  //5. 이 전체 과정을 반복하면 좋겠지요~^^* 무한 반복함수인 draw()에서 train 함수를 호출하면 될 것 같네요~^^*
 

네~^^* 그럼 이제 우리~^^* Supervised Learning 기능이 탑재된 클래스 Perceptron 전체 코드를 한 번 볼까요~^^*

class Perceptron {
  constructor(totalInputs, learningRate) {
   
    this.weights = [];
    this.learningConstant = learningRate;
    
    for (let i = 0; i < totalInputs; i++) {
      this.weights[i] = random(-1, 1);
    }
    //1. 모든 입력값에 대하여, 그 입력값을 자신의 가중치로 곱한다.
    //1. For every input, multiply that input by its weight.
  }
  
  feedforward(inputs) {
    let sum = 0;
    for (let i = 0; i < this.weights.length; i++) {
      sum += inputs[i] * this.weights[i];
    }
    //2. Sum all of the weighted input
    //2. 가중치값이 반영된 입력값을 모두 더한다.
    return this.activate(sum);
    //총합에 대해 부호를 부여하는 함수 activate()을 호출합니다. 
  }
  
  activate(sum) {
    if (sum > 0) {
      return 1;
    } else {
      return -1;
    }
    //3. Compute the output of the perceptron based on that sum passed through an activiation function (the sign of the sum)
    //3. 총합에 +_부호를 부여하는 활성화 함수를 통과한 총합에 기반하여 perceptron 결과를 계산한다. 
  }
  
   train(inputs, desired) {
    let guess = this.feedforward(inputs);
    let error = desired - guess;
    for (let i = 0; i < this.weights.length; i++) {
      this.weights[i] += error * inputs[i] * this.learningConstant;
    }
  }
  //Supervised Learning 이 이루어 지는 함수입니다. 
  //1. known answer 알려진 답인 desired를 parameter로 받습니다. 
  //2. feedforward 함수를 호출하여 input 값을 arguement로 넘겨주며 답을 추측해 보라고 요구합니다. 
  //3.알려진 답 desired에서 feedforward 함수가 return해 준 추측값 guess를 뺄셈하여 변수 error에 저장합니다.
  //4. error값과 input 값과 learningConstatnt 회당 학습률을 곱하여 새로운 가중치값으로 조정합니다. 
  //5. 이 전체 과정을 반복하면 좋겠지요~^^* 무한 반복함수인 draw()에서 train 함수를 호출하면 될 것 같네요~^^*
}

오늘 저와 함께 Gradient Descent를 구현한 Supervised Learning Algorithm 기반 함수 train() 코드를 만들어 주셔서 감사합니다~^^*

내일은 우리~^^* 이 훈련과정을 통해서 정답을 찾아가는 과정을 시각적으로 표현해 볼까요~^^*

네~^^* 좋아요~^^* 고마워요~^^*

오늘도 멋진 아침! 맛있는 점심! 따뜻한 저녁! 드시고요!

보람찬 하루를 자유롭게 날아다니다

gradual descend하여

편안한 밤에 안착하시기 바래요~^^*

깊은 밤 코~^^* 하시구요~^^*

네~^^* 꿈은 이루어 집니다~^^*

댓글 남기기