ADP/실기

자기조직화지도(Self-Organizing Map, SOM)

hyerimir 2024. 1. 28. 15:37

 

# 자기조직화지도
# 대뇌피질과 시각피질의 학습 과정을 모델화하여 자율학습에 의한 클러스터링을 수행하는 알고리즘
# Map size를 설정(군집의 수를 차원의 수로 맞추어야 함)
# default map을 조금씩 수정해서 데이터 분포 형태에 map을 근사
import pandas as pd
import numpy as np
iris = pd.read_csv('../data/iris.csv')

y = iris['target']
X = iris.drop('target', axis = 1)

# feature scaling
from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxSclaer(feature_range = (0,1))
X = scaler.fit_transform(X)

# 설치필요함
# ! pip install sklearn-som
from sklearn_som.som import SOM

iris_som = SOM(m = 3, n = 1, dim = 4)
# 여기서 dim은 변수의 개수
iris_som.fit(X, epochs = 100)

predictions = iris_som.predict(X)
iris['cluster'] = predictions
# 군집결과 시각화
import seaborn as sns
import matplotlib.pyplot as plt

sns.pairplot(iris, diag_kind = 'kde', hue = 'cluster', palette = 'bright')
plt.show()
# 17회 기출
# 데이터를 7:3으로 나누고, train 데이터셋을 som 알고리즘으로 군집화
# test 데이터셋에 대한 오분류표 구하기

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, stratify = y, test_size = 0.3,
	random_state = 2021)
    
som = SOM(m=3, n=1, dim = 4)
som.fit(X_train)

y_pred = som.predict(X_test)

result = pd.DataFrame()
result['y_test'] = y_test
result['y_pred'] = y_pred

result.loc[result['y_test'] == 'Iris-setosa', 'target_num'] = 0
result.loc[result['y_test'] == 'Iris-virginica', 'target_num'] = 2
result.loc[result['y_test'] == 'Iris-versicolor', 'target_num'] = 1
from sklearn.metrics import accuracy_score, confusion_matrix, roc_auc_score, classification_report
accuracy_score(result['target_num'], result['y_pred'])
confusion_matrix(result['target_num'], result['y_pred'])
print(classification_report(result['target_num'], result['y_pred']))