k-최근접 이웃 회귀 (K-Nearest Neighbors Regression, K-NN 회귀)에서 k 값에 따라 과대적합 (overfitting)과 과소적합 (underfitting)이 발생하기도 한다. 과대적합은 학습 데이터에 너무 민감하게 반응하여, 새로운 데이터에 일반화하지 못하는 현상을 의미하며, 예측할 때 가장 가까운 단 1개의 이웃만을 참고하기 때문에 훈련 데이터에는 정확하지만 테스트 데이터나 새로운 데이터에서는 성능이 낮아진다. 한편, 과소적합은 모델이 너무 단순해서 학습 데이터의 패턴조차 잘 설명하지 못하는 현상을 말하는 것으로, k 값이 너무 커서 많은 이웃의 평균을 사용하기 때문에 국지적인 패턴을 놓치게 된다. 2주차에서는 k-최근접 이웃 회귀 모델에서 과대적합과 과소적합 현상을 직접 코드를 통하여 구현해보고 현상을 관찰해보았다.

 

예시 코드 (실행 코드 일부)

 

적절한 모델인 경우 (k = 5)

k 값이 적절하게 설정된 경우, 아래와 같이 훈련 데이터의 분포를 적절하게 표현하고 있음을 확인할 수 있다.

 

 

과대적합인 경우 (k = 1)

k 값이 1이거나 작은 경우에는 아래처럼 훈련 데이터를 매우 충실히 잘 따라감을 확인할 수 있다.
하지만 이상치에 대해서도 과하게 반응하는 것을 확인할 수 있어, 이런 경우에는 k 값을 적절히 높여줄 필요가 있다.

 

 

과대적합인 경우 (k = 10)

k 값이 지나치게 높아지면 그래프가 평탄화하거나 급격하게 단순화되며, 국지적 패턴을 무시하는 경향을 확인할 수 있었다.
이런 경우, 예측이 평균값에 가까워지고 정확도가 저하되기에 이런 경우에는 k 값을 낮출 필요가 있다.

 

 

구글 계정이 있다면 누구나 무료로 사용할 수 있는 코랩 (Colab)

