클러스터링 연습
[공지사항] 지킬블로그 안내드립니다.
지킬 블로그에 대하여 알아보겠습니다.
클러스터링 연습
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
# Load data
df = pd.read_csv('./sample_data/spiral2.csv') # CSV 파일 경로
target = df['color'].to_numpy() # 추후 예측치와 비교를 위한
df.drop('color', axis=1, inplace=True)
data = df.to_numpy()
print(data)
print(target)
# Determine the optimal number of clusters (Elbow method)
inertia = []
for k in range(1, 7):
km = KMeans(n_clusters=k, n_init='auto', random_state=42)
km.fit(data)
inertia.append(km.inertia_)
plt.figure(figsize=(8, 5))
plt.plot(range(1, 7), inertia, marker='o')
plt.xlabel('Number of clusters (k)')
plt.ylabel('Inertia')
plt.title('Elbow Method for Determining Optimal k')
plt.show()
# Apply KMeans with the chosen number of clusters
km = KMeans(n_clusters=3, n_init='auto', random_state=42)
km.fit(data)
print(np.unique(km.labels_, return_counts=True))
# Plot the distribution of clusters
fig, axs = plt.subplots(1, 2, figsize=(16, 8))
axs[0].scatter(data[:, 0], data[:, 1], c=target, cmap='spring')
axs[0].set_title('Original Labels')
axs[1].scatter(data[:, 0], data[:, 1], c=km.labels_, cmap='inferno')
axs[1].set_title('KMeans Clusters')
plt.show()
코드 해석
넘파이 불러오기 하고 저장하는 코드 입니다.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
import numpy as np: NumPy 라이브러리를 np라는 이름으로 불러옵니다. 수치 계산에 유용합니다.import pandas as pd: Pandas 라이브러리를 pd라는 이름으로 불러옵니다. 데이터 처리를 위해 사용됩니다.import matplotlib.pyplot as plt: Matplotlib의 pyplot 모듈을 plt라는 이름으로 불러옵니다. 시각화를 위해 사용됩니다.from sklearn.cluster import KMeans: scikit-learn 라이브러리에서 KMeans 클래스를 불러옵니다. KMeans 클러스터링 알고리즘을 사용하기 위해 필요합니다.
# Load data
df = pd.read_csv('./sample_data/spiral2.csv') # CSV 파일 경로
target = df['color'].to_numpy() # 추후 예측치와 비교를 위한
df.drop('color', axis=1, inplace=True)
data = df.to_numpy()
df = pd.read_csv('./sample_data/spiral2.csv'): CSV 파일을 읽어와 Pandas DataFrame으로 저장합니다.target = df['color'].to_numpy(): ‘color’ 열을 NumPy 배열로 변환하여target변수에 저장합니다. 나중에 예측 결과와 비교하기 위해 사용합니다.df.drop('color', axis=1, inplace=True): DataFrame에서 ‘color’ 열을 제거합니다.axis=1은 열을 삭제함을 의미하며,inplace=True는 원래 DataFrame에 바로 적용함을 의미합니다.data = df.to_numpy(): DataFrame을 NumPy 배열로 변환하여data변수에 저장합니다. KMeans 알고리즘에 입력하기 위해 필요합니다.
print(data)
print(target)
print(data): NumPy 배열로 변환된 데이터를 출력합니다.print(target): 원래 ‘color’ 열을 출력합니다.
# Determine the optimal number of clusters (Elbow method)
inertia = []
for k in range(1, 7):
km = KMeans(n_clusters=k, n_init='auto', random_state=42)
km.fit(data)
inertia.append(km.inertia_)
-
inertia = []: 클러스터 개수에 따른 관성 값을 저장할 빈 리스트를 생성합니다. -
for k in range(1, 7)-
클러스터 개수를 1부터 6까지 반복합니다.
km = KMeans(n_clusters=k, n_init='auto', random_state=42): k개의 클러스터를 가지는 KMeans 객체를 생성합니다.n_init='auto'는 초기화 횟수를 자동으로 설정하며,random_state=42는 결과 재현을 위해 난수 시드를 고정합니다.km.fit(data): 데이터를 사용해 KMeans 모델을 학습시킵니다.inertia.append(km.inertia_): 학습된 KMeans 모델의 관성 값을 리스트에 추가합니다. 관성 값은 클러스터 내의 점들 사이의 거리를 측정합니다.
plt.figure(figsize=(8, 5))
plt.plot(range(1, 7), inertia, marker='o')
plt.xlabel('Number of clusters (k)')
plt.ylabel('Inertia')
plt.title('Elbow Method for Determining Optimal k')
plt.show()
plt.figure(figsize=(8, 5)): 8x5 인치 크기의 새로운 그림을 생성합니다.plt.plot(range(1, 7), inertia, marker='o'): x축에 클러스터 개수(1~6), y축에 각 클러스터 개수에 따른 관성 값을 가지는 선 그래프를 그립니다.marker='o'는 각 데이터 포인트에 원형 마커를 추가합니다.plt.xlabel('Number of clusters (k)'): x축에 레이블을 추가합니다.plt.ylabel('Inertia'): y축에 레이블을 추가합니다.plt.title('Elbow Method for Determining Optimal k'): 그래프에 제목을 추가합니다.plt.show(): 그래프를 화면에 표시합니다.
# Apply KMeans with the chosen number of clusters
km = KMeans(n_clusters=3, n_init='auto', random_state=42)
km.fit(data)
print(np.unique(km.labels_, return_counts=True))
km = KMeans(n_clusters=3, n_init='auto', random_state=42): 3개의 클러스터를 가지는 KMeans 객체를 생성합니다.km.fit(data): 데이터를 사용해 KMeans 모델을 학습시킵니다.print(np.unique(km.labels_, return_counts=True)): KMeans 모델의 클러스터 레이블의 고유값과 각 레이블의 개수를 출력합니다.
# Plot the distribution of clusters
fig, axs = plt.subplots(1, 2, figsize=(16, 8))
axs[0].scatter(data[:, 0], data[:, 1], c=target, cmap='spring')
axs[0].set_title('Original Labels')
axs[1].scatter(data[:, 0], data[:, 1], c=km.labels_, cmap='inferno')
axs[1].set_title('KMeans Clusters')
plt.show()
fig, axs = plt.subplots(1, 2, figsize=(16, 8)): 1행 2열로 구성된 서브플롯을 생성합니다. 전체 그림의 크기는 16x8 인치입니다.axs[0].scatter(data[:, 0], data[:, 1], c=target, cmap='spring'): 첫 번째 서브플롯에 원본 데이터의 산점도를 그립니다.c=target은 점들의 색상을 원본 레이블에 따라 설정하며,cmap='spring'은 색상 맵을 지정합니다.axs[0].set_title('Original Labels'): 첫 번째 서브플롯에 제목을 추가합니다.axs[1].scatter(data[:, 0], data[:, 1], c=km.labels_, cmap='inferno'): 두 번째 서브플롯에 KMeans 클러스터링 결과의 산점도를 그립니다.c=km.labels_는 점들의 색상을 클러스터 레이블에 따라 설정하며,cmap='inferno'은 색상 맵을 지정합니다.axs[1].set_title('KMeans Clusters'): 두 번째 서브플롯에 제목을 추가합니다.plt.show(): 전체 그림을 화면에 표시합니다.
댓글남기기