2017년 11월 1일 수요일

[Neural Network] Perceptron (in C)

//
// perceptron (without step function)
//

#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#define TRAIN_SAMPLES 4
void main()
{
//
//training set for OR pattern
//
// input: X
double X[TRAIN_SAMPLES][2] =
{
0, 0, // 클래스 0
0, 1, // 클래스 1
1, 0, // 클래스 1
1, 1 // 클래스 1
};
// target Y
double Y[TRAIN_SAMPLES] =
{
0, 1, 1, 1
};

//
// weight
//
double W[3];
//------------------------------------------------------------
// 1) Training
//------------------------------------------------------------

//
// initialize W
//
for (int i = 0; i < 3; i++)
W[i] = ((double)rand() / RAND_MAX)*0.5 - 0.25;

unsigned int epoch = 0;
unsigned int MAX_EPOCH = 500;
double Etha = 0.05;

double output;
double x1, x2;
double target;
while (epoch++ < MAX_EPOCH)
{
//
// 1 epoch (for all training samples)
//
// compute deltaWi for each Wi
//
double deltaW[3];
for (int i = 0; i < TRAIN_SAMPLES; i++)
{
deltaW[0] = 0.0;
deltaW[1] = 0.0;
deltaW[2] = 0.0;

x1 = X[i][0];
x2 = X[i][1];
target = Y[i];

output = 1 * W[0] + x1 * W[1] + x2 * W[2];

deltaW[0] += (target - output) * 1;
deltaW[1] += (target - output) * x1;
deltaW[2] += (target - output) * x2;
}
//
// update W
//
W[0] = W[0] + Etha * (deltaW[0] / TRAIN_SAMPLES);
W[1] = W[1] + Etha * (deltaW[1] / TRAIN_SAMPLES);
W[2] = W[2] + Etha * (deltaW[2] / TRAIN_SAMPLES);
//
// compute the Error(Cost)
//
double cost;
cost = 0.0;

for (int i = 0; i < TRAIN_SAMPLES; i++)
{
x1 = X[i][0];
x2 = X[i][1];
target = Y[i];

output = 1 * W[0] + x1 * W[1] + x2 * W[2];

cost += (target - output) * (target - output);
}
cost = 0.5 * cost / TRAIN_SAMPLES;

printf("%05d: cost = %10.9lf \n", epoch, cost);
}
printf("training done\n\n");
//------------------------------------------------------------
// 2) Testing for the training set
//------------------------------------------------------------
for (int i = 0; i < TRAIN_SAMPLES; i++)
{
x1 = X[i][0];
x2 = X[i][1];
target = Y[i];
output = 1 * W[0] + x1 * W[1] + x2 * W[2];

printf("%2.1lf %2.1lf (%d) ----- %2.1lf \n", x1, x2, (int)target, output);
}
printf("training test done\n\n");

//------------------------------------------------------------
// 3) Testing for unknown data
//------------------------------------------------------------
x1 = 0.01; // <----- 이 값을 0~1사이로 바꾸어서 테스트 해 봅니다.
x2 = 0.05; // <----- 이 값을 0~1사이로 바꾸어서 테스트 해 봅니다.

double Threshold = 0.3; // <----- 이 값을 바꾸어 최종 클래스 판단처리,
// 나중에 출력을 2개 이상으로 하면 가장 큰 값 나오는 노드를 최종 클래스로 판단

output = 1 * W[0] + x1 * W[1] + x2 * W[2];

int output_class = (output > Threshold) ? 1 : 0;

printf("%2.1lf %2.1lf ----- %2.1lf ----- %d \n", x1, x2, output, output_class);
printf("testing test done\n\n");
}

댓글 없음:

댓글 쓰기