특별한 인공지능용 라이브러리 전혀 안쓰고 시도해 봤습니다.

옛날 1960년대 전산자원이 지극히 열악한 환경에서 시도한 방식이라 XOR을 시도하면 옛날처럼 틀린 값이 나옵니다.

 

결과 :

 

코드 :

/* "OR" problem with 1 neuron in ESP32
  ----------------------------------
   input1   |  input2   |  output
  ----------+-----------+-----------
   1(True)  |  1(True)  |  1(True)
   1(True)  |  0(False) |  1(True)
   0(False) |  1(True)  |  1(True)
   0(False) |  0(False) |  0(False)
  ----------------------------------*/
#include <math.h>

const int PatternCount = 4;  // 4 cases, 총 가능한 경우의 수
const int InputCol = 2;      // 2 key values (input1, input2)
const float learning_rate = 0.1;  // 학습률
const float x[PatternCount][InputCol] = {  // Inputs of OR - All cases
   {1, 1},  // 1(True)  |  1(True)
   {1, 0},  // 1(True)  |  0(False)
   {0, 1},  // 0(False) |  1(True)
   {0, 0}   // 0(False) |  0(False)
};

// known results (원하는 결과값)
const float y[PatternCount] = { 
   1, 
   1, 
   1, 
   0 
};

float w[InputCol]; // 가중치 (입력항 갯수만큼), 난수(Random)로 초기화할 것.
float b;           // 편향치 (항상 1개만 사용) - bias, 난수(Random)로 초기화할 것.
float b_x = 1.0;
int j;
float output;
float error;
float error_sum;
float tempval;
String s;

// 활성화 함수 (Activation Function)
float sigmoid (float n) {
    return 1/(1 + exp(-n));
}

void setup() {
   Serial.begin(19200);
   Serial.println(" ");
   Serial.println("OR problem solving using ESP32 with only 1 neuron.");
   
   // Initialize, 난수(Random)로 초기화할 것.  이번에는 대충 초기화했슴.
   w[0] = 0.7245;  // Any number (0 < n < 1) to initialize
   w[1] = 0.4356;  // Any number (0 < n < 1) to initialize
   b = 0.76254;    // Any number (0 < n < 1) to initialize

  // 첫번째 루프 : 2000번의 학습을 진행시킬 예정.
   for (int i = 1; i <= 2000; i++) {  
      error_sum = 0;  // 한번의 학습 결과를 저장 (기본 값은 0)

      // 두번째 루프  : 4번의 인스턴스 (ROW)를 사용함.
      j = 0;
      do {
         output = sigmoid((x[j][0] * w[0]) + (x[j][1] * w[1]) + b_x * b);   
         error = y[j] - output;
         w[0] = w[0] + (x[j][0]) * learning_rate * error;
         w[1] = w[1] + (x[j][1]) * learning_rate * error;
         b = b + b_x * learning_rate * error;
         error_sum += error;    
         j++;
      } while (j < 4);   
      
      if ((i % 200)==0) {  // 결과 표시 매 200번마다
         s = "";  s = s + i;  s = s +" - Output :";   s = s + output;
         s = s + "   Error_Sum :";  s = s + error_sum;
         Serial.println(s);
      }     
   }
   // 최종 확인
   Serial.println("-------- Final -----------");
   for (int i = 0; i < 4; i++) {
      s = i;  s = s + " - Output :";
      tempval = sigmoid((x[i][0] * w[0]) + (x[i][1] * w[1]) + b);
      s = s + tempval;  s = s + "   Round : ";   s = s + round(tempval);
      s = s + "  Exp.Y : ";  s = s + y[i];
      Serial.println(s);
   }
}

void loop() {
  
}

'인공지능 ESP32' 카테고리의 다른 글

ESP32에서 다층 신경망을 돌리고 결과를 저장하기 - (구상)  (0) 2021.10.09
Demo32_Simple_ML  (0) 2021.10.09
Code Block 실험.  (0) 2019.07.27

+ Recent posts