# plotly를 사용해서 상대적으로 간단히 그래프를 그릴 수도 있습니다.
import numpy as np
import plotly.express as px
import plotly.graph_objs as go
import itertools
def surface_3d(df, f1, f2, target, length=20, **kwargs):
"""
2특성 1타겟 선형모델평면을 시각화 합니다.
df : 데이터프레임
f1 : 특성 1 열 이름
f2 : 특성 2 열 이름
target : 타겟 열 이름
length : 각 특성의 관측치 갯수
"""
# scatter plot(https://plotly.com/python-api-reference/generated/plotly.express.scatter_3d)
plot = px.scatter_3d(df, x=f1, y=f2, z=target, opacity=0.5, **kwargs)
# 다중선형회귀방정식 학습
model = LinearRegression()
model.fit(df[[f1, f2]], df[target])
# 좌표축 설정
x_axis = np.linspace(df[f1].min(), df[f1].max(), length)
y_axis = np.linspace(df[f2].min(), df[f2].max(), length)
coords = list(itertools.product(x_axis, y_axis))
# 예측
pred = model.predict(coords)
z_axis = pred.reshape(length, length).T
# plot 예측평면
plot.add_trace(go.Surface(x=x_axis, y=y_axis, z=z_axis, colorscale='Viridis'))
return plot
이후
surface_3d(
train,
f1='GrLivArea',
f2='OverallQual',
target='SalePrice',
title='House Prices'
)
import matplotlib.pyplot as plt
style.use('seaborn-talk')
fig = plt.figure()
# for 3d plot
ax = fig.gca(projection='3d')
ax.scatter(train['GrLivArea'], train['OverallQual'], train['SalePrice'])
ax.set_xlabel('GrLivArea', labelpad=12)
ax.set_ylabel('OverallQual', labelpad=10)
ax.set_zlabel('SalePrice', labelpad=20)
plt.suptitle('Housing Prices', fontsize=15)
plt.show()