군집화 - K-means(colab에서 과제)

2023. 11. 29. 21:53빅데이터

728x90

1. K-means(K=2, seed=1) 알고리즘을 사용하여 데이터를 군집화하고, silhouette score를 출력하세요.

from pyspark.ml.clustering import KMeans
from pyspark.ml.evaluation import ClusteringEvaluator

#Train K-means model, k=2,seed=1 -> 2개의 클러스터로 
kmeans=KMeans().setK(2).setSeed(1)
model=kmeans.fit(features)

# make predictions
predictions=model.transform(features)

#evaluate clustering by computing silhouette score
evaluator=ClusteringEvaluator()
silhouette=evaluator.evaluate(predictions)

print(silhouette)

 

 

K-means 알고리즘의 Input Columns은 'features'라는 이름을 지닌 열을 가지고 있어야 하고,

그 열은 vector로 된 값들을 가지고 있어야 한다.

 

silhouette score

: clustering이 얼마나 잘됐나 나타내는 지표 s(i)

a(i)= i라는 점과 같은 cluster에 위치한 다른 모든 점들까지의 평균거리

b(i)= i라는 점과 가장 가까운 cluster안의 모든 점들까지의 평균거리

s(i)는 -1 ~1의 값을 갖고, 1에 가까울수록 clustering이 잘된 것.

 

 

2. PCA로 차원을 축소하여 features를 2차원 데이터로 변환한 후

각 data points를 scatter plot으로 그리기

from pyspark.ml.feature import PCA
from pyspark.ml.linalg import Vectors
import numpy as np
import matplotlib.pyplot as plt

# PCA
pca=PCA(k=2,inputCol="features",outputCol="pcaFeatures")
model=pca.fit(features)
result=model.transform(features).select("pcaFeatures")

# pandas DataFrame으로 변환
pd_res = result.toPandas()

# Vector로 묶여 있는 두 개의 점을 'x'와 'y'로 분리하여 기존의 DataFrame에 추가
pd_res[['x', 'y']] = pd.DataFrame(pd_res.pcaFeatures.tolist(), index=pd_res.index)


plt.scatter(pd_res['x'], pd_res['y'] , alpha=0.25) # x 좌표, y 좌표, 투명도 설정
plt.show() # 그리기

 

728x90

'빅데이터' 카테고리의 다른 글

Recommender System  (0) 2023.12.03
Dimensionality Reduction(차원 축소)  (2) 2023.12.03
추천시스템 - ALS (colab에서 과제)  (1) 2023.11.29
Clustering  (0) 2023.11.25
Distance Measures  (5) 2023.11.25