우선 구글 계정을 로그인 한 후, 코랩 홈페이지 (https://colab.research.google.com) 에 접속하면 이용할 수 있었다.
로그인하지 않아도 코랩은 들어갈 수 있으나, 로그인하지 않으면 실습이 불가능하기에 구글 계정을 통한 로그인은 필수적이다.

구글 코랩을 몇 차례 이용한 적이 있는데다가 주피터 노트북 (Jupyter Notebook)은 평소에 사용하고 있기에 인터페이스는 익숙했다.
이번 주는 혼공학습단 14기의 1주차 학습 과정을 진행했으며, 1~2단원까지 공부한 내용을 정리해보았다.

 

생산 분류 문제

도미 데이터 준비하기

 

빙어 데이터 준비하기

 

K-최근접 이웃 알고리즘 (K-Nearest Neighbors Algorithm)

어떤 데이터가 주어질 때, 그 주변에 있는 k개의 가장 가까운 이웃들을 살펴보고, 다수에 의해 데이터의 레이블 (label) 또는 값을 결정한다.

In this class, I learned about one-dimensional array for containing the values.

Unlike general variables, one-dimensional arrangement can be accessed through an index to each space.
For example, if you declare five variables, each variable must be defined with a specific value.
However, if you declare a 1D array with five spaces only once, each value can be accessed through an index.

/* General Variables */
int A1 = 10;
int A2 = 20;
int A3 = 30;
int A4 = 40;
int A5 = 50;

/* One-dimensional Array */
int A[5] = {10, 20, 30, 40, 50};

 

In case of charater array, string values can be seperated by each letter with indexing.

/* General Variables */
char Char1 = 'H';
char Char2 = 'E';
char Char3 = 'L';
char Char4 = 'L';
char Char5 = 'O';

printf("%c \n", Char1);
printf("%c \n", Char2);
printf("%c \n", Char3);
printf("%c \n", Char4);
printf("%c \n", Char5);


/* One-dimensional Array */
char Str[6] = "HELLO";

printf("%s \n", Str);
printf("%c \n", Str[0]);
printf("%c \n", Str[1]);
printf("%c \n", Str[2]);
printf("%c \n", Str[3]);
printf("%c \n", Str[4]);

 

 

Today's lecture covered how to make a code for 'Number Baseball Game' in C Programming.
Here's the rules of 'Number Baseball Game' as below.

1. Generate 3 digits randomly
2. Enter 3 digits to get the right answer.
3. If the digit position and value of the entered number are the same, it is considered a strike.
4. The digit position of the entered number is different, but if the value is the same, it is considered a ball.
5. Out if the number you enter does not have the same number as the number you created.
6. If you get the right answer before 3 outs, you win. If you get 3 outs, you lose.

 

And I practice to write a code for implementing the 'Number Baseball Game' as below.

#include <stdio.h>
#include <stdlib.h>

/* run this program using the console pauser or add your own getch, system("pause") or input loop */

int main(int argc, char *argv[]) {
    
    /* Initialize the variable for putting the values */
    int Q_num1, Q_num2, Q_num3;
    int A_num1, A_num2, A_num3;
    int input;
    int strike = 0, ball = 0, out = 0;
    
    /* Initialize the randum seed function */
    srand((unsigned)time(NULL));
    
    /* Check the first number */
    Q_num1 = rand() % 10;
    
    /* Check the second number */
    Q_num2 = rand() % 10;
    
    while (Q_num2 == Q_num1) {
    	Q_num2 = rand() % 10;
    }
    
    /* Check the third number */
    Q_num3 = rand() % 10;
    while ((Q_num3 == Q_num1) || (Q_num3 == Q_num2)) {
    	Q_num3 = rand() % 10;
    }
    
    while(1) {
    	/* Input the number */
        printf("Please input the number \n");
        scanf("%d", &input);
        
        A_num1 = input/100;
        A_num2 = (input%100)/10;
        A_num3 = input%10;
        
        /* Checking the first number whether strike or ball */
        if (A_num1 == Q_num1) strike++;
        else if (A_num1 == Q_num2) ball++;
        else if (A_num1 == Q_num3) ball++;
        
        /* Checking the second number whether strike or ball */
        if (A_num2 == Q_num1) ball++;
        else if (A_num2 == Q_num2) strike++;
        else if (A_num2 == Q_num3) ball++;
        
        /* Checking the third number whether strike or ball */
        if (A_num3 == Q_num1) strike++;
        else if (A_num3 == Q_num2) ball++;
        else if (A_num3 == Q_num3) strike++;
        
        /* Counting when the strike and ball are zero */
        if ((strike == 0) && (ball == 0)) out ++;
        
        printf("%d strike, %d ball, %d out \n", strike, ball, out);
        
        /* If input number make 3 strike, the player won the game */
        if (strike == 3) {
        	printf("Player win \n");
            printf("Anwer is %d%d%d, Q_num1, Q_num2, Q_num3);
            break;
        }
        
        /* If input number make 3 out, the player fail the game */
        if (out == 3) {
        	printf("Player fail \n");
            printf("Answer is %d%d%d, Q_num1, Q_num2, Q_num3);
            break;
        }
        
        /* Initialize the count */
        strike = 0;
        ball = 0;
    }
    
    return 0;
}

I learned the 'for' and 'while' repeated statement which is used to repeatedly command a particularly actions.

1. 'For' statement
This iteration operates the action code while satisfying the conditional expression from the initial condition of the variable.

#include <stdio.h>
#include <stdlib.h>

/* run this program using the console pauser or add your own getch, system("pause") or input loop */

int main(int argc, char *argv[]) {
    
    int i;
    
    for (initial variable; repeated condtion, incremental conditon) {
    	Action code;
    }
    
    return 0;
}

 

2. 'While' statement
This iteration is repeated if the content of the conditional expression is true.

#include <stdio.h>
#include <stdlib.h>

/* run this program using the console pauser or add your own getch, system("pause") or input loop */

int main(int argc, char *argv[]) {
    
    int i;
    
    while (conditon) {
    	Action code;
    }
    
    return 0;
}

 

+ Recent posts