상관계수 놀이 : http://guessthecorrelation.com/
단순선형회귀 : $Y$ = $\beta_0$ + $\beta_1$$X$
다중선형회귀 : $Y$ = $\beta_0$ + $\beta_2$$X1_1$ + ... + $\beta_p$$X_p$
일반화 선형 모형 중 하나이며, 종속 변수가 수치형 자료인 경우 우선적으로 고려하는 모형
보통 다중선형회귀(Multiple Linear Regression)을 칭하며, 종속변수가 하나인 경우는 단순 선형 회귀이다.
예시 : 사업장 매출 예측, 에너지 소비량 예측
https://rstudio-pubs-static.s3.amazonaws.com/190997_40fa09db8e344b19b14a687ea5de914b.html
$R^2$는 총변동(TTS, Total Sum of Squares)에서 설명된 부분
import pandas as pd
from sklearn import datasets, linear_model
import statsmodels.formula.api as sm
from statsmodels.sandbox.regression.predstd import wls_prediction_std
import matplotlib.pyplot as plt
import matplotlib as mpl
import matplotlib.font_manager as fm
import seaborn as sns
from seaborn.linearmodels import corrplot,symmatplot
import numpy as np
import os
import math
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
%matplotlib inline
os.chdir('/Users/jinseokryu/Desktop/ML강의자료/대구대학교/linear_regression/')
172개 자전거 대여 업체의 마케팅 데이터
google_adwords : 구글
AdWords, facebook : 페이스북 광고
twitter : 트위터 광고 등에 대한 비용
marketing_total : 총 마케팅 예산
revenues : 매출
employees : 종업원수
pop_density : 타켓 시장의 인구밀도 수준
marketing = pd.read_csv("./marketing.csv")
marketing = marketing.drop(['employees'],axis=1)
marketing.head()
marketing.describe()
sns.pairplot(marketing)
marketing.corr()
corrplot(marketing)
model = sm.ols(formula = 'revenues ~ marketing_total', data = marketing)
result = model.fit()
# 요약결과 출력
print(result.summary())
x, y = marketing["marketing_total"],marketing["revenues"]
# or via jointplot (with histograms aside):
sns.jointplot(x, y, kind='scatter', joint_kws={'alpha':0.5})
plt.scatter(x,y)
plt.plot(x,result.predict(marketing[["marketing_total"]]),'r')
plt.ylabel('marketing_total')
plt.xlabel('revenues')
model = sm.ols(formula = 'revenues ~ google_adwords', data = marketing)
result = model.fit()
# 요약결과 출력
print(result.summary())
model = sm.ols(formula = 'revenues ~ facebook', data = marketing)
result = model.fit()
# 요약결과 출력
print(result.summary())
model = sm.ols(formula = 'revenues ~ twitter', data = marketing)
result = model.fit()
# 요약결과 출력
print(result.summary())
model1 = sm.ols(formula = 'revenues ~ google_adwords + facebook', data = marketing)
result1 = model1.fit()
# 요약결과 출력
print(result1.summary())
from statsmodels.stats.outliers_influence import variance_inflation_factor
dfX0 = marketing[["google_adwords","facebook"]]
vif = pd.DataFrame()
vif["VIF Factor"] = [variance_inflation_factor(dfX0.values, i) for i in range(dfX0.shape[1])]
vif["features"] = dfX0.columns
vif
model = sm.ols(formula = 'revenues ~ google_adwords + facebook + twitter', data = marketing)
result = model.fit()
# 요약결과 출력
print(result.summary())
from statsmodels.stats.outliers_influence import variance_inflation_factor
dfX0 = marketing[["google_adwords","facebook","twitter"]]
vif = pd.DataFrame()
vif["VIF Factor"] = [variance_inflation_factor(dfX0.values, i) for i in range(dfX0.shape[1])]
vif["features"] = dfX0.columns
vif
train = marketing[:int(len(marketing)*0.7)]
test = marketing[int(len(marketing)*0.7):]
y_fit = result1.predict(test[['google_adwords','facebook']])
x_surf, y_surf = np.meshgrid(np.linspace(marketing.google_adwords.min(), marketing.google_adwords.max(), 100),np.linspace(marketing.facebook.min(), marketing.facebook.max(), 100))
onlyX = pd.DataFrame({'google_adwords': x_surf.ravel(), 'facebook': y_surf.ravel()})
fittedY=result1.predict(exog=onlyX)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(x_surf,y_surf,fittedY.reshape(x_surf.shape), color='r', alpha=0.7)
ax.scatter(train['google_adwords'],train['facebook'],train['revenues'],c='blue', marker='o', alpha=0.5)
ax.scatter(test['google_adwords'],test['facebook'],test['revenues'],c='green', marker='o', alpha=0.5)
ax.set_xlabel('google_adwords')
ax.set_ylabel('facebook')
ax.set_zlabel('revenues')
ax.view_init(azim=50)
sns.pairplot(marketing, hue='pop_density',size=3)
sns.factorplot(kind='box', y='value', x='variable', hue='pop_density',
data=pd.melt(marketing, id_vars=['pop_density'], value_vars=['google_adwords', 'facebook']), size=8, aspect=1.5, legend_out=False)
<데이터 분석 결과 요약 정리>
인구밀도가 높은 곳을 타겟팅하는 자전거 대여 업체에서는 facebook광고를 사용하는 것이 낫고,
인구밀도가 낮은 곳을 타겟팅하는 자전거 대여 업체에서는 google_adwords광고를 사용하는 것이 낫다.
단, facebook광고는 1(1000$) 증가할 때마다 0.19씩 수익이 증가하고, google_adwords광고는 1(1000$) 증가할 때마다 0.04씩 수익이 증가하기 때문에 가성비가 좋은 것은 facebook광고이다.
그러나 google_adwords와 수익간의 상관성이 높기 때문에 google_adwords에 투자하면 수익이 증가할 것이라는 안전성은 확보된다.