기본 콘텐츠로 건너뛰기

[matplotlib] 등고선(Contour)

[data analysis]가상 데이터 만들기

가상데이터 만들기

내용

make_classification

sklearn.datasets.make_classification() 함수는 분류용 가상 데이터를 생성합니다.

  • 인수
    • n_samples : 표본 데이터의 수, 디폴트 100
    • n_features : 독립 변수의 수, 디폴트 20
    • n_informative : 독립 변수 중 종속 변수와 상관 관계가 있는 성분의 수, 디폴트 2
    • n_redundant : 독립 변수 중 다른 독립 변수의 선형 조합으로 나타나는 성분의 수, 디폴트 2
    • n_repeated : 독립 변수 중 단순 중복된 성분의 수, 디폴트 0
    • n_classes : 종속 변수의 클래스 수, 디폴트 2
    • n_clusters_per_class : 클래스 당 클러스터의 수, 디폴트 2
    • weights : 각 클래스에 할당된 표본 수
    • random_state : 난수 발생 시드
  • 반환값
    • X : [n_samples, n_features] 크기의 배열, 독립 변수
    • y : [n_samples] 크기의 배열, 종속 변수

위 함수에서 인수의 관계는 다음을 만족하여야 합니다.

(n_classes) × (n_clusters_per_class) ≤ 2(n_informative)
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
font1={'size':11, 'weight':'bold'}
font2={'family':'nanumgothic', 'size':11, 'weight':'bold'}
from sklearn.datasets import make_classification
X,y=make_classification(n_features=1, n_informative=1, n_redundant=0, n_clusters_per_class=1, random_state=2)
plt.scatter(X, y, marker='o', c=y, s=100, edgecolor='k', linewidth=2)
plt.show()
plt.hist(X[y==0], bins=10, density=True, alpha=0.6, histtype='stepfilled', label="y=0",color="blue")
plt.hist(X[y==1], bins=10, density=True, alpha=0.6, histtype='stepfilled', label="y=1",color="red")
plt.legend()
plt.show()

위 코드는 독립변수 1개에 2개의 클래스를 가지는 데이터입니다. 특성은 라벨과 상관성이 있는 변수입니다. 다음 코드는 특성 2개이지만 라벨과 상관성 있는 특성은 1개입니다. 이 경우 특성 1은 라벨과 상관성은 작습니다.

X1,y1=make_classification(n_features=2, n_informative=1, n_redundant=0, n_clusters_per_class=1, random_state=1)
plt.scatter(X1[:,0], X1[:,1], marker='o', c=y1, s=100, edgecolor='k', linewidth=2)
plt.show()
plt.figure(figsize=(10, 5))
plt.subplot(1,2,1)
plt.hist(X1[:,0][y1==0], bins=10, density=True, histtype="stepfilled", label="y=0",alpha=0.6,color="blue")
plt.hist(X1[:,0][y1==1], bins=10, density=True, histtype="stepfilled", label="y=1",alpha=0.6,color="red")
plt.legend()
plt.xlabel("$\mathbf{x_1}$")
plt.subplot(1,2,2)
plt.hist(X1[:,1][y1==0], bins=10, density=True, histtype="stepfilled", label="y=0",alpha=0.6,color="blue")
plt.hist(X1[:,1][y1==1], bins=10, density=True, histtype="stepfilled", label="y=1",alpha=0.6,color="red")
plt.legend()
plt.xlabel("$\mathbf{x_2}$")
plt.show()

다음은 특성 2개 모두 라벨과 상관성이 있도록 설정한 것입니다.. 그러나 결과는 특성 한개만이 라벨과 상관성을 보입니다. n_features를 n_informative 보다 크게 한다면 라벨과의 상관성있는 변수의 수를 지정한 대로 얻을 수 있습니다.

X2, y2 = make_classification(n_samples=500, n_features=2, n_informative=2, n_redundant=0, n_clusters_per_class=1, random_state=3)
plt.scatter(X2[:,0], X2[:,1], marker='o', c=y2, s=100, edgecolor='k', linewidth=1)
plt.show()
plt.figure(figsize=(10,5))
plt.subplot(1,2,1)
sns.histplot(X2[y2==0,0], label="y=0",alpha=0.6,color="blue")
sns.histplot(X2[y2==1,0], label="y=1",alpha=0.6,color="red")
plt.legend()
plt.xlabel("$\mathbf{x_1}$")
plt.subplot(1,2,2)
sns.histplot(X2[y2==0,1], label="y=0",alpha=0.6,color="blue")
sns.histplot(X2[y2==1,1], label="y=1",alpha=0.6,color="red")
plt.legend()
plt.xlabel("$\mathbf{x_2}$")
plt.show()
X3, y3 = make_classification(n_samples=500, n_features=3, n_informative=2, n_redundant=0, n_clusters_per_class=2, random_state=5)
plt.scatter(X3[:,0], X3[:,1], marker='o', c=y3, s=100, edgecolor='k', linewidth=1)
plt.show()
plt.figure(figsize=(6, 12))
for i in range(3):
    plt.subplot(3,1,i+1)
    sns.histplot(X3[y3==0,i], label="y=0",alpha=0.6,color="blue")
    sns.histplot(X3[y3==1,i], label="y=1",alpha=0.6,color="red")
    plt.legend()
    plt.xlabel(f"X{i+1}")
