[SciPy] 1. Linear Regression (Application to Scatter Plot)

in #kr-python6 years ago

안녕하세요!
오랜만에, 정말 정말 오랜만에,

[Matplotlib, Numpy, and Scipy]

주제로 돌아왔습니다.

이번 소주제는 Linear Regression 선형 회귀(線型 回歸)입니다.


먼저 아래 Scatter Plot 산점도를 보시겠습니다.

이 그림에 대한 자세한 설명은 생략합니다!
다만 X축, Y축, 그리고 Color 이렇게 세가지 변수로
각각의 데이타, 즉 한 점이 정의되었음을 알려드립니다.

위 그림의 X축과 Y축 변수를 가지고 Linear Regression 선형 회귀를 해보겠습니다.

Python에서 Linear Regression 선형 회귀를 구현하는 방법에는 몇 가지가 있을텐데,
저는 "scikit-learn (a.k.a sklearn)" 즉, Python Machine Learning 패키지에 들어있는
가장 간단한 "linear_model"을 이용할 예정입니다.

간략화된 코드는 다음과 같습니다.

from sklearn import linear_model

### linear_model 안의 LinearRegression 함수를 불러옵니다. 
regr=linear_model.LinearRegression()   

### Regression 함수를 계산합니다. 
regr.fit(xdata.reshape([-1,1]), ydata.reshape([-1,1]))   

### R^2 값을 계산합니다. 
r2score=regr.score(xdata,ydata)   

### 기울기, 절편, 그리고 R^2 값을 화면에 출력합니다. 
print(regr.coef_, regr.intercept_,r2score)   

### 선을 긋기 위한 임시의 x 값을 준비합니다.
xtmp=np.linspace(xdata.min(),xdata.max(),(xdata.max()-xdata.min())*100)    

### 계산한 기울기와 절편 값을 이용하여 Y 값을 예측합니다. 
y_pred=regr.predict(xtmp)   

### 그림에 선을 추가합니다. 
ax.plot(xtmp,y_pred,color='0.1',linestyle='--',linewidth=1.5)   

### 그림에 계수와 R^2 값을 추가합니다. 
anntxt=r'$R^2={:.3f}$'.format(r2score)
anntxt2='coef.={:.3f}'.format(coef[0][0])
ax.annotate(anntxt,xy=(0.03,0.64),xycoords='axes fraction',ha='left',fontsize=12,stretch='semi-condensed')
ax.annotate(anntxt2,xy=(0.03,0.76),xycoords='axes fraction',ha='left',fontsize=12,stretch='semi-condensed')

### 초기화 시킵니다. (다음에 재사용을 위해)
regr.__init__()  



그래서 위의 코드를 추가한 결과 위의 Scatter Plot은 다음과 같이 바뀌었습니다.


부연설명 1
혹시 자료에 Missing Value 혹은 Undef 값이 있을 경우,
Regression 하기 전에 확실히 제거해주는 게 좋습니다.
Numpy에서는 다음과 같이 "조건부 인덱싱"을 이용하면 쉽게 제거할 수 있습니다.

idx=np.logical_and(xdata>=0., ydata>=0)
xdatatmp=xdata[idx]
ydatatmp=ydata[idx]

부연설명2
위의 예제에서 X값과 Y값은 1-D Array입니다.
그런데, LinearRegression() 함수는 기본적으로 2-D Array를 받아들입니다.
그래서 위의 예제에서 xdata와 ydata의 모양을 바꾸었습니다.

regr.fit(xdata.reshape([-1,1]), ydata.reshape([-1,1]))   

reshape() 함수에서 "-1"은 보통 "나머지"의 뜻입니다. 즉, 위의 경우 두번째 축으로 1을 배정하고 첫번째 축에 "나머지" 다 배정한다는 뜻입니다.

원래 예정대로라면 Matplotlib 항목에서 Bar plot과 Scatter plot 등을 이어나가야 하는데 그동안 게을렀습니다. 하긴 해야죠. (언젠가는!)

Matplotlib List

[Matplotlib] 00. Intro + 01. Page Setup
[Matplotlib] 02. Axes Setup: Subplots
[Matplotlib] 03. Axes Setup: Text, Label, and Annotation
[Matplotlib] 04. Axes Setup: Ticks and Tick Labels
[Matplotlib] 05. Plot Accessories: Grid and Supporting Lines
[Matplotlib] 06. Plot Accessories: Legend
[Matplotlib] 07. Plot Main: Plot
[Matplotlib] 08. Plot Main: Imshow
[Matplotlib] 09. Plot Accessary: Color Map (part1)
[Matplotlib] 10. Plot Accessary: Color Map (part2) + Color Bar

F2PY List

[F2PY] 01. Basic Example: Simple Gaussian 2D Filter
[F2PY] 02. Basic Example: Moving Average
[F2PY] 03. Advanced Example: Using OpenMP

Scipy List

[SciPy] 1. Linear Regression (Application to Scatter Plot)

Sort:  

Andrew Ng 선생님의 Coursera Machine Learning Class가 생각나네요 ^^

누군지 찾아봤습니다. 스탠포드 겸임교수면서 중국 바이두의 과학부장이라니 대단한 사람이군요.
(그런데 위의 선형 회귀는 사실 머신러닝이라 부르기도 아까운 기본적인 내용이라.. ㅎㅎ)

첫수업인가 나와요 ^^ 그 이후로 수업을 안들어서 ㅎㅎ

정석 펴서 집합만 보고 덮었다는 느낌이군요? ^^

앞장만 새까맣게 ㅎㅎ

zorba님이 dj-on-steem님을 멘션하셨습니당. 아래 링크를 누르시면 연결되용~ ^^
zorba님의 [2018/8/22] 가장 빠른 해외 소식! 해외 스티미언 소모임 회원들의 글을 소개해드립니다.

...enerva 뉴욕 dj-on-steem/td> DC 근교 hello-sunshine DC

Coin Marketplace

STEEM 0.16
TRX 0.15
JST 0.028
BTC 53921.46
ETH 2250.39
USDT 1.00
SBD 2.30