C 언어로 선형 회귀 계수 계산하기

CBeginner
지금 연습하기

소개

이 실습에서는 C 프로그래밍을 사용하여 선형 회귀 계수, 기울기 (m) 및 절편 (b) 을 계산하는 방법을 배웁니다. 이 실습은 (x, y) 데이터 포인트를 읽고, 기울기와 절편을 계산하고, y = mx + b 형식으로 선형 회귀 방정식을 출력하는 단계별 과정을 다룹니다. 이 실습은 널리 사용되는 프로그래밍 언어인 C 를 사용하여 통계 데이터 분석 및 모델링에 대한 실질적인 접근 방식을 제공합니다.

(x, y) 데이터 포인트 읽기

이 단계에서는 C 언어로 선형 회귀 분석을 위해 (x, y) 데이터 포인트를 읽는 방법을 배웁니다. 여러 데이터 포인트를 입력받아 나중의 계산을 위해 저장하는 프로그램을 만들 것입니다.

먼저 데이터 포인트 읽기를 구현하기 위한 C 파일을 생성해 봅시다.

cd ~/project
nano linear_regression.c

이제 다음 코드를 파일에 추가합니다.

#include <stdio.h>
#define MAX_POINTS 100

typedef struct {
    double x;
    double y;
} DataPoint;

int main() {
    DataPoint points[MAX_POINTS];
    int num_points = 0;

    printf("Enter x and y coordinates (enter -1 -1 to finish):\n");

    while (num_points < MAX_POINTS) {
        double x, y;
        scanf("%lf %lf", &x, &y);

        if (x == -1 && y == -1) {
            break;
        }

        points[num_points].x = x;
        points[num_points].y = y;
        num_points++;
    }

    printf("\nData Points Entered:\n");
    for (int i = 0; i < num_points; i++) {
        printf("Point %d: (%.2f, %.2f)\n", i+1, points[i].x, points[i].y);
    }

    return 0;
}

프로그램을 컴파일합니다.

gcc -o linear_regression linear_regression.c

프로그램을 실행하고 몇 가지 샘플 데이터 포인트를 입력해 보세요.

./linear_regression

예시 출력:

Enter x and y coordinates (enter -1 -1 to finish):
1 2
2 4
3 5
4 4
5 5
-1 -1

Data Points Entered:
Point 1: (1.00, 2.00)
Point 2: (2.00, 4.00)
Point 3: (3.00, 5.00)
Point 4: (4.00, 4.00)
Point 5: (5.00, 5.00)

이 코드의 주요 구성 요소를 살펴보겠습니다.

  1. x 와 y 좌표를 저장하기 위해 DataPoint 구조체를 정의합니다.
  2. MAX_POINTS는 오버플로를 방지하기 위해 데이터 포인트의 수를 제한합니다.
  3. 프로그램은 좌표를 읽기 위해 while 루프를 사용합니다.
  4. 사용자는 데이터 포인트를 입력하고 -1 -1을 입력하여 입력을 종료할 수 있습니다.
  5. 프로그램은 입력된 모든 데이터 포인트를 확인을 위해 출력합니다.

기울기 (m) 및 절편 (b) 계산

이 단계에서는 최소 제곱법을 사용하여 선형 회귀의 기울기 (m) 와 절편 (b) 을 계산하는 방법을 배웁니다.

먼저 이전의 linear_regression.c 파일을 업데이트합니다.

cd ~/project
nano linear_regression.c

이전 코드를 다음 구현으로 바꿉니다.

#include <stdio.h>
#include <math.h>
#define MAX_POINTS 100

typedef struct {
    double x;
    double y;
} DataPoint;

// 선형 회귀 계수를 계산하는 함수
void computeLinearRegression(DataPoint points[], int num_points, double *m, double *b) {
    double sum_x = 0, sum_y = 0, sum_xy = 0, sum_x_squared = 0;

    for (int i = 0; i < num_points; i++) {
        sum_x += points[i].x;
        sum_y += points[i].y;
        sum_xy += points[i].x * points[i].y;
        sum_x_squared += points[i].x * points[i].x;
    }

    double n = num_points;

    // 기울기 (m) 계산
    *m = (n * sum_xy - sum_x * sum_y) / (n * sum_x_squared - sum_x * sum_x);

    // y 절편 (b) 계산
    *b = (sum_y - (*m) * sum_x) / n;
}

int main() {
    DataPoint points[MAX_POINTS];
    int num_points = 0;

    printf("Enter x and y coordinates (enter -1 -1 to finish):\n");

    while (num_points < MAX_POINTS) {
        double x, y;
        scanf("%lf %lf", &x, &y);

        if (x == -1 && y == -1) {
            break;
        }

        points[num_points].x = x;
        points[num_points].y = y;
        num_points++;
    }

    double slope, intercept;
    computeLinearRegression(points, num_points, &slope, &intercept);

    printf("\n선형 회귀 결과:\n");
    printf("점의 개수: %d\n", num_points);
    printf("기울기 (m): %.4f\n", slope);
    printf("y 절편 (b): %.4f\n", intercept);
    printf("방정식: y = %.4fx + %.4f\n", slope, intercept);

    return 0;
}

