import pandas as pd
import math
retail_df = pd.read_excel('Online_Retail.xlsx')
retail_df.head()
aggregations = {
'InvoiceNo':'count',
'SaleAmount':'sum',
'InvoiceDate':'max'
}
customer_df = retail_df.groupby('CustomerID').agg(aggregations)
customer_df = customer_df.reset_index() # 하지 않으면 customrID가 index가 되어버림
customer_df.head() #작업 확인용 출력
k = 3 # Number of clusters
kmeans = KMeans(n_clusters=k)
kmeans.fit(scaled_data)
cluster_assignments = kmeans.labels_
centroids = kmeans.cluster_centers_
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score, silhouette_samples
X_features = customer_df[['Freq_log', 'SaleAmount_log', 'ElapsedDays_log']].values
# 정규 분포로 다시 스케일링하기
from sklearn.preprocessing import StandardScaler
X_features_scaled = StandardScaler().fit_transform(X_features)
kmeans = KMeans(n_clusters=3, random_state=0)
Y_labels = kmeans.fit_predict(X_features_scaled)
print (Y_labels) # cluster별로 임의의 번호를 붙인 것
customer_df['ClusterLabel'] = Y_labels
customer_df.head() #작업 확인용 출력
from matplotlib import cm
cm.jet(1/4)
def clusterScatter(n_cluster, X_features):
c_colors = []
kmeans = KMeans(n_clusters=n_cluster, random_state=0)
Y_labels = kmeans.fit_predict(X_features)
for i in range(n_cluster):
c_color = cm.jet(float(i) / n_cluster) #클러스터의 색상 설정
c_colors.append(c_color)
#클러스터의 데이터 분포를 동그라미로 시각화 , 0, 1 차원
plt.scatter(X_features[Y_labels == i,0], X_features[Y_labels == i,1],
marker='o', color=c_color, edgecolor='black', s=50,
label='cluster '+ str(i))
print (c_colors)
#각 클러스터의 중심점을 삼각형으로 표시
for i in range(n_cluster):
plt.scatter(kmeans.cluster_centers_[i,0], kmeans.cluster_centers_[i,1],
marker='^', color=c_colors[i], edgecolor='w', s=200)
plt.legend()
plt.grid()
plt.tight_layout()
plt.show()
k 값에 따라 clustering의 성능이 좌우됨
엘보우 방법 : 클러스터의 수를 순차적으로 늘려가면서 결과를 모니터링 한다. 만약 하나의 클러스터를 추가했을 때 이전보다 훨씬 더 나은 결과를 나타내지 않는다면, 이전의 클러스터의 수를 선택
distortions = []
for i in range(1, 6):
kmeans_i = KMeans(n_clusters=i, random_state=0) # 모델 생성
kmeans_i.fit(X_features_scaled) # 모델 훈련
distortions.append(kmeans_i.inertia_) # 클러스터 내 센트로이드와의 거리 제곱합
plt.plot(range(1,6), distortions, marker='o')
plt.xlabel('Number of clusters')
plt.ylabel('Distortion')
plt.show()
silhouette_values = silhouette_samples(X_features, Y_labels, metric='euclidean')
print (silhouette_values)
print (silhouette_values.mean())