| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | 4 | 5 | 6 | |
| 7 | 8 | 9 | 10 | 11 | 12 | 13 |
| 14 | 15 | 16 | 17 | 18 | 19 | 20 |
| 21 | 22 | 23 | 24 | 25 | 26 | 27 |
| 28 | 29 | 30 | 31 |
- Unreal Engine
- 게임개발
- 유니티
- Aegis
- 보안
- os
- local prediction
- gameplay tag
- rpc
- widget
- attribute
- UI
- listen server
- 게임 개발
- stride
- ability task
- CTF
- MAC
- animation
- 언리얼 엔진
- 언리얼엔진
- gameplay effect
- photon fusion2
- Multiplay
- unity
- linear regression
- gameplay ability system
- C++
- gas
- Replication
- Today
- Total
Replicated
Regression 본문
1. Simple Linear Regression
- 종속 변수와 독립 변수 사이의 선형 관계를 파악하고 이를 예측에 활용하는 기법
- X와 y 사이의 관계식: 모델
- y = WX + b -> W와 b를 찾는 것이 학습 목표
- 두 변수가 선형 관계에 있는지 알아보는 방법: 산점도, 상관계수
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, r2_score
from sklearn.model_selection import train_test_split
필요 모듈들
cars = pd.read_csv('/content/gdrive/MyDrive/Data/cars.csv')
print(cars)
speed = cars['speed'].to_frame()
dist = cars['dist']

to_frame() : 1차원 데이터 시리즈를 2차원 데이터 데이터프레임으로 변경
train_X, test_X, train_y, test_y = \
train_test_split(speed, dist, test_size=0.2, random_state=123)
트레인, 테스트 분리
random_state=123
-> train, test 나눌 때 임의로 나누기에 실행 시마다 결과가 달라지는데 이거 고정하는거
model = LinearRegression()
model.fit(train_X, train_y)
pred_y = model.predict(test_X)
print(pred_y)

모델 학습시키고 예측

이런 식으로 독립변수 넣어주면 됨
print('Coefficients: {0:.2f}, Intercept {1:.3f}'\
.format(model.coef_[0], model.intercept_))

계수(W)랑 절편(b)
dist = 3.96 x speed - 18.323
print('Mean squared error: {0:.2f}'.format(mean_squared_error(test_y, pred_y)))
print('Coefficient of determination: %.2f'% r2_score(test_y, pred_y))
MSE랑 Coefficient of determination(R2 Score)으로 모델 평가
MSE는 작을 수록 정확한 모델
R2 Score는 1에 가까울수록 좋은 모델 (최대 1, 예측 결과와 실제값이 완전히 일치할 때)

plt.scatter(test_X, test_y, color='black') #실제값
plt.plot(test_X, pred_y, color='blue', linewidth=3) #예측값
plt.xlabel('speed')
plt.ylabel('dist')
plt.show()

시각화
Multiple Liniear Regression
- 독립 변수가 2개 이상인 경우
- 중선형 회귀식의 형태
- y = b0 + b1x1 + b2x2 ... bkxk + ε
예시: 연봉 예측 모델
import pandas as ps
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, r2_score
from sklearn.model_selection import train_test_split
df = ps.read_csv('/content/gdrive/MyDrive/Data/prestige.csv')
print(df)
df_X = df[['education','women','prestige']]
df_y = df['income']

train_X, test_X, train_y, test_y = train_test_split(df_X, df_y, test_size=0.2, random_state=123)
model = LinearRegression()
model.fit(train_X, train_y)
pred_y = model.predict(test_X)
print(pred_y)

입력이 여러개 들어가는데 사용법은 거의 비슷
print('Coefficients: {0:.2f},{1:.2f},{2:.2f} Intercept {3:.3f}'\
.format(model.coef_[0], model.coef_[1], model.coef_[2], model.intercept_))
print('Mean squared error: {0:.2f}'.format(mean_squared_error(test_y, pred_y)))
print('Coefficient of determination: %.2f'% r2_score(test_y, pred_y))

계수와 절편, MSE, R2 Score
my_test_x = np.array([11.44,8.13,54.1]).reshape(1,-1)
my_pred_y = model.predict(my_test_x)
print(my_pred_y)

직접 값 넣으려면 reshape으로 1행 짜리로 만들어서 넣어야 함
sklearn이 그냥 (샘플 수, 특성수) 2차원 배열로 입력을 받기 때문
Logistic Regression
일반적인 회귀문제에서 종속 변수는 수치 데이터
그런데 범주형 데이터도 있음
-> 로지스틱 회귀로 분류 문제를 회귀 방법으로 해결 가능
Iris 품종 예측
from sklearn import datasets
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
iris_X, iris_y = datasets.load_iris(return_X_y=True)
print(iris_X.shape) # (150, 4)
train_X, test_X, train_y, test_y = train_test_split(iris_X, iris_y, test_size=0.3, random_state=1234)

150개 인스턴스, 4개 피쳐
model = LogisticRegression()
model.fit(train_X, train_y)
pred_y = model.predict(test_X)
print(pred_y)
acc = accuracy_score(test_y, pred_y)
print('Accuracy : {0:3f}'.format(acc))

* Accuracy: 전체 중 정답을 맞춘 인스턴스 비율
참고 사항, 로지스틱 회귀도 종속 변수는 숫자여야 함
문자형으로 되어 있는 범주 데이터는 숫자로 변환한 후 작업 필요 (근데 sklearn은 안해도 됨)
from sklearn.preprocessing import LabelEncoder
import numpy as np
number = LabelEncoder()
label_str = np.array(['M','F','M','F','M'])
label_num = number.fit_transform(label_str).astype('int')
print(label_str)
print(label_num)

일단 이런식으로 가능
회귀 문제 해결에 있어 regression 위에서 쓰인 학습 알고리즘은 성능은 별로
근데 단순하고 이해하기 쉬워서 많이 씀
예측 정확도가 높은 모델을 원하면..
- SVR (support vector regressor)
- RandomForestRegressor
- XGboost regressor
'학부 > 딥러닝' 카테고리의 다른 글
| 인공신경망 개요 (0) | 2025.10.18 |
|---|---|
| Feature Selection, Model Stacking (0) | 2025.10.18 |
| Classification / 결정 트리, SVM, XGBoost (0) | 2025.10.13 |
| Classification / 앙상블, 하이퍼 파라미터 튜닝, K-fold CV, 성능 평가 (0) | 2025.10.13 |
| 머신 러닝 개념 (0) | 2025.10.12 |