plt.show()

함수의 인수 weights는 각 클래스에 할당되는 sample의 수입니다. 이 인자를 사용하여 비대칭 가상 데이터를 생성할 수 있습니다.

X4, y4=make_classification(n_features=2, n_informative=2, n_redundant=0, n_clusters_per_class=1, weights=[0.9, 0.1], random_state=6)
np.unique(y4, return_counts=True)
(array([0, 1]), array([90, 10]))
plt.scatter(X4[:,0], X4[:,1], s=100, c=y4, marker='o', edgecolor="k")
plt.xlabel(r"$\mathbf{x_1}$", size=15)
plt.ylabel(r"$\mathbf{x_2}$", size=15)
plt.show()

다중 클래스 생성

X5, y5=make_classification(n_features=2, n_informative=2, n_redundant=0, n_clusters_per_class=1, n_classes=4, random_state=7)
plt.scatter(X5[:,0], X5[:,1], s=100, c=y5, marker='o', edgecolor="k")
plt.xlabel(r"$\mathbf{x_1}$", size=15)
plt.ylabel(r"$\mathbf{x_2}$", size=15)
plt.show()

make_blobs

make_blobs() 함수는 사우시안 정규분포를 사용하여 군집된 데이터(clustered data)를 생성합니다. 군집 데이터의 모든 방향은 같은 특성을 가지므로 등방성이 유지됩니다. 그러므로 make_classifiction 분류를 위한 데이터 생성인 점은 같지만 make_blobs()에 의해 생성된 데이터들은 원형의 형태로 밀집된 형태를 보입니다.

  • 인수
    • n_samples : 표본 데이터의 수, 디폴트 100
    • n_features : 독립 변수의 수, 디폴트 20
    • centers : 생성할 클러스터의 수 혹은 중심, [n_centers, n_features] 크기의 배열. 디폴트 3
    • cluster_std: 클러스터의 표준 편차, 디폴트 1.0
    • center_box: 생성할 클러스터의 바운딩 박스(bounding box), 디폴트 (-10.0, 10.0))
  • 반환값
    • X : [n_samples, n_features] 크기의 배열, 독립 변수
    • y : [n_samples] 크기의 배열, 종속 변수
from sklearn.datasets import make_blobs
X6, y6=make_blobs(n_samples=500, n_features=2, centers=3, random_state=8)
plt.scatter(X6[:,0], X6[:,1], s=100, c=y6, marker='o', edgecolor="k")
plt.xlabel(r"$\mathbf{x_1}$", size=15)
plt.ylabel(r"$\mathbf{x_2}$", size=15)
plt.show()

make_moons

make_moons() 함수는 이진분류를 위한 데이터를 생성합니다. 군집 데이터는 초승달 모양으로 분포되어 있습니다.

  • 인수
    • n_samples : 표본 데이터의 수, 디폴트 100
    • noise: 잡음의 크기. 0이면 정확한 반원을 이룸
from sklearn.datasets import make_moons
X7,y7=make_moons(n_samples=200, noise=0, random_state=9)
plt.scatter(X7[:,0], X7[:,1], s=100, c=y7, marker='o', edgecolor="k")
plt.xlabel(r"$\mathbf{x_1}$", size=15)
plt.ylabel(r"$\mathbf{x_2}$", size=15)
plt.show()
X7,y7=make_moons(n_samples=200, noise=0.1, random_state=9)
plt.scatter(X7[:,0], X7[:,1], s=100, c=y7, marker='o', edgecolor="k")
plt.xlabel(r"$\mathbf{x_1}$", size=15)
plt.ylabel(r"$\mathbf{x_2}$", size=15)
plt.show()
X7,y7=make_moons(n_samples=200, noise=1, random_state=9)
plt.scatter(X7[:,0], X7[:,1], s=100, c=y7, marker='o', edgecolor="k")
plt.xlabel(r"$\mathbf{x_1}$", size=15)
plt.ylabel(r"$\mathbf{x_2}$", size=15)
plt.show()

make_gaussian_quantiles

make_gaussian_quantiles() 함수는 다차원 정규 분포의 표본을 생성하고 분포의 평균(기대값)을 중심으로 한 등고선으로 클래스를 분리한다. 이 데이터는 타원형 형태의 닫힌 경계선으로만 분류할 수 있다.

  • 인수
    • mean: 기댓값 벡터
    • cov: 공분산 행렬
    • n_samples : 표본 데이터의 수, 디폴트 100
    • n_features : 독립 변수의 수, 디폴트 20
    • n_classes : 클래스의 수
  • 반환값
    • X : [n_samples, n_features] 크기의 배열, 독립 변수
    • y : [n_samples] 크기의 배열, 종속 변수
from sklearn.datasets import make_gaussian_quantiles
X8, y8=make_gaussian_quantiles(mean=[1, 5], n_samples=300, n_features=2, n_classes=2, random_state=10)
plt.scatter(X8[:,0], X8[:,1], s=100, c=y8, marker='o', edgecolor="k")
plt.xlabel(r"$\mathbf{x_1}$", size=15)
plt.ylabel(r"$\mathbf{x_2}$", size=15)
plt.show()

댓글