天天看點

自組織神經網絡(SOM)的Python第三方庫minisom分類功能實作

minisom分類功能

這個例子展示了如何使用 MiniSom 來解決分類問題。分類機制将使用 MiniSom 實作,評估将使用 sklearn。

首先,讓我們加載一個資料集(在本例中是著名的 Iris 資料集)并應用歸一化:

from minisom import MiniSom
import numpy as np

data = np.genfromtxt('iris.csv', delimiter=',', usecols=(0, 1, 2, 3))
data = np.apply_along_axis(lambda x: x/np.linalg.norm(x), 1, data)
labels = np.genfromtxt('iris.csv', delimiter=',', usecols=(4), dtype=str)      

這是一個簡單的分類函數,它使用配置設定給相關獲勝神經元的标簽對資料中的樣本進行分類。一個标簽 C 如果映射到該神經元中的大多數樣本具有标簽,則與該神經元相關聯 C. 該函數将配置設定資料集中最常見的标簽,以防樣本映射到未配置設定類别的神經元。

:
def classify(som, data):
    """Classifies each sample in data in one of the classes definited
    using the method labels_map.
    Returns a list of the same length of data where the i-th element
    is the class assigned to data[i].
    """
    winmap = som.labels_map(X_train, y_train)
    default_class = np.sum(list(winmap.values())).most_common()[0][0]
    result = []
    for d in data:
        win_position = som.winner(d)
        if win_position in winmap:
            result.append(winmap[win_position].most_common()[0][0])
        else:
            result.append(default_class)
    return result      

現在我們可以 1) 拆分訓練和測試集中的資料,2) 訓練 som,3) 列印包含所有名額的分類報告以評估分類結果。

from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report

X_train, X_test, y_train, y_test = train_test_split(data, labels, stratify=labels)

som = MiniSom(7, 7, 4, sigma=3, learning_rate=0.5, 
              neighborhood_function='triangle', random_seed=10)
som.pca_weights_init(X_train)
som.train_random(X_train, 500, verbose=False)

print(classification_report(y_test, classify(som, X_test)))
      
precision    recall  f1-score   support

  setosa       1.00      1.00      1.00        13      

versicolor 0.92 1.00 0.96 12

virginica 1.00 0.92 0.96 13

accuracy                           0.97        38      

macro avg 0.97 0.97 0.97 38

weighted avg 0.98 0.97 0.97 38