수학 라이브러리와 함께 프로그램을 컴파일합니다.

gcc -o linear_regression linear_regression.c -lm

샘플 데이터 포인트로 프로그램을 실행합니다.

./linear_regression

예시 출력:

Enter x and y coordinates (enter -1 -1 to finish):
1 2
2 4
3 5
4 4
5 5
-1 -1

선형 회귀 결과:
점의 개수: 5
기울기 (m): 0.6000
y절편 (b): 2.2000
방정식: y = 0.6000x + 2.2000

선형 회귀 계산에 대한 주요 내용:

  1. 최소 제곱법을 사용하여 기울기와 절편을 계산합니다.
  2. 기울기 공식: m = (n _ Σ(xy) - Σx _ Σy) / (n * Σ(x²) - (Σx)²)
  3. y 절편 공식: b = (Σy - m * Σx) / n
  4. computeLinearRegression() 함수는 이러한 매개변수를 계산합니다.
  5. 메인 함수는 회귀 방정식을 출력합니다.

y = mx + b 출력

이 단계에서는 계산된 기울기와 절편을 사용하여 선형 회귀 방정식을 출력하고 y 값을 예측하는 방법을 배웁니다.

예측 기능을 추가하기 위해 linear_regression.c 파일을 업데이트합니다.

cd ~/project
nano linear_regression.c

이전 코드를 다음 구현으로 바꿉니다.

#include <stdio.h>
#include <math.h>
#define MAX_POINTS 100

typedef struct {
    double x;
    double y;
} DataPoint;

void computeLinearRegression(DataPoint points[], int num_points, double *m, double *b) {
    double sum_x = 0, sum_y = 0, sum_xy = 0, sum_x_squared = 0;

    for (int i = 0; i < num_points; i++) {
        sum_x += points[i].x;
        sum_y += points[i].y;
        sum_xy += points[i].x * points[i].y;
        sum_x_squared += points[i].x * points[i].x;
    }

    double n = num_points;

    *m = (n * sum_xy - sum_x * sum_y) / (n * sum_x_squared - sum_x * sum_x);
    *b = (sum_y - (*m) * sum_x) / n;
}

// y 값을 예측하는 함수
double predictY(double m, double b, double x) {
    return m * x + b;
}

int main() {
    DataPoint points[MAX_POINTS];
    int num_points = 0;

    printf("Enter x and y coordinates (enter -1 -1 to finish):\n");

    while (num_points < MAX_POINTS) {
        double x, y;
        scanf("%lf %lf", &x, &y);

        if (x == -1 && y == -1) {
            break;
        }

        points[num_points].x = x;
        points[num_points].y = y;
        num_points++;
    }

    double slope, intercept;
    computeLinearRegression(points, num_points, &slope, &intercept);

    printf("\n선형 회귀 방정식:\n");
    printf("y = %.4fx + %.4f\n", slope, intercept);

    // 샘플 x 값에 대한 예측 y 값 출력
    printf("\n예측된 y 값들:\n");
    double test_x_values[] = {0, 2.5, 6, 10};
    for (int i = 0; i < 4; i++) {
        double predicted_y = predictY(slope, intercept, test_x_values[i]);
        printf("x = %.2f 일 때, y = %.4f\n", test_x_values[i], predicted_y);
    }

    return 0;
}

프로그램을 컴파일합니다.

gcc -o linear_regression linear_regression.c -lm

샘플 데이터 포인트로 프로그램을 실행합니다.

./linear_regression

예시 출력:

Enter x and y coordinates (enter -1 -1 to finish):
1 2
2 4
3 5
4 4
5 5
-1 -1

선형 회귀 방정식:
y = 0.6000x + 2.2000

예측된 y 값들:
x = 0.00일 때, y = 2.2000
x = 2.50일 때, y = 3.7000
x = 6.00일 때, y = 5.8000
x = 10.00일 때, y = 8.2000

회귀 방정식 출력에 대한 주요 내용:

  1. 주어진 x 에 대한 y 를 계산하는 predictY() 함수를 추가했습니다.
  2. 메인 함수는 전체 방정식 (y = mx + b) 을 출력합니다.
  3. 서로 다른 x 입력에 대한 y 값을 보여주며 예측을 보여줍니다.
  4. 출력은 선형 회귀 모델을 명확하게 시각화합니다.

요약

이 실험에서 C 언어로 선형 회귀 분석을 위한 (x, y) 데이터 포인트를 읽는 방법을 배웠습니다. 여러 데이터 포인트를 입력받아 저장하고, 입력된 데이터 포인트를 확인하기 위해 출력하는 프로그램을 만들었습니다.

다음으로, 선형 회귀 직선의 기울기 (m) 와 절편 (b) 을 계산하고, y = mx + b 형식으로 방정식을 출력하는 방법을 배울 것입니다.