회귀분석
참조 : https://daryan.tistory.com/23 sin() 함수를 그려보고, sin()함수에 난수를 더해 임의의 표본 생성
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
%matplotlib inline #문서내에 그래프 출력 import numpy as np import pylab as pl def f(size): x = np.linspace(0, 4.5, size) y = 2 * np.sin(x * 1.5) return (x,y) def sample(size): x = np.linspace(0, 4.5, size) y = 2 * np.sin(x * 1.5) + pl.randn(x.size) return (x,y) pl.clf() f_x, f_y = f(50) pl.plot(f_x, f_y) x, y = sample(50) pl.plot(x, y, 'k.') |
sklearn 모듈을 활용하여 선형회귀 : degree가 1이면 선형, 이상이면 n차 곡선이 그려짐
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
from sklearn.linear_model import LinearRegression def fit_polynomial(x, y, degree): #x, y 분포에 적합한 다향식 추출 model = LinearRegression() model.fit(np.vander(x, degree + 1), y) return model def apply_polynomial(model, x): #추출된 다항식에 x를 넣어 예측값 y를 구함 degree = model.coef_.size - 1 y = model.predict(np.vander(x, degree + 1)) return y model = fit_polynomial(x, y, 4) p_y = apply_polynomial(model, x) pl.plot(x, y, 'k.') pl.plot(x, p_y,'g') |
degree = 1 degree = 2 degree = 3 degree = 4 numpy.vander() 함수 사용 예
1 2 3 4 5 |
#np.vander()함수 : x = np.array([4,2,7]) print(np.vander(x, 4)) print(np.vander(x, 6)) |