지난달 2주, 요번달, 다음달은 다음 학기 강의과목중 하나인 "다변량통계분석" 강의자료를 만드는 중인데, 이 그림들도 멋지죠?
공분산을 공부하는데 많은 도움이 될거예요. 코드도 드리니, 매트릭스 숫자만 바꿔보면 쉽게 이미지를 바꿀 수 있어요.
# ============================================
# 예제 2: 양의 상관관계
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import multivariate_normal
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
plt.rcParams['font.family'] ='Malgun Gothic'
plt.rcParams['axes.unicode_minus'] =False
# 그림 설정
fig = plt.figure(figsize=(15, 10))
# 3D 플롯
ax1 = fig.add_subplot(3, 3, 1, projection='3d')
x = np.linspace(-4, 4, 100)
y = np.linspace(-4, 4, 100)
X, Y = np.meshgrid(x, y)
pos = np.dstack((X, Y))
print("=" * 50)
print("예제 2: 양의 상관관계")
print("=" * 50)
mu2 = np.array([0, 0])
sigma2 = np.array([[1, 0.5], [0.5, 1]])
print(f"평균 μ = {mu2}")
print(f"공분산 Σ =\n{sigma2}\n")
ax4 = fig.add_subplot(3, 3, 3, projection='3d')
rv2 = multivariate_normal(mu2, sigma2)
Z2 = rv2.pdf(pos)
ax4.plot_surface(X, Y, Z2, cmap='plasma', alpha=0.8)
ax4.set_xlabel('x₁')
ax4.set_ylabel('x₂')
ax4.set_zlabel('확률밀도')
ax4.set_title('3D: 양의 상관관계')
ax5 = fig.add_subplot(3, 3, 2)
contour2 = ax5.contourf(X, Y, Z2, levels=20, cmap='plasma')
ax5.contour(X, Y, Z2, levels=10, colors='black', alpha=0.3, linewidths=0.5)
ax5.plot(mu2[0], mu2[1], 'r*', markersize=15)
ax5.set_xlabel('x₁')
ax5.set_ylabel('x₂')
ax5.set_title('등고선: 양의 상관관계')
plt.colorbar(contour2, ax=ax5)
samples2 = rv2.rvs(size=1000)
ax6 = fig.add_subplot(3, 3, 1)
ax6.scatter(samples2[:, 0], samples2[:, 1], alpha=0.5, s=10)
ax6.plot(mu2[0], mu2[1], 'r*', markersize=15)
ax6.set_xlabel('x₁')
ax6.set_ylabel('x₂')
ax6.set_title('샘플: 양의 상관관계')
ax6.set_xlim(-4, 4)
ax6.set_ylim(-4, 4)
plt.tight_layout()
plt.savefig('multivariate_gaussian.png', dpi=300, bbox_inches='tight')
plt.show()