### Install kohonen Package Source: https://github.com/rwehrens/kohonen/blob/master/README.md Install the kohonen package from CRAN. This is the first step before using any of its functionalities. ```r install.packages("kohonen") ``` -------------------------------- ### Create SOM Grid with somgrid() Source: https://context7.com/rwehrens/kohonen/llms.txt Configure SOM grid topology, dimensions, and neighbourhood functions using `somgrid()`. Set `toroidal = TRUE` for wrapping edges (donut topology). ```r library(kohonen) # Create rectangular grid with Gaussian neighbourhood rect_grid <- somgrid( xdim = 8, # Width ydim = 6, # Height topo = "rectangular", # Grid topology neighbourhood.fct = "gaussian", # Neighbourhood function toroidal = FALSE # Non-wrapping edges ) # Create hexagonal grid with bubble neighbourhood (default) hex_grid <- somgrid( xdim = 10, ydim = 10, topo = "hexagonal", neighbourhood.fct = "bubble", toroidal = TRUE # Wrapping edges (donut topology) ) # Grid coordinates print(hex_grid$pts) # Returns matrix with x,y coordinates for each unit ``` -------------------------------- ### Train Supervised XYF Map Source: https://context7.com/rwehrens/kohonen/llms.txt Demonstrates training a supervised XYF map for wine classification. ```r library(kohonen) # Load and prepare data data(wines) set.seed(123) # Split into training (70%) and test (30%) train_idx <- sample(nrow(wines), round(0.7 * nrow(wines))) train_data <- scale(wines[train_idx, ]) test_data <- scale(wines[-train_idx, ], center = attr(train_data, "scaled:center"), scale = attr(train_data, "scaled:scale")) train_vintages <- vintages[train_idx] test_vintages <- vintages[-train_idx] # Train supervised XYF map xyf.wines <- xyf( X = train_data, Y = train_vintages, grid = somgrid(6, 6, "hexagonal"), rlen = 200 ) ``` -------------------------------- ### somgrid() - Create SOM Grid Source: https://context7.com/rwehrens/kohonen/llms.txt Creates grid structures for organizing map units with options for topology, shape, and neighbourhood functions. ```APIDOC ## somgrid(xdim, ydim, topo, neighbourhood.fct, toroidal) ### Description Creates grid structures for map units. ### Parameters #### Request Body - **xdim** (numeric) - Required - Width of the grid. - **ydim** (numeric) - Required - Height of the grid. - **topo** (string) - Optional - Grid topology (rectangular, hexagonal). - **neighbourhood.fct** (string) - Optional - Neighbourhood function (gaussian, bubble). - **toroidal** (logical) - Optional - Whether to use wrapping edges. ``` -------------------------------- ### supersom() - Train Multi-Layer SOM Source: https://context7.com/rwehrens/kohonen/llms.txt Trains maps with multiple data layers, allowing integration of different data types with customizable weights. ```APIDOC ## supersom(data, grid, whatmap, user.weights, maxNA.fraction, rlen, mode) ### Description Trains maps with multiple data layers. ### Parameters #### Request Body - **data** (list) - Required - List of data matrices. - **grid** (somgrid) - Required - Grid configuration object. - **whatmap** (vector) - Optional - Layers to use. - **user.weights** (vector) - Optional - Weights for each layer. - **maxNA.fraction** (numeric) - Optional - Fraction of allowed NA values. - **rlen** (numeric) - Optional - Number of training iterations. - **mode** (string) - Optional - Training mode (online, batch, pbatch). ``` -------------------------------- ### Train a Basic SOM with som() Source: https://context7.com/rwehrens/kohonen/llms.txt Use the `som()` function to train a standard self-organizing map on a single data matrix. Ensure data is scaled before training. The `rlen` parameter controls training iterations, and `alpha` sets the learning rate. ```r library(kohonen) # Load the wines dataset data(wines) # Scale the data and train a 5x5 hexagonal SOM som.wines <- som( X = scale(wines), grid = somgrid(5, 5, "hexagonal"), rlen = 100, # Number of training iterations alpha = c(0.05, 0.01), # Learning rate (start, end) keep.data = TRUE ) # View summary of trained map summary(som.wines) # Output: SOM of size 5x5 with a hexagonal topology and a bubble neighbourhood function. # The number of data layers is 1. # Distance measure(s) used: sumofsquares. # Training data included: 177 objects. # Mean distance to the closest unit in the map: 1.536. # Get number of units in the map nunits(som.wines) # Output: 25 ``` -------------------------------- ### Visualize Kohonen Training Progress and Results Source: https://context7.com/rwehrens/kohonen/llms.txt Uses standard plot methods to inspect training changes, unit counts, and codebook mappings for multi-modal data. ```R par(mfrow = c(2, 2)) plot(xyf.wines, type = "changes", main = "Training Progress") plot(xyf.wines, type = "counts", main = "Unit Counts") plot(xyf.wines, type = "codes", whatmap = 1, main = "Wine Properties") plot(xyf.wines, type = "codes", whatmap = 2, main = "Vintage Codes") ``` -------------------------------- ### som() - Train Basic SOM Source: https://context7.com/rwehrens/kohonen/llms.txt Trains a standard self-organizing map on a single data matrix to map high-dimensional data to a two-dimensional grid. ```APIDOC ## som(X, grid, rlen, alpha, keep.data) ### Description Trains a standard self-organizing map on a single data matrix. ### Parameters #### Request Body - **X** (matrix) - Required - Data matrix to be mapped. - **grid** (somgrid) - Required - Grid configuration object. - **rlen** (numeric) - Optional - Number of training iterations. - **alpha** (numeric vector) - Optional - Learning rate (start, end). - **keep.data** (logical) - Optional - Whether to keep the training data in the object. ``` -------------------------------- ### getCodes Source: https://context7.com/rwehrens/kohonen/llms.txt Extracts codebook vectors from a trained kohonen object. ```APIDOC ## getCodes ### Description Extracts codebook vectors from a trained kohonen object, supporting both single-layer and multi-layer (supersom) maps. ### Parameters #### Request Body - **kohonen_object** (object) - Required - A trained kohonen object. - **idx** (integer/vector) - Optional - Index or indices of the layers to extract. ``` -------------------------------- ### xyf() - Train Supervised SOM Source: https://context7.com/rwehrens/kohonen/llms.txt Trains a two-layer map where one layer contains features and another contains class labels for supervised learning. ```APIDOC ## xyf(X, Y, grid, rlen) ### Description Trains a two-layer map for supervised learning scenarios. ### Parameters #### Request Body - **X** (matrix) - Required - Feature matrix. - **Y** (factor/matrix) - Required - Class labels. - **grid** (somgrid) - Required - Grid configuration object. - **rlen** (numeric) - Optional - Number of training iterations. ``` -------------------------------- ### Visualize Trained Maps Source: https://context7.com/rwehrens/kohonen/llms.txt Provides various visualization types for examining trained self-organizing maps. ```r library(kohonen) data(wines) som.wines <- som(scale(wines), grid = somgrid(5, 5, "hexagonal")) # 1. Codebook vectors visualization plot(som.wines, type = "codes", main = "Codebook Vectors") # 2. Training progress plot(som.wines, type = "changes", main = "Training Progress") # 3. Mapping plot - show where objects map plot(som.wines, type = "mapping", pchs = 20, main = "Object Mapping") # 4. Counts plot - number of objects per unit plot(som.wines, type = "counts", main = "Unit Population") # 5. Quality plot - distance of objects to winning units plot(som.wines, type = "quality", palette.name = heat.colors, main = "Mapping Quality") # 6. U-matrix - neighbour distances (cluster boundaries) plot(som.wines, type = "dist.neighbours", main = "U-Matrix (Neighbour Distances)") # 7. Property plot - visualize any unit property # Example: show first codebook dimension as property codes <- getCodes(som.wines) plot(som.wines, type = "property", property = codes[, 1], main = "First Variable") ``` -------------------------------- ### Train Multi-Layer SOMs with supersom() Source: https://context7.com/rwehrens/kohonen/llms.txt Use `supersom()` for multi-layer SOMs, integrating different data types with specified weights and distance functions. Set `maxNA.fraction` to handle missing values and `mode` for training strategy (online, batch, pbatch). ```r library(kohonen) data(yeast) # Train supersom with multiple gene expression time series yeast.supersom <- supersom( data = yeast, # List of data matrices grid = somgrid(6, 6, "hexagonal"), whatmap = c("alpha", "cdc15", "cdc28", "elu"), # Layers to use user.weights = c(1, 1, 1, 1), # Equal weights maxNA.fraction = 0.5, # Allow up to 50% NA values rlen = 100, mode = "online" # Training mode: online, batch, pbatch ) # View training progress plot(yeast.supersom, "changes") # Visualize object mapping with class colors obj.classes <- as.integer(yeast$class) colors <- c("yellow", "green", "blue", "red", "orange") plot(yeast.supersom, type = "mapping", col = colors[obj.classes], pch = obj.classes, main = "Yeast Data Clustering") ``` -------------------------------- ### plot.kohonen - Visualize Trained Maps Source: https://context7.com/rwehrens/kohonen/llms.txt The `plot()` function provides multiple visualization types for examining trained self-organizing maps, including codebook vectors, training progress, mapping, counts, quality, U-matrix, and property plots. ```APIDOC ## plot.kohonen - Visualize Trained Maps ### Description The `plot()` function provides multiple visualization types for examining trained self-organizing maps. ### Method `plot(x, type, ...)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```r library(kohonen) data(wines) som.wines <- som(scale(wines), grid = somgrid(5, 5, "hexagonal")) # 1. Codebook vectors visualization plot(som.wines, type = "codes", main = "Codebook Vectors") # 2. Training progress plot(som.wines, type = "changes", main = "Training Progress") # 3. Mapping plot - show where objects map plot(som.wines, type = "mapping", pchs = 20, main = "Object Mapping") # 4. Counts plot - number of objects per unit plot(som.wines, type = "counts", main = "Unit Population") # 5. Quality plot - distance of objects to winning units plot(som.wines, type = "quality", palette.name = heat.colors, main = "Mapping Quality") # 6. U-matrix - neighbour distances (cluster boundaries) plot(som.wines, type = "dist.neighbours", main = "U-Matrix (Neighbour Distances)") # 7. Property plot - visualize any unit property # Example: show first codebook dimension as property codes <- getCodes(som.wines) plot(som.wines, type = "property", property = codes[, 1], main = "First Variable") ``` ### Response #### Success Response (200) Generates various plots based on the `type` parameter. #### Response Example (Visual output, no direct code example for response body) ``` -------------------------------- ### Expand SOM Map Resolution with expandMap() Source: https://context7.com/rwehrens/kohonen/llms.txt Use `expandMap()` to double the resolution of an existing trained SOM by interpolating new codebook vectors from neighboring units. This function requires a previously trained SOM object. ```r library(kohonen) data(wines) ``` -------------------------------- ### Train a Supervised SOM with xyf() Source: https://context7.com/rwehrens/kohonen/llms.txt The `xyf()` function trains a two-layer map for supervised learning, separating features (X) from class labels (Y). Scale feature data before input. The `rlen` parameter controls training iterations. ```r library(kohonen) data(wines) # Train XYF map with wine measurements and vintage labels xyf.wines <- xyf( X = scale(wines), # Feature matrix Y = vintages, # Class labels (factor) grid = somgrid(5, 5, "hexagonal"), rlen = 100 ) summary(xyf.wines) # Output: SOM of size 5x5 with a hexagonal topology and a bubble neighbourhood function. # The number of data layers is 2. # Distance measure(s) used: sumofsquares, tanimoto. ``` -------------------------------- ### Validate Data Layers with check.whatmap Source: https://context7.com/rwehrens/kohonen/llms.txt Validates and converts whatmap specifications into numeric indices for supersom objects. ```r library(kohonen) data(yeast) # Train supersom yeast.som <- supersom(yeast, somgrid(4, 4, "hexagonal"), maxNA.fraction = 0.5) # Check whatmap by name valid_whatmap <- check.whatmap(yeast.som, c("alpha", "cdc15")) print(valid_whatmap) # Returns numeric indices # Check whatmap by index valid_whatmap <- check.whatmap(yeast.som, c(1, 3, 5)) print(valid_whatmap) ``` -------------------------------- ### Extract Codebook Vectors with getCodes Source: https://context7.com/rwehrens/kohonen/llms.txt Retrieves codebook vectors from a trained kohonen object, supporting both single-layer and multi-layer maps. ```r library(kohonen) data(wines) som.wines <- som(scale(wines), grid = somgrid(5, 5, "hexagonal")) # Get all codebook vectors (returns matrix for single-layer SOM) codes <- getCodes(som.wines) print(dim(codes)) # Output: [1] 25 13 (25 units, 13 variables) # For multi-layer maps data(yeast) yeast.supersom <- supersom(yeast, somgrid(4, 4, "hexagonal"), whatmap = c("alpha", "cdc15"), maxNA.fraction = 0.5) # Get specific layer alpha_codes <- getCodes(yeast.supersom, idx = 1) # Get multiple layers multi_codes <- getCodes(yeast.supersom, idx = 1:2) ``` -------------------------------- ### tricolor - Generate RGB Colors for Map Units Source: https://context7.com/rwehrens/kohonen/llms.txt The `tricolor()` function generates RGB color values for map units based on their grid positions, useful for visualizing map topology and spatial relationships. ```APIDOC ## tricolor - Generate RGB Colors for Map Units ### Description The `tricolor()` function generates RGB color values for map units based on their grid positions, useful for visualizing map topology. ### Method `tricolor(grid, offset = 0)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```r library(kohonen) # Create grid grid <- somgrid(10, 10, "hexagonal") # Generate tricolor palette (default RGB based on position) unit_colors <- tricolor(grid, offset = 0.2) # Create map visualization data(wines) som.wines <- som(scale(wines), grid = grid) # Use tricolors as background plot(som.wines, type = "mapping", bgcol = rgb(unit_colors[, 1], unit_colors[, 2], unit_colors[, 3]), main = "Map with Tricolor Background") ``` ### Response #### Success Response (200) - **unit_colors** (matrix) - A matrix where each row represents a map unit and columns are R, G, B values. #### Response Example ```r # Example output structure: # [,1] [,2] [,3] # [1,] 0.1 0.5 0.9 # [2,] 0.2 0.6 0.8 # ... ``` ``` -------------------------------- ### Generate RGB Colors for Map Units Source: https://context7.com/rwehrens/kohonen/llms.txt Generates RGB color values for map units based on their grid positions to visualize topology. ```r library(kohonen) # Create grid grid <- somgrid(10, 10, "hexagonal") # Generate tricolor palette (default RGB based on position) unit_colors <- tricolor(grid, offset = 0.2) # Create map visualization data(wines) som.wines <- som(scale(wines), grid = grid) # Use tricolors as background plot(som.wines, type = "mapping", bgcol = rgb(unit_colors[, 1], unit_colors[, 2], unit_colors[, 3]), main = "Map with Tricolor Background") ``` -------------------------------- ### Calculate Topological Distances with unit.distances Source: https://context7.com/rwehrens/kohonen/llms.txt Computes topological distances between all pairs of units in a map grid, using Chebyshev distance for rectangular grids and Euclidean for hexagonal. ```r library(kohonen) # Create grids with different topologies rect_grid <- somgrid(4, 4, "rectangular") hex_grid <- somgrid(4, 4, "hexagonal") # Calculate unit distances rect_dist <- unit.distances(rect_grid) hex_dist <- unit.distances(hex_grid) # For rectangular grids, uses Chebyshev distance (maximum of x,y differences) # For hexagonal grids, uses Euclidean distance # Find immediate neighbours (distance = 1) neighbours_of_unit_1 <- which(hex_dist[1, ] > 0 & hex_dist[1, ] <= 1.01) print(neighbours_of_unit_1) # Output: [1] 2 5 6 ``` -------------------------------- ### predict.kohonen - Make Predictions Using Trained Map Source: https://context7.com/rwehrens/kohonen/llms.txt The `predict()` function uses a trained map to predict properties for new data based on the training data's unit associations. It can be used for classification tasks. ```APIDOC ## predict.kohonen - Make Predictions Using Trained Map ### Description The `predict()` function uses a trained map to predict properties for new data based on the training data's unit associations. ### Method `predict(object, newdata, whatmap, ...)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```r library(kohonen) data(wines) # Prepare training and test data training <- sample(nrow(wines), 120) Xtraining <- scale(wines[training, ]) Xtest <- scale(wines[-training, ], center = attr(Xtraining, "scaled:center"), scale = attr(Xtraining, "scaled:scale")) # Create named data lists trainingdata <- list( measurements = Xtraining, vintages = vintages[training] ) testdata <- list( measurements = Xtest, vintages = vintages[-training] ) # Train supervised map mygrid <- somgrid(5, 5, "hexagonal") som.wines <- supersom(trainingdata, grid = mygrid) # Predict vintages for test data using only measurements som.prediction <- predict(som.wines, newdata = testdata, whatmap = "measurements") ``` ### Response #### Success Response (200) - **predictions** (list) - A list containing the predicted values for specified variables. #### Response Example ```r # Confusion matrix table(Actual = vintages[-training], Predicted = som.prediction$predictions[["vintages"]]) # Output: # Predicted # Actual Barbera Barolo Grignolino # Barbera 15 0 3 # Barolo 1 18 0 # Grignolino 2 0 18 ``` ``` -------------------------------- ### Expand SOM Map Resolution Source: https://context7.com/rwehrens/kohonen/llms.txt Increases the resolution of an existing SOM while preserving learned patterns. ```r # Train initial small map small_som <- som(scale(wines), grid = somgrid(3, 3, "hexagonal")) # Expand to 6x6 map expanded_som <- expandMap(small_som) # The expanded map preserves learned patterns but with finer resolution print(expanded_som$grid) # New dimensions: 6x6 ``` -------------------------------- ### Convert Class Vectors with classvec2classmat Source: https://context7.com/rwehrens/kohonen/llms.txt Converts factors to binary indicator matrices and vice versa, useful for supervised SOMs. ```r library(kohonen) # Convert factor to class matrix class_vector <- factor(c("A", "B", "A", "C", "B", "A")) class_matrix <- classvec2classmat(class_vector) print(class_matrix) # A B C # [1,] 1 0 0 # [2,] 0 1 0 # [3,] 1 0 0 # [4,] 0 0 1 # [5,] 0 1 0 # [6,] 1 0 0 # Convert back to class vector recovered_classes <- classmat2classvec(class_matrix) print(recovered_classes) # Output: [1] A B A C B A # Levels: A B C # With threshold for uncertain predictions class_matrix_uncertain <- class_matrix * 0.3 # Low confidence classmat2classvec(class_matrix_uncertain, threshold = 0.5) # Returns NA for predictions below threshold ``` -------------------------------- ### Map New Data to Trained SOM Source: https://context7.com/rwehrens/kohonen/llms.txt Maps new observations to the closest units in a trained self-organizing map using the map function. ```r library(kohonen) data(wines) # Split data for training and testing set.seed(42) training_idx <- sample(nrow(wines), 120) train_data <- scale(wines[training_idx, ]) test_data <- scale(wines[-training_idx, ], center = attr(train_data, "scaled:center"), scale = attr(train_data, "scaled:scale")) # Train SOM som.wines <- som(train_data, grid = somgrid(5, 5, "hexagonal")) # Map test data to trained SOM mapping_result <- map(som.wines, newdata = test_data) # Results contain: # - unit.classif: winning unit for each test observation # - distances: distance to winning unit print(mapping_result$unit.classif) # Output: [1] 7 13 18 22 ... print(mapping_result$distances) # Output: [1] 1.234 0.987 1.456 ... ``` -------------------------------- ### map.kohonen - Map New Data to Trained SOM Source: https://context7.com/rwehrens/kohonen/llms.txt The `map()` function maps new observations to the closest units in a trained self-organizing map. It returns the winning unit for each observation and the distance to that unit. ```APIDOC ## map.kohonen - Map New Data to Trained SOM ### Description The `map()` function maps new observations to the closest units in a trained self-organizing map. ### Method `map(x, newdata, ...)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```r library(kohonen) data(wines) # Split data for training and testing set.seed(42) training_idx <- sample(nrow(wines), 120) train_data <- scale(wines[training_idx, ]) test_data <- scale(wines[-training_idx, ], center = attr(train_data, "scaled:center"), scale = attr(train_data, "scaled:scale")) # Train SOM som.wines <- som(train_data, grid = somgrid(5, 5, "hexagonal")) # Map test data to trained SOM mapping_result <- map(som.wines, newdata = test_data) ``` ### Response #### Success Response (200) - **unit.classif** (numeric vector) - The winning unit for each test observation. - **distances** (numeric vector) - The distance of each test observation to its winning unit. #### Response Example ```r print(mapping_result$unit.classif) # Output: [1] 7 13 18 22 ... print(mapping_result$distances) # Output: [1] 1.234 0.987 1.456 ... ``` ``` -------------------------------- ### Predict Properties Using Trained Map Source: https://context7.com/rwehrens/kohonen/llms.txt Uses a trained map to predict properties for new data based on unit associations. ```r library(kohonen) data(wines) # Prepare training and test data training <- sample(nrow(wines), 120) Xtraining <- scale(wines[training, ]) Xtest <- scale(wines[-training, ], center = attr(Xtraining, "scaled:center"), scale = attr(Xtraining, "scaled:scale")) # Create named data lists trainingdata <- list( measurements = Xtraining, vintages = vintages[training] ) testdata <- list( measurements = Xtest, vintages = vintages[-training] ) # Train supervised map mygrid <- somgrid(5, 5, "hexagonal") som.wines <- supersom(trainingdata, grid = mygrid) # Predict vintages for test data using only measurements som.prediction <- predict(som.wines, newdata = testdata, whatmap = "measurements") # Confusion matrix table(Actual = vintages[-training], Predicted = som.prediction$predictions[["vintages"]]) # Output: # Predicted # Actual Barbera Barolo Grignolino # Barbera 15 0 3 # Barolo 1 18 0 # Grignolino 2 0 18 ``` -------------------------------- ### Predict and Evaluate Model Performance Source: https://context7.com/rwehrens/kohonen/llms.txt Generates predictions from a trained model and calculates classification accuracy using a confusion matrix. ```R # Predict test data predictions <- predict(xyf.wines, newdata = test_data, whatmap = 1) # Evaluate accuracy confusion <- table(Actual = test_vintages, Predicted = predictions$predictions[[2]]) print(confusion) accuracy <- sum(diag(confusion)) / sum(confusion) cat("Classification Accuracy:", round(accuracy * 100, 1), "%\n") ``` -------------------------------- ### Calculate Layer-Specific Distances with layer.distances Source: https://context7.com/rwehrens/kohonen/llms.txt Calculates average distances between objects and their winning units for specific data layers in a supersom. ```r library(kohonen) data(yeast) # Train multi-layer supersom yeast.supersom <- supersom(yeast, grid = somgrid(6, 6, "hexagonal"), whatmap = c("alpha", "cdc15"), maxNA.fraction = 0.5) # Calculate layer-specific quality for each unit alpha_quality <- layer.distances(yeast.supersom, whatmap = "alpha") cdc15_quality <- layer.distances(yeast.supersom, whatmap = "cdc15") # Compare layer qualities print(summary(alpha_quality)) print(summary(cdc15_quality)) ``` -------------------------------- ### add.cluster.boundaries - Overlay Cluster Boundaries Source: https://context7.com/rwehrens/kohonen/llms.txt The `add.cluster.boundaries()` function adds cluster boundaries to an existing map plot based on a clustering of the units. This helps in visualizing the clusters identified on the SOM. ```APIDOC ## add.cluster.boundaries - Overlay Cluster Boundaries ### Description The `add.cluster.boundaries()` function adds cluster boundaries to an existing map plot based on a clustering of the units. ### Method `add.cluster.boundaries(som.model, clustering, ...)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```r library(kohonen) data(wines) som.wines <- som(scale(wines), grid = somgrid(5, 5, "hexagonal")) # Cluster the codebook vectors codes <- getCodes(som.wines) unit_clusters <- cutree(hclust(dist(codes)), k = 3) # Create counts plot and add cluster boundaries plot(som.wines, type = "counts", main = "Units with Cluster Boundaries") add.cluster.boundaries(som.wines, clustering = unit_clusters, lwd = 3, col = "blue") ``` ### Response #### Success Response (200) Adds cluster boundaries to the currently active plot. #### Response Example (Visual output, no direct code example for response body) ``` -------------------------------- ### Calculate Pairwise Distances with object.distances Source: https://context7.com/rwehrens/kohonen/llms.txt Calculates distances between training data objects or codebook vectors using the map's distance functions. ```r library(kohonen) data(wines) som.wines <- som(scale(wines), grid = somgrid(5, 5, "hexagonal")) # Distances between training data objects data_distances <- object.distances(som.wines, type = "data") print(as.matrix(data_distances)[1:5, 1:5]) # Distances between codebook vectors code_distances <- object.distances(som.wines, type = "codes") print(as.matrix(code_distances)[1:5, 1:5]) ``` -------------------------------- ### unit.distances Source: https://context7.com/rwehrens/kohonen/llms.txt Calculates the topological distances between all pairs of units in the map grid. ```APIDOC ## unit.distances ### Description Calculates the topological distances between all pairs of units in the map grid based on the grid topology (rectangular or hexagonal). ### Parameters #### Request Body - **grid** (somgrid) - Required - The grid object defining the map topology. ``` -------------------------------- ### classvec2classmat Source: https://context7.com/rwehrens/kohonen/llms.txt Converts a factor or class vector to a binary indicator matrix. ```APIDOC ## classvec2classmat ### Description Converts a factor or class vector to a binary indicator matrix for use in supervised SOMs. The inverse function classmat2classvec is also available. ### Parameters #### Request Body - **class_vector** (factor/vector) - Required - The input class vector to convert. ``` -------------------------------- ### Overlay Cluster Boundaries Source: https://context7.com/rwehrens/kohonen/llms.txt Adds cluster boundaries to an existing map plot based on a clustering of the units. ```r library(kohonen) data(wines) som.wines <- som(scale(wines), grid = somgrid(5, 5, "hexagonal")) # Cluster the codebook vectors codes <- getCodes(som.wines) unit_clusters <- cutree(hclust(dist(codes)), k = 3) # Create counts plot and add cluster boundaries plot(som.wines, type = "counts", main = "Units with Cluster Boundaries") add.cluster.boundaries(som.wines, clustering = unit_clusters, lwd = 3, col = "blue") ``` -------------------------------- ### object.distances Source: https://context7.com/rwehrens/kohonen/llms.txt Calculates pairwise distances between data objects or codebook vectors. ```APIDOC ## object.distances ### Description Calculates pairwise distances between data objects or codebook vectors using the map's distance functions. ### Parameters #### Request Body - **kohonen_object** (object) - Required - A trained kohonen object. - **type** (string) - Required - The type of distance to calculate: "data" for training data objects or "codes" for codebook vectors. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.