클러스터 시각화
방금 최적의 k 값(k=16)으로 k-means 모델을 학습하고 클러스터 센터(센트로이드)를 생성했어요. 마지막 연습에서는 클러스터와 센트로이드를 겹쳐서 시각화합니다. 이렇게 하면 군집화가 얼마나 잘 되었는지 확인할 수 있어요(이상적으로는 클러스터끼리는 뚜렷하게 분리되고, 센트로이드는 각 클러스터의 중심에 있어야 합니다).
이를 위해 먼저 rdd_split_int RDD를 Spark DataFrame으로, 이어서 플로팅에 사용할 수 있는 Pandas DataFrame으로 변환해요. 같은 방식으로 cluster_centers도 Pandas DataFrame으로 변환합니다. 두 DataFrame을 모두 만든 뒤에는 Matplotlib으로 산점도를 그립니다.
워크스페이스에는 SparkContext sc, 변수 rdd_split_int와 cluster_centers, 그리고 matplotlib.pyplot(별칭 plt)이 준비되어 있습니다.
이 연습은 강의의 일부입니다
PySpark로 배우는 빅데이터 기초
연습 안내
rdd_split_intRDD를 Spark DataFrame으로 변환한 다음, pandas DataFrame으로 변환하세요.cluster_centers리스트에서 pandas DataFrame을 만드세요.- 원시 데이터의 pandas DataFrame(
rdd_split_int_df_pandas)으로 산점도를 그리고, 센트로이드의 Pandas DataFrame(cluster_centers_pandas) 산점도를 그 위에 겹쳐 표시하세요.
실습형 인터랙티브 연습
이 예제를 이 샘플 코드를 완성하여 풀어보세요.
# Convert rdd_split_int RDD into Spark DataFrame and then to Pandas DataFrame
rdd_split_int_df_pandas = spark.____(rdd_split_int, schema=["col1", "col2"]).toPandas()
# Convert cluster_centers to a pandas DataFrame
cluster_centers_pandas = pd.DataFrame(____, columns=["col1", "col2"])
# Create an overlaid scatter plot of clusters and centroids
plt.scatter(rdd_split_int_df_pandas["col1"], rdd_split_int_df_pandas["col2"])
plt.scatter(____["col1"], ____["col2"], color="red", marker="x")
plt.show()