#라이브러리임포트
import pandas as pd
import matplotlib.pyplot as plt
uci_path = 'https://archive.ics.uci.edu/ml/machine-learning-databases/\
00292/Wholesale%20customers%20data.csv'
df = pd.read_csv(uci_path, header=0)
df.head(150)
df.info()
df['Channel'].unique()
# df.Channel.unique() 도 가능
df['Region'].unique()
# df.Channel.unique() 도 가능
X = df.iloc[:,:]
X.shape
X.head()
# 데이터 정규화 -> 스케일링(차원 축소)
from sklearn import preprocessing
X = preprocessing.StandardScaler().fit(X).transform(X)
from sklearn import cluster
kmeans = cluster.KMeans(n_clusters=5, random_state = 7) #5개의 군집으로 만들어줘
kmeans.fit(X)
kmeans.labels_
cluster_label = kmeans.labels_
cluster_label
df['Cluster'] = cluster_label
df.head()
df['Cluster'].unique()
# 채널과 지역의 연관관계(색 별 구분)
df.plot(kind='scatter', x='Channel', y='Region', c='Cluster',
cmap='Set1', figsize=(10,10))
# 우유와 델리의 연관관계(색 별 구분)
df.plot(kind='scatter', x='Milk', y='Delicassen', c='Cluster',
cmap='Set1', figsize=(10,10))
# 식료품와 신선식품의 연관관계(색 별 구분)
df.plot(kind='scatter', x='Grocery', y='Fresh', c='Cluster',
cmap='Set1', figsize=(10,10))
# 식료품과 종이형 세제의 연관관계(색 별 구분)
df.plot(kind='scatter', x='Grocery', y='Detergents_Paper', c='Cluster',
cmap='Set1', figsize=(10,10))
# 냉동식품과 종이형 세제의 연관관계(색 별 구분)
df.plot(kind='scatter', x='Frozen', y='Detergents_Paper', c='Cluster',
cmap='Set1', figsize=(10,10))
# 특정 cluster만 추출해서 시각화
mask = (df['Cluster']==0) | (df['Cluster']==3) # '|' = 또는
ndf=df[mask]
ndf.Cluster.unique()
# 클러스터 0과 3의 냉동식품과 종이형 세제의 연관관계(색 별 구분)
ndf.plot(kind='scatter', x='Frozen', y='Detergents_Paper', c='Cluster',
cmap='Set1', figsize=(10,10))
# 특정 cluster만 제외하고 시각화
mask = (df['Cluster']==0) | (df['Cluster']==3)
ndf = df[~mask] # '~' = except 의미
ndf.Cluster.unique()
# 클러스터 1,2,4의 동식품과 종이형 세제의 연관관계(색 별 구분)
ndf.plot(kind='scatter', x='Frozen', y='Detergents_Paper', c='Cluster',
cmap='Set1', figsize=(10,10))
# 데이터프레임을 사용해 df['Cluster'] 따라서 색으로 구분된 산점도 행렬
pd.plotting.scatter_matrix(df, c=df['Cluster'], figsize =(20,20), marker='o',
hist_kwds={'bins':20}, s=60, alpha=0.8)
plt.tight_layout()
import numpy as np
plt.imshow([np.unique(df['Cluster'])])
plt.show()
len(df[df['Cluster']==0])
len(df[df['Cluster']==1])
len(df[df['Cluster']==2])
len(df[df['Cluster']==3])
len(df[df['Cluster']==4])
#라이브러리 임포트
import pandas as pd
import folium
df = pd.read_excel('/content/2016_middle_shcool_graduates_report.xlsx', index_col=0,
header = 0, engine ='openpyxl')
df.head()
df.info()
df['코드'].unique()
df['주야'].unique()
df['지역'].unique()
len(df['지역'].unique())
df['유형'].unique()
결과값: array(['국립', '공립', '사립'], dtype=object)
상기 모든 컬럼들이 범주형이라는 것을 알 수 있다.
# 중학교 위치 지도 시각화
mschool_map = folium.Map(location=[37.55, 126.98], tiles='Stamen Terrain', zoom_start=12)
# 중학교 위치 정보를 CircleMarker로 표시 -> popup은 학교명 /필요한 컬럼: 위도, 경도, 학교명
for name, lat, lng in zip(df.학교명, df.위도, df.경도):
folium.CircleMarker([lat, lng], #위도 경도
radius=5, #반지름
color='brown', #둘레 색상
fill=True,
fill_color='coral', #원 안 색상
fill_opacity=0.7, #투명도
popup='<pre>'+ name +'</pre>').add_to(mschool_map)
mschool_map
from sklearn import preprocessing
label_encoder = preprocessing.LabelEncoder()
l_location = label_encoder.fit_transform(df['지역']) # unique에 맞게 인코딩(25개 -> 0 ~ 24)
l_code = label_encoder.fit_transform(df['코드']) # 3,5,9 -> 0,1,2 로 변경해줌(범위조절)
l_type = label_encoder.fit_transform(df['유형']) # unique에 맞게 인코딩(3개 -> 0 ~ 2)
l_day = label_encoder.fit_transform(df['주야']) # 주간 -> 0
# df 새로운 컬럼으로 추가
df['l_location'] = l_location
df['l_code'] = l_code
df['l_type'] = l_type
df['l_day'] = l_day
df.head()
columns_list = [9,10,11,13]
X = df.iloc[:, columns_list] # [rows_index, columns_index], : = 모든 rows를 의미
X = preprocessing.StandardScaler().fit(X).transform(X)
# DBSCAN 모델 설정
from sklearn import cluster
dbm = cluster.DBSCAN(eps = 0.3, min_samples=5)
dbm.fit(X)
import numpy as np
np.unique(dbm.labels_)
cluster_label = dbm.labels_
df['Cluster'] = cluster_label
df.head()
df['Cluster'].value_counts()
# 클러스터 1에 속하는 데이터만 보려면
df[df['Cluster']==1]
#클러스터 값을 기준(key)으로 그룹하고, 그룹별로 내용(value) 출력(5개 출력)
group_cols = [0,1,3] + columns_list
#지역, 학교명, 유형, + cols
grouped = df.groupby('Cluster')
grouped['Cluster'].value_counts()
for index, group in grouped: #key: -1,0,1,2,3,4/ value: 각 클러스터에 속한 df들
print(' * Cluster: ', index)
print(' * len: ', len(group))
print(group.iloc[:,group_cols].head())
# 중학교 위치 지도 시각화
cluster_map = folium.Map(location=[37.55, 126.98], tiles='Stamen Terrain', zoom_start=12)
colors = {-1: 'gray', 0:'coral', 1:'blue', 2:'green', 3:'red', 4:'purple', 5:'orange'}
# 중학교 위치 정보를 CircleMarker로 표시 -> popup은 학교명 /필요한 컬럼: 위도, 경도, 학교명
for name, lat, lng , clus in zip(df.학교명, df.위도, df.경도, df.Cluster):
folium.CircleMarker([lat, lng], #위도 경도
radius=5, #반지름
color=colors[clus], #둘레 색상
fill=True,
fill_color=colors[clus], #원 안 색상
fill_opacity=0.7, #투명도
popup='<pre>'+ name +'</pre>').add_to(cluster_map)
cluster_map