회귀분석이란?

독립변수 x에 대응하는 종속변수 y와 가장 비슷한 값 $\hat y$ 를 출력하는 함수 $f(x)$ 를 찾는 과정

회귀분석에서 가장 중요한 개념은 예측값과 잔차(residual)이다. 예측값은 만들어진 모델이 추정하는 값이고, 잔차는 예측값과 관측값의 차이이다.

\hat\beta = {{ { n(\Sigma_i^n{x_i}{y_i}) - (\Sigma_i^n{x_i} (\Sigma_i^n{y_i}) } }\over{ n(\Sigma_i^n{x^2}) - (\Sigma_i^n{x})^2 } }

$$ \hat \alpha = \bar{y} - \hat \beta x$$

$$\hat y = \hat\alpha + \hat\beta x = \bar {y} + \hat\beta(x-\bar {x})$$

Example

lotsize=[10,20,30,40,40,50,60,60,70,80] #로트 크기
peo = [20,29,50,60,70,85,90,95,109,120] #생산 인력
df=pd.DataFrame({'lot':lotsize, 'peo':peo})
df
plt.scatter(data=df , x='lot',y='peo')
plt.show()

이 예에서 로트크기와 같이 영향을 주는 변수를 독립변수(explanatory variable), 설명변수(independent variable)라고 하며, 생산인력과 같이 영향을 받는 변수를 종속변수 (dependent variable) 또는 반응변수(response variable) 라고 한다.

회귀분석은 설명변수의 값으로부터 종속변수의 값을 에측하고자 함이 그 목적으로서, 설명변수와 종속변수의 관계를 구체적인 함수 형태로 나타내고자 하는 것이 분석의 주요 내용이다.

설명변수가 한 개일 때의 회귀분석을 단순 회귀분석 (simple regression)이라 하고, 두 개 이상의 설명변수를 고려하는 회귀분석을 multiple regression이라 한다.

설명변수가 하나이고 설명변수와 종속변수의 관계가 직선관계인 경우 Simple Linear Regression이라 한다.

회귀분석의 첫 단계에서 할 일은 산점도를 그려보고, 독립변수와 종속변수의 관게에 대한 대략적인 파악을 하고, 적절한 모형을 설정하는 것이다.

df['x_square'] = df['lot'].apply(lambda x : x**2)
df['y_square'] = df['peo'].apply(lambda x : x**2)
df['xy']=df[['lot','peo']].apply(lambda x : x['lot'] * x['peo'], axis=1)
df

n=len(df['lot'])
beta_up = n*(df['xy'].sum()) - df['lot'].sum() * df['peo'].sum()
beta_down = n*(df['x_square'].sum()) - (df['lot'].sum())**2
beta = beta_up/beta_down

alpha = df['peo'].mean() - beta*df['lot'].mean()
alpha , beta
#(4.711711711711715, 1.4801801801801802)

def simpleLinearRegression(x,y):

    # input : two list x and y (x and y must have same length)
    # output : alpha, beta ( y = alpha + beta * x )

    meanx=sum(x)/len(x)
    meany=sum(y)/len(y)
    분자=sum(list(map(lambda x : (x[0]-meanx)*(x[1]-meany),zip(x,y))))
    분모=sum(list(map(lambda x : (x-meanx)**2 , x)))
    beta=분자/분모
    alpha=meany - beta*meanx
    print(f"y = {beta} * x + ({alpha})")
    return alpha, beta

simpleLinearRegression(df['lot'],df['peo'])

y = 1.4801801801801804 * x + (4.7117117117117004)
(4.7117117117117004, 1.4801801801801804)
'''

sklearn.linear_model.LinearRegression사용

공식문서

from sklearn.linear_model import LinearRegression
model = LinearRegression()
feature = ['YearBuilt','GarageArea','GrLivArea','OverallQual','FullBath']
target = ['SalePrice']

def new(dfraw,feature,target):
    model = LinearRegression()
    X_train = dfraw[[feature]]
    y_train = dfraw[target]
    model.fit(X_train, y_train)
    print(f'{feature}\t&\t{target[0]} \ty(SalesPrice) = {round(model.coef_[0][0],3)} * {feature} + {round(model.intercept_[0],3)}')
    return model, model.coef_ , model.intercept_

+ Recent posts