Self-Organizing Map (SOM) Clustering in Python: Visualizing 39 Samples with 10 Features
To cluster the samples using the Self-Organizing Map (SOM) algorithm, you can use the MiniSom library in Python. Here's an example code that will help you achieve this:
import numpy as np
from minisom import MiniSom
import matplotlib.pyplot as plt
# Define the dimensions of the SOM grid
grid_size = (8, 8) # Adjust the grid size according to your preference
# Load your data
data = np.random.rand(39, 10) # Replace this with your actual data
# Normalize the data
data = (data - np.min(data)) / (np.max(data) - np.min(data))
# Train the SOM
som = MiniSom(grid_size[0], grid_size[1], 10, sigma=1.0, learning_rate=0.5)
som.train_random(data, 100) # Adjust the number of iterations (100) according to your preference
# Get the cluster labels for each sample
cluster_labels = som.labels_map(data)
# Initialize an empty dictionary to store the samples for each cluster
clusters = {}
for i in range(grid_size[0]):
for j in range(grid_size[1]):
clusters[(i, j)] = []
# Assign each sample to its respective cluster
for idx, sample in enumerate(data):
x, y = som.winner(sample)
clusters[(x, y)].append(idx)
# Print the samples for each cluster
for cluster, samples in clusters.items():
print(f'Cluster {cluster}: {samples}')
# Visualize the clusters
plt.figure(figsize=(10, 10))
plt.pcolor(som.distance_map().T, cmap='bone_r') # Plot the distance map
plt.colorbar()
# Mark the samples for each cluster
for cluster, samples in clusters.items():
plt.plot(cluster[0] + 0.5, cluster[1] + 0.5, 'o', markerfacecolor='None', markeredgecolor='r', markersize=12, markeredgewidth=2)
for sample in samples:
plt.text(cluster[0] + 0.5, cluster[1] + 0.5, str(sample), color='g')
plt.show()
Make sure to replace the data variable with your actual data. The code will train the SOM on the data, assign cluster labels to each sample, and visualize the clusters on a grid. The cluster labels for each sample will also be printed.
原文地址: https://www.cveoy.top/t/topic/pTOR 著作权归作者所有。请勿转载和采集!