/ PROGRAMING, PYTHON

선형회귀

선형회귀

기본적으로 ChatGPT를 이용하여 틀을 잡고 만든 것

선형회귀 1

주어진 데이터에 대해 선형 회귀 모델을 구현하고, 새로운 입력값에 대해 예측을 수행하는 함수를 작성하시오.

import numpy as np

class LinearRegression:
    def __init__(self):
        self.coefficients = None

    def fit(self, X, y):
        # Add a column of 1s to the input X
        X = np.c_[np.ones(X.shape[0]), X]

        # Calculate the coefficients using the normal equation
        self.coefficients = np.linalg.inv(X.T @ X) @ X.T @ y

    def predict(self, X):
        # Add a column of 1s to the input X
        X = np.c_[np.ones(X.shape[0]), X]

        # Calculate the predicted values using the learned coefficients
        y_pred = X @ self.coefficients

        return y_pred
    

# 테스트 데이터 생성
x = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
y = np.array([1, 3, 2, 5, 7, 8, 8, 9, 10, 12])

lr = LinearRegression()
lr.fit(x,y)

# 새로운 값 예측
x_new = np.array([[10], [11], [12]])
y_new = lr.predict(x_new)

print(y_new)

[12.93333333 14.1030303  15.27272727]

선형회귀 2

주어진 데이터에 대해 sklearn 선형회귀 모델을 사용하여 새로운 입력값에 대해 예측을 수행하는 함수를 작성하시오.

import numpy as np
from sklearn.linear_model import LinearRegression

# 테스트 데이터 생성
x = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
y = np.array([1, 3, 2, 5, 7, 8, 8, 9, 10, 12])

# 선형 회귀 모델 학습
model = LinearRegression()
model.fit(x.reshape(-1, 1), y)

# 새로운 값 예측
x_new = np.array([[10], [11], [12]])
y_new = model.predict(x_new)

print(y_new)
[12.93333333 14.1030303  15.27272727]