Package: python-som
python-somImplementation of the 2D self-organizing map, with support for NumPy arrays and Pandas DataFrames.
Most features were implemented using NumPy, with Scikit-learn for standardization and PCA operations.FeaturesStepwise and batch trainingRandom weight initializationRandom sampling weight initializationLinear weight initialization (with PCA)Automatic selection of map size ratio (with PCA)Support for cyclic arrays, for toroidal or spherical mapsGaussian and Bubble neighborhood functionsSupport for custom decay functionsSupport for visualization (U-matrix, activation matrix)Support for supervised learning (label map)Support for NumPy arrays, Pandas DataFrames and regular lists of valuesUsageIn the following code excerpt (also available intest.py) is an example of instantiation and training of a SOM with the Iris dataset:# Import python_somimportpython_som# Import NumPy and Pandas for storing dataimportnumpyasnpimportpandasaspd# Import libraries for plotting resultsimportmatplotlib.pyplotaspltimportseabornassns# Load Iris dataset and columns of features and labelsiris=sns.load_dataset('iris')target=iris.iloc[:,-1].to_numpy()iris=iris.iloc[:,:-1].to_numpy()# Transform labels into numeric codes for plottingtg=np.zeros(len(target),dtype=int)tg[target=='setosa']=0tg[target=='versicolor']=1tg[target=='virginica']=2# Instantiate SOM from  python_som# Selecting shape automatically (providing dataset for constructor)# Using default decay and distance functions# Using gaussian neighborhood function# Using cyclic arrays in the vertical and horizontal directionssom=python_som.SOM(x=20,y=None,input_len=iris.shape[1],learning_rate=0.5,neighborhood_radius=1.0,neighborhood_function='gaussian',cyclic_x=True,cyclic_y=True,data=iris)# Initialize weights of the SOM with linear initializationsom.weight_initialization(mode='linear',data=iris)# Training SOM with default number of iterations# Using batch learning processsom.train(data=iris,n_iteration=len(iris),mode='batch',verbose=True)# Calculating distance matrix for plottingumatrix=som.distance_matrix().T# Plotting U-matrix with seaborn/matplotlibplt.figure(figsize=som.get_shape())plt.pcolor(umatrix,cmap='bone_r')markers=['o','s','D']colors=['C0','C1','C2']forcnt,xxinenumerate(iris):w=som.winner(xx)# getting the winnerplt.plot(w[0]+.5,w[1]+.5,markers[tg[cnt]],markerfacecolor='None',markeredgecolor=colors[tg[cnt]],markersize=12,markeredgewidth=2)plt.axis([0,som.get_shape()[0],0,som.get_shape()[1]])plt.show()Test outputThe following image is generated from the previous test code, with the U-matrix of the trained SOM, and the distribution of the instances from the Iris dataset.
In this graph, the instances are mapped to the self-organizing map, with color codes for each different label:Setosa: blue circleVersicolor: orange squareVirginica: green diamondPublic methods and functionsThe following are lists of public methods and functions currently available in the SOM class. The full documentation of each method can be found in thesource code:Utility functions_asymptotic_decay_linear_decay_exponential_decay_inverse_decay_euclidean_distanceSOM public methodsSOMSOM.get_shapeSOM.get_weightsSOM.set_learning_rateSOM.set_neighborhood_radiusSOM.activateSOM.winnerSOM.quantizationSOM.quantization_errorSOM.distance_matrixSOM.activation_matrixSOM.winner_mapSOM.label_mapSOM.trainSOM.weight_initializationReferencesThis implemetation was based on the following paper, by Professor Teuvo Kohonen:Teuvo Kohonen,
Essentials of the self-organizing map,
Neural Networks,
Volume 37,
2013,
Pages 52-65,
ISSN 0893-6080,https://doi.org/10.1016/j.neunet.2012.09.018.