### Example: Class Matrix Conversion Source: https://rwehrens.r-universe.dev/kohonen/doc/manual.html Demonstrates the conversion between class vectors and class matrices using sample data. ```R classes <- c(rep(1, 5), rep(2, 7), rep(3, 9)) classmat <- classvec2classmat(classes) classmat classmat2classvec(classmat) ``` ```R classes <- c(rep(1, 5), rep(2, 7), rep(3, 9)) classmat <- classvec2classmat(classes) classmat classmat2classvec(classmat) ``` -------------------------------- ### Example: Process Powder Pattern Data Source: https://rwehrens.r-universe.dev/kohonen/doc/manual.html An example demonstrating how to load and process the 'degelder' dataset, including creating a custom distance function and training a Self-Organizing Map (SOM). ```R ## Not run: data(degelder) mydata <- list(patterns = degelder$patterns, CellVol = log(degelder$properties[,"cell.vol"])) ## custom distance function require(Rcpp) sourceCpp(system.file("Distances", "wcc.cpp", package = "kohonen")) set.seed(7) powsom <- supersom(data = mydata, grid = somgrid(6, 4, "hexagonal"), dist.fcts = c("WCCd", "sumofsquares"), keep.data = TRUE) summary(powsom) ## End(Not run) ``` ```R ## Not run: data(degelder) mydata <- list(patterns = degelder$patterns, CellVol = log(degelder$properties[,"cell.vol"])) ## custom distance function require(Rcpp) sourceCpp(system.file("Distances", "wcc.cpp", package = "kohonen")) set.seed(7) powsom <- supersom(data = mydata, grid = somgrid(6, 4, "hexagonal"), dist.fcts = c("WCCd", "sumofsquares"), keep.data = TRUE) summary(powsom) ## End(Not run) ``` -------------------------------- ### somgrid and unit.distances Functions Source: https://rwehrens.r-universe.dev/kohonen/doc/manual.html Documentation for the somgrid and unit.distances functions, including their arguments, return values, and usage examples. ```APIDOC ## somgrid and unit.distances Functions ### Description Functions for creating and analyzing Self-Organizing Map (SOM) grids. ### Arguments - **xdim** (numeric) - Dimensions of the grid. - **ydim** (numeric) - Dimensions of the grid. - **topo** (character) - Topology of the grid, either "rectangular" or "hexagonal". - **neighbourhood.fct** (character) - Neighbourhood function, either "bubble" or "gaussian". - **toroidal** (logical) - Whether the grid is toroidal. - **grid** (somgrid object) - An object of class "somgrid". ### Value - `somgrid`: Returns an object of class "somgrid" with grid points and input arguments. - `unit.distances`: Returns a symmetrical matrix containing distances between units. Calculates Euclidean or maximum distances based on `grid$n.hood`. For toroidal maps, calculates shortest path distances. ### Usage ```R somgrid(xdim = 8, ydim = 6, topo = c("rectangular", "hexagonal"), neighbourhood.fct = c("bubble", "gaussian"), toroidal = FALSE) unit.distances(grid, toroidal) ``` ### Examples ```R mygrid <- somgrid(5, 5, "hexagonal") fakesom <- list(grid = mygrid) class(fakesom) <- "kohonen" par(mfrow = c(2,1)) dists <- unit.distances(mygrid) plot(fakesom, type="property", property = dists[1,], main="Distances to unit 1", zlim=c(0,6), palette = rainbow, ncolors = 7) dists <- unit.distances(mygrid, toroidal=TRUE) plot(fakesom, type="property", property = dists[1,], main="Distances to unit 1 (toroidal)", zlim=c(0,6), palette = rainbow, ncolors = 7) ``` ``` -------------------------------- ### Create and Summarize a Kohonen Map with Wines Data Source: https://rwehrens.r-universe.dev/kohonen/doc/manual.html This example demonstrates creating a kohonen map using the `xyf` function with the 'wines' dataset and then summarizing the resulting object. It involves scaling data and converting class vectors. ```r data(wines) xyf.wines <- xyf(scale(wines), classvec2classmat(vintages), grid = somgrid(5, 5, "hexagonal")) xyf.wines summary(xyf.wines) ``` -------------------------------- ### Example: Expand SOM Map Source: https://rwehrens.r-universe.dev/kohonen/doc/manual.html Demonstrates expanding a Self-Organizing Map (SOM) using the 'expandMap' function and then retraining a SOM with the expanded grid and initialized codes. ```R data(yeast) yeast.supersom <- supersom(yeast, somgrid(4, 4, "hexagonal"), whatmap = 3:6, maxNA.fraction = .5) yeast.supersom2 <- expandMap(yeast.supersom) yeast.supersom3 <- supersom(yeast, yeast.supersom2$grid, whatmap = 3:6, maxNA.fraction = .5, init = yeast.supersom2$codes[3:6]) ``` ```R data(yeast) yeast.supersom <- supersom(yeast, somgrid(4, 4, "hexagonal"), whatmap = 3:6, maxNA.fraction = .5) yeast.supersom2 <- expandMap(yeast.supersom) yeast.supersom3 <- supersom(yeast, yeast.supersom2$grid, whatmap = 3:6, maxNA.fraction = .5, init = yeast.supersom2$codes[3:6]) ``` -------------------------------- ### Kohonen Map Plotting Examples Source: https://rwehrens.r-universe.dev/kohonen/doc/manual.html Examples demonstrating various plotting functions for Kohonen maps, including visualizing codebook vectors, mapping quality, unit predictions, component planes, and neighbor distances. ```APIDOC ## Visualize Codebook Vectors ### Description Displays both sets of codebook vectors in the map. ### Method plot ### Endpoint N/A (Function call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```R par(mfrow = c(1,2)) plot(kohmap, type="codes", main = c("Codes X", "Codes Y")) par(mfrow = c(1,1)) ``` ### Response #### Success Response (200) Displays plots. #### Response Example None ``` ```APIDOC ## Visualize Mapping Quality ### Description Plots the quality of the mapping, often represented by similarities, using a specified color palette. ### Method plot ### Endpoint N/A (Function call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```R similarities <- plot(kohmap, type="quality", palette.name = terrain.colors) ``` ### Response #### Success Response (200) Returns mapping quality values and displays a plot. #### Response Example None ``` ```APIDOC ## Visualize Mapping with Labels and Colors ### Description Plots the mapping of data points onto the Kohonen map, with options for labels and colors based on vintage. ### Method plot ### Endpoint N/A (Function call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```R plot(kohmap, type="mapping", labels = as.integer(vintages), col = as.integer(vintages), main = "mapping plot") ``` ### Response #### Success Response (200) Displays the mapping plot. #### Response Example None ``` ```APIDOC ## Visualize Mapping with Background Colors based on Predictions ### Description Adds background colors to map units based on predicted class labels. ### Method plot ### Endpoint N/A (Function call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```R xyfpredictions <- classmat2classvec(getCodes(kohmap, 2)) bgcols <- c("gray", "pink", "lightgreen") plot(kohmap, type="mapping", col = as.integer(vintages), pchs = as.integer(vintages), bgcol = bgcols[as.integer(xyfpredictions)], main = "another mapping plot", shape = "straight", border = NA) ``` ### Response #### Success Response (200) Displays the mapping plot with background colors. #### Response Example None ``` ```APIDOC ## Show Component Planes ### Description Displays 'component planes' for the SOM, showing the distribution of a specific component across the map. ### Method plot ### Endpoint N/A (Function call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```R set.seed(7) sommap <- som(scale(wines), grid = somgrid(6, 4, "hexagonal") ) plot(sommap, type = "property", property = getCodes(sommap, 1)[,1], main = colnames(getCodes(sommap, 1))[1]) ``` ### Response #### Success Response (200) Displays the component plane plot. #### Response Example None ``` ```APIDOC ## Show the U-Matrix ### Description Displays the U-matrix (Unified Distance Matrix) which shows the average distance between a unit and its neighbors, useful for visualizing clusters. ### Method plot ### Endpoint N/A (Function call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```R Umat <- plot(sommap, type="dist.neighbours", main = "SOM neighbour distances") ``` ### Response #### Success Response (200) Displays the U-matrix plot. #### Response Example None ``` ```APIDOC ## Add Cluster Boundaries ### Description Adds hierarchical clustering boundaries to a SOM plot based on codebook vectors. ### Method add.cluster.boundaries ### Endpoint N/A (Function call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```R som.hc <- cutree(hclust(object.distances(sommap, "codes")), 5) add.cluster.boundaries(sommap, som.hc) ``` ### Response #### Success Response (200) Modifies the existing plot to include cluster boundaries. #### Response Example None ``` ```APIDOC ## Visualize Changes During Training ### Description Plots the changes in the Kohonen map during the training process. ### Method plot ### Endpoint N/A (Function call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```R plot(kohmap, type="changes") ``` ### Response #### Success Response (200) Displays the training changes plot. #### Response Example None ``` ```APIDOC ## Visualize Unit Counts ### Description Plots the number of data points mapped to each unit in the Kohonen map. ### Method plot ### Endpoint N/A (Function call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```R counts <- plot(kohmap, type="counts", shape = "straight") ``` ### Response #### Success Response (200) Displays the unit counts plot. #### Response Example None ``` -------------------------------- ### Example SOM Grid and Distance Plot Source: https://rwehrens.r-universe.dev/kohonen/doc/manual.html Demonstrates creating a hexagonal SOM grid and plotting unit distances. It shows how to visualize distances to unit 1 for both non-toroidal and toroidal grids. ```R mygrid <- somgrid(5, 5, "hexagonal") fakesom <- list(grid = mygrid) class(fakesom) <- "kohonen" par(mfrow = c(2,1)) dists <- unit.distances(mygrid) plot(fakesom, type="property", property = dists[1,], main="Distances to unit 1", zlim=c(0,6), palette = rainbow, ncolors = 7) dists <- unit.distances(mygrid, toroidal=TRUE) plot(fakesom, type="property", property = dists[1,], main="Distances to unit 1 (toroidal)", zlim=c(0,6), palette = rainbow, ncolors = 7) ``` -------------------------------- ### Visualize Kohonen Map Components Source: https://rwehrens.r-universe.dev/kohonen/doc/manual.html Examples for plotting codebook vectors, mapping quality, and unit mappings for Kohonen maps. ```R par(mfrow = c(1,2)) plot(kohmap, type="codes", main = c("Codes X", "Codes Y")) par(mfrow = c(1,1)) similarities <- plot(kohmap, type="quality", palette.name = terrain.colors) plot(kohmap, type="mapping", labels = as.integer(vintages), col = as.integer(vintages), main = "mapping plot") ## add background colors to units according to their predicted class labels xyfpredictions <- classmat2classvec(getCodes(kohmap, 2)) bgcols <- c("gray", "pink", "lightgreen") plot(kohmap, type="mapping", col = as.integer(vintages), pchs = as.integer(vintages), bgcol = bgcols[as.integer(xyfpredictions)], main = "another mapping plot", shape = "straight", border = NA) ``` -------------------------------- ### Train a SOM and get dimensions of codes Source: https://rwehrens.r-universe.dev/kohonen/doc/manual.html Trains a Self-Organizing Map (SOM) on scaled wine data and retrieves the dimensions of the codebook vectors. This is a basic example of SOM training. ```R data(wines) set.seed(7) som.wines <- som(scale(wines), grid = somgrid(5, 5, "hexagonal")) dim(getCodes(som.wines)) ``` -------------------------------- ### List package help topics Source: https://rwehrens.r-universe.dev/kohonen/doc/manual.html Displays the index of available functions and datasets within the kohonen package. ```text check.whatmap Check the validity of a whatmap argument classvec2classmat Convert a classification vector into a matrix or the other way around. degelder Powder pattern data by Rene de Gelder expandMap Expand a self-organising map getCodes Extract codebook vectors from a kohonen object kohonen-package Supervised and Unsupervised Self-Organising Maps layer.distances Assessing distances to winning units map.kohonen Map data to a supervised or unsupervised SOM nir Near-infrared data with temperature effects object.distances Calculate distances between object vectors in a SOM peppaPic Synthetic image of a pepper plant with peppers plot.kohonen Plot kohonen object predict.kohonen Predict properties using a trained Kohonen map summary.kohonen Summary and print methods for kohonen objects supersom Self- and super-organising maps tricolor Provides smooth unit colors for SOMs unit.distances SOM-grid related functions wines Wine data yeast Yeast cell-cycle data ``` -------------------------------- ### Perform SOM, XYF, and Supersom analysis Source: https://rwehrens.r-universe.dev/kohonen/doc/manual.html Demonstrates training SOM and XYF models on wine data and a Supersom model on yeast data. ```R data(wines) ## som som.wines <- som(scale(wines), grid = somgrid(5, 5, "hexagonal")) summary(som.wines) nunits(som.wines) ## xyf xyf.wines <- xyf(scale(wines), vintages, grid = somgrid(5, 5, "hexagonal")) summary(xyf.wines) ## supersom example data(yeast) yeast.supersom <- supersom(yeast, somgrid(6, 6, "hexagonal"), whatmap = c("alpha", "cdc15", "cdc28", "elu"), maxNA.fraction = .5) plot(yeast.supersom, "changes") 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") ``` -------------------------------- ### Get the Number of Units in a Kohonen Map Source: https://rwehrens.r-universe.dev/kohonen/doc/manual.html The `nunits` function is a utility that returns the total number of units (neurons) present in a trained kohonen map object. ```r nunits(kohobj) ``` -------------------------------- ### Wine Dataset Preparation and Training Source: https://rwehrens.r-universe.dev/kohonen/doc/manual.html Scales the wine dataset and prepares training and test data lists for SOM modeling. ```R data(wines) training <- sample(nrow(wines), 120) Xtraining <- scale(wines[training, ]) Xtest <- scale(wines[-training, ], center = attr(Xtraining, "scaled:center"), scale = attr(Xtraining, "scaled:scale")) trainingdata <- list(measurements = Xtraining, vintages = vintages[training]) testdata <- list(measurements = Xtest, vintages = vintages[-training]) mygrid = somgrid(5, 5, "hexagonal") som.wines <- supersom(trainingdata, grid = mygrid) ``` -------------------------------- ### Create SOM Grid Source: https://rwehrens.r-universe.dev/kohonen/doc/manual.html Initializes a SOM grid with specified dimensions, topology, and neighborhood function. Use for setting up the grid structure before training a SOM. ```R somgrid(xdim = 8, ydim = 6, topo = c("rectangular", "hexagonal"), neighbourhood.fct = c("bubble", "gaussian"), toroidal = FALSE) ``` -------------------------------- ### SOM Algorithm Parameters Source: https://rwehrens.r-universe.dev/kohonen/doc/manual.html This section details the various arguments accepted by the SOM algorithm for training and configuration. ```APIDOC ## SOM Algorithm Parameters ### Description This section details the various arguments accepted by the SOM algorithm for training and configuration. ### Parameters #### Arguments - **X**, **Y** (numerical data matrices or factors) - Required - No `data.frame` objects are allowed - convert them to matrices first. - **data** (list of data matrices or factors) - Required - If a vector is entered, it will be converted to a one-column matrix. No `data.frame` objects are allowed. - **grid** (grid object) - Required - A grid for the codebook vectors; see `somgrid`. - **rlen** (numeric) - Optional - The number of times the complete data set will be presented to the network. - **alpha** (vector of two numbers) - Optional - Learning rate, indicating the amount of change. Default is to decline linearly from 0.05 to 0.01 over `rlen` updates. Not used for the batch algorithm. - **radius** (numeric or vector) - Optional - The radius of the neighbourhood, either given as a single number or a vector (start, stop). If it is given as a single number the radius will change linearly from `radius` to zero; as soon as the neighbourhood gets smaller than one only the winning unit will be updated. Note that the default before version 3.0 was to run from `radius` to `-radius`. If nothing is supplied, the default is to start with a value that covers 2/3 of all unit-to-unit distances. - **whatmap** (data layers) - Optional - What data layers to use. If unspecified all layers are used. - **user.weights** (numeric) - Optional - The weights given to individual layers. This can be a single number, a vector of the same length as `whatmap`, or a vector of the same length as `data`. In xyf maps, this argument provides the same functionality as the now-deprecated `xweight` argument that was used prior to version 3.0. - **maxNA.fraction** (numeric) - Optional - The maximal fraction of values that may be NA to prevent the row to be removed. - **keep.data** (boolean) - Optional - If TRUE, return original data and mapping information. If FALSE, only return the trained map (in essence the codebook vectors). - **dist.fcts** (vector of strings) - Optional - Vector of distance functions to be used for the individual data layers, of the same length as the `data` argument, or the same length of the `whatmap` argument. If the length of this vector is one, the same distance will be used for all layers. Admissible values currently are "sumofsquares", "euclidean", "manhattan", and "tanimoto". Default is to use "sumofsquares" for continuous data, and "tanimoto" for factors. - **mode** (string) - Optional - Type of learning algorithm. - **cores** (numeric) - Optional - Number of cores to use in the "pbatch" learning mode. The default, -1, corresponds to using all available cores. - **init** (list of matrices) - Optional - List of matrices, initial values for the codebook vectors. The list should have the same length as the data list, and corresponding numbers of variables (columns). Each list element should have a number of rows corresponding to the number of units in the map. - **normalizeDataLayers** (boolean) - Optional - Indicating whether `distance.weights` should be calculated. If `normalizeDataLayers == FALSE` the user weights are applied to the data immediately. - **kohobj** (kohonen object) - Optional - An object of class `kohonen`. - **...** (any) - Optional - Further arguments for the `supersom` function presented to the `som` or `xyf` wrappers. ### Details In order to avoid some layers to overwhelm others, simply because of the scale of the data points, the `supersom` function by default applies internal weights to balance this. The `user.weights` argument is applied on top of that: the result is that when a user specifies equal weights for all layers (the default), all layers contribute equally to the global distance measure. For large data sets (defined as containing more than 500 records), a sample of size 500 is used to calculate the mean distances in each data layer. If `normalizeDataLayers == FALSE` the user weights are applied directly to the data (`distance.weights` are set to 1). Various definitions of the Tanimoto distance exist in the literature. The implementation here returns (for two binary vectors of length n) the fraction of cases in which the two vectors disagree. This is basically the Hamming distance divided by n - the incorrect naming is retained (for the moment) to guarantee backwards compatibility. If the vectors are not binary, they will be converted to binary strings (with 0.5 as the class boundary). This measure should not be used when variables are outside the range [0-1]; a check is done to make sure this is the case. ``` -------------------------------- ### Summary and Print Methods for Kohonen Objects Source: https://rwehrens.r-universe.dev/kohonen/doc/manual.html Provides documentation for the `summary` and `print` methods applicable to `kohonen` objects, offering insights into the map's quality and structure. ```APIDOC ## Summary and print methods for kohonen objects ### Description Summary and print methods for `kohonen` objects. The `print` method shows the dimensions and the topology of the map; if information on the training data is included, the `summary` method additionally prints information on the size of the data, the distance functions used, and the mean distance of an object to its closest codebookvector, which is an indication of the quality of the mapping. ### Usage ```R ## S3 method for class 'kohonen' summary(object, ...) ## S3 method for class 'kohonen' print(x, ...) ``` ### Arguments * `x`, `object`: A `kohonen` object. * `...`: Not used. ### Author(s) Ron Wehrens ### See Also `som`, `xyf`, `supersom` ### Examples ```R data(wines) xyf.wines <- xyf(scale(wines), classvec2classmat(vintages), grid = somgrid(5, 5, "hexagonal")) xyf.wines summary(xyf.wines) ``` ``` -------------------------------- ### Perform Supervised SOM Modeling with xyf Source: https://rwehrens.r-universe.dev/kohonen/doc/manual.html Demonstrates training a supervised SOM using the xyf function and visualizing the results with plots and symbols. ```R data(nir) set.seed(3) nirnet <- xyf(X = nir$spectra[nir$training,], Y = nir$composition[nir$training,], user.weights = c(3,1), grid = somgrid(6, 6, "hexagonal"), rlen=500) plot(nirnet, "counts", main="Counts") ## Focus on compound 2 (water): par(mfrow = c(1,2)) set.seed(13) nirnet <- xyf(X = nir$spectra[nir$training,], Y = nir$composition[nir$training, 2, drop = FALSE], grid = somgrid(6, 6, "hexagonal"), rlen=500) water.xyf <- predict(nirnet, newdata = nir$spectra[nir$training,], unit.predictions = getCodes(nirnet, 2), whatmap = 1)$prediction plot(nirnet, "property", property = water.xyf[[1]], main="Prediction of water content") ## Plot temperatures as circles symbols(nirnet$grid$pts[nirnet$unit.classif,] + matrix(rnorm(sum(nir$training)*2, sd=.1), ncol=2), circles = (nir$temperature[nir$training] - 20)/250, inches = FALSE, add = TRUE) ## Model temperatures set.seed(13) nirnet2 <- xyf(X = nir$spectra[nir$training,], Y = matrix(nir$temperature[nir$training], ncol = 1), user.weights = c(1,3), grid = somgrid(6, 6, "hexagonal"), rlen=500) temp.xyf <- predict(nirnet2, newdata = nir$spectra[nir$training,], unit.predictions = getCodes(nirnet2, 2), whatmap = 1)$prediction plot(nirnet2, "property", property = temp.xyf[[1]], palette.name = rainbow, main="Prediction of temperatures") ## Plot concentrations of water as circles symbols(nirnet2$grid$pts[nirnet2$unit.classif,] + matrix(rnorm(sum(nir$training)*2, sd=.1), ncol=2), circles = 0.05 + 0.4 * nir$composition[nir$training,2], inches = FALSE, add = TRUE) ``` -------------------------------- ### Load and Inspect 'peppaPic' Dataset Source: https://rwehrens.r-universe.dev/kohonen/doc/manual.html Loads the 'peppaPic' dataset, which contains image data for a pepper plant. It shows how to view the first few rows and visualize the ground truth per pixel. ```R data(peppaPic) head(peppaPic) ## show ground truth per pixel image(t(matrix(peppaPic[,1], 600, 800))[,600:1], col = rainbow(10)) ``` -------------------------------- ### Create and Analyze SOM with wines dataset Source: https://rwehrens.r-universe.dev/kohonen/doc/manual.html Demonstrates the creation of a Self-Organizing Map (SOM) using the 'supersom' function with the 'wines' dataset. It also shows how to calculate object distances for both data and codebook vectors. ```R data(wines) set.seed(7) sommap <- supersom(list(measurements = scale(wines), vintages = vintages), grid = somgrid(6, 4, "hexagonal")) obj.dists <- object.distances(sommap, type = "data") code.dists <- object.distances(sommap, type = "codes") ``` -------------------------------- ### Generate SOM Component Planes and U-Matrices Source: https://rwehrens.r-universe.dev/kohonen/doc/manual.html Demonstrates creating SOMs with hexagonal or rectangular grids and visualizing property planes and neighbor distances. ```R set.seed(7) sommap <- som(scale(wines), grid = somgrid(6, 4, "hexagonal")) plot(sommap, type = "property", property = getCodes(sommap, 1)[,1], main = colnames(getCodes(sommap, 1))[1]) ## Show the U matrix Umat <- plot(sommap, type="dist.neighbours", main = "SOM neighbour distances") ## use hierarchical clustering to cluster the codebook vectors som.hc <- cutree(hclust(object.distances(sommap, "codes")), 5) add.cluster.boundaries(sommap, som.hc) ## and the same for rectangular maps set.seed(7) sommap <- som(scale(wines),grid = somgrid(6, 4, "rectangular")) plot(sommap, type="dist.neighbours", main = "SOM neighbour distances") ## use hierarchical clustering to cluster the codebook vectors som.hc <- cutree(hclust(object.distances(sommap, "codes")), 5) add.cluster.boundaries(sommap, som.hc) ``` -------------------------------- ### Plotting Kohonen Map Visualizations Source: https://rwehrens.r-universe.dev/kohonen/doc/manual.html Demonstrates basic usage of the plot function on a kohonen object to visualize training changes and unit counts. ```R data(wines) set.seed(7) kohmap <- xyf(scale(wines), vintages, grid = somgrid(5, 5, "hexagonal"), rlen=100) plot(kohmap, type="changes") counts <- plot(kohmap, type="counts", shape = "straight") ``` -------------------------------- ### Prepare Data for SOM Prediction Source: https://rwehrens.r-universe.dev/kohonen/doc/manual.html This code prepares training and testing datasets by sampling, scaling, and structuring them into lists suitable for SOM training and prediction. Ensure data layers match the trained map. ```R data(wines) training <- sample(nrow(wines), 120) Xtraining <- scale(wines[training, ]) Xtest <- scale(wines[-training, ], center = attr(Xtraining, "scaled:center"), scale = attr(Xtraining, "scaled:scale")) trainingdata <- list(measurements = Xtraining, vintages = vintages[training]) testdata <- list(measurements = Xtest, vintages = vintages[-training]) ``` -------------------------------- ### Create a Simple Self-Organizing Map Source: https://rwehrens.r-universe.dev/kohonen/doc/manual.html The `som` function is a wrapper for `supersom` used for creating a SOM with a single data layer. It takes the data matrix `X` as input and accepts additional arguments via `...`. ```r som(X, ...) ``` -------------------------------- ### Supervised Yeast Mapping with supersom Source: https://rwehrens.r-universe.dev/kohonen/doc/manual.html Creates a map based on both alpha and class layers, then predicts class based on the alpha layer mapping. ```R yeast.som2 <- supersom(lapply(yeast, function(x) subset(x, training)), grid = somgrid(4, 6, "hexagonal"), whatmap = c("alpha", "class"), maxNA.fraction = .5) yeast.som2.prediction <- predict(yeast.som2, newdata = lapply(yeast, function(x) subset(x, !training)), whatmap = "alpha") table(yeast$class[!training], yeast.som2.prediction$prediction[["class"]]) ``` -------------------------------- ### Calculate distances to winning units and layer distances Source: https://rwehrens.r-universe.dev/kohonen/doc/manual.html Demonstrates calculating distances of individual objects to their closest SOM units using `dist2WU` and aggregating these distances to the unit level with `layer.distances`. Useful for quality plots. ```R library(kohonen) data(wines) wines.sc <- scale(wines) set.seed(7) xyf.wines <- xyf(wines.sc, vintages, grid = somgrid(5, 5, "hexagonal")) dist2WU(xyf.wines, whatmap = 1) plot(xyf.wines, "quality", whatmap = 1) plot(xyf.wines, "property", property = layer.distances(xyf.wines, whatmap = 1)) ``` -------------------------------- ### Predicting Specific Layers Source: https://rwehrens.r-universe.dev/kohonen/doc/manual.html Demonstrates various ways to predict specific layers, including explicit and implicit mapping. ```R som.prediction <- predict(som.wines, newdata = testdata, whatmap = "measurements") table(vintages[-training], som.prediction$predictions[["vintages"]]) ## same, but now indicated implicitly som.prediction <- predict(som.wines, newdata = testdata[1]) table(vintages[-training], som.prediction$predictions[["vintages"]]) ## if no names are present in the list elements whatmap needs to be ## given explicitly; note that the order of the data layers needs to be ## consistent with the kohonen object som.prediction <- predict(som.wines, newdata = list(Xtest), whatmap = 1) table(vintages[-training], som.prediction$predictions[["vintages"]]) ``` -------------------------------- ### SOM Training and Prediction Source: https://rwehrens.r-universe.dev/kohonen/doc/manual.html Demonstrates the use of the `supersom` function for training a SOM and `predict` for making predictions based on the 'alpha' mapping. ```APIDOC ## SOM Training and Prediction This section illustrates how to train a Self-Organising Map (SOM) using the `supersom` function and then use the trained map to predict values for a specific mapping ('alpha') on new data. ### Usage ```R yeast.som2 <- supersom(lapply(yeast, function(x) subset(x, training)), grid = somgrid(4, 6, "hexagonal"), whatmap = c("alpha", "class"), maxNA.fraction = .5) yeast.som2.prediction <- predict(yeast.som2, newdata = lapply(yeast, function(x) subset(x, !training)), whatmap = "alpha") table(yeast$class[!training], yeast.som2.prediction$prediction[["class"]]) ``` ### Parameters * `yeast`: A list containing yeast data, split into training and non-training sets. * `training`: A logical vector indicating the training subset. * `grid`: A `somgrid` object defining the dimensions and topology of the SOM grid. * `whatmap`: Specifies the mappings to be used for training and prediction. * `maxNA.fraction`: The maximum fraction of NAs allowed in a variable. * `newdata`: New data for prediction. ### Response Example ```R # Example output of the table function # FALSE TRUE # 1 10 2 # 2 5 8 ``` ``` -------------------------------- ### Load Wine Data Source: https://rwehrens.r-universe.dev/kohonen/doc/manual.html Loads the 'wines' dataset, which contains chemical analysis data for three types of Italian wines. ```R data(wines)data(wines) ``` -------------------------------- ### SOM-grid related functions Source: https://rwehrens.r-universe.dev/kohonen/doc/manual.html Functions for setting up and managing SOM grids, including distance calculations between units. ```APIDOC ## SOM-grid related functions ### Description Function `somgrid` (modified from the version in the class package) sets up a grid of units, of a specified size and topology. Distances between grid units are calculated by function `unit.distances`. ``` -------------------------------- ### Load Yeast Cell-Cycle Data Source: https://rwehrens.r-universe.dev/kohonen/doc/manual.html Loads the 'yeast' dataset, containing microarray cell-cycle data for yeast genes. ```R data(yeast)data(yeast) ``` -------------------------------- ### peppaPic Dataset Source: https://rwehrens.r-universe.dev/kohonen/doc/manual.html Accesses the synthetic image data of a pepper plant. ```APIDOC ## peppaPic ### Description A data matrix representing a 600 by 800 image of a pepper plant. Each row is a pixel, with the first column as the class label and subsequent columns as RGB values. ### Usage `data("peppaPic")` ``` -------------------------------- ### Self- and Super-Organising Maps (SOMs) Source: https://rwehrens.r-universe.dev/kohonen/doc/manual.html Documentation for the `som`, `xyf`, and `supersom` functions, which implement Self-Organising Maps and their extensions for multi-layered data. ```APIDOC ## Self- and super-organising maps ### Description A supersom is an extension of self-organising maps (SOMs) to multiple data layers, possibly with different numbers and different types of variables (though equal numbers of objects). NAs are allowed. A weighted distance over all layers is calculated to determine the winning units during training. Functions `som` and `xyf` are simply wrappers for supersoms with one and two layers, respectively. Function `nunits` is a utility function returning the number of units in the map. ### Usage ```R som(X, ...) xyf(X, Y, ...) supersom(data, grid=somgrid(), rlen = 100, alpha = c(0.05, 0.01), radius = quantile(nhbrdist, 2/3), whatmap = NULL, user.weights = 1, maxNA.fraction = 0L, keep.data = TRUE, dist.fcts = NULL, mode = c("online", "batch", "pbatch"), cores = -1, init, normalizeDataLayers = TRUE) nunits(kohobj) ``` ### Arguments * `X`: Data for the SOM. * `Y`: Second data set for `xyf`. * `data`: Data for `supersom`. * `grid`: A `somgrid` object specifying the map topology. * `rlen`: Number of iterations. * `alpha`: Learning rate. * `radius`: Radius for neighborhood function. * `whatmap`: Specifies which data layers to use. * `user.weights`: User-defined weights for data layers. * `maxNA.fraction`: Maximum allowed fraction of NAs. * `keep.data`: Whether to keep the data in the returned object. * `dist.fcts`: Distance functions to use. * `mode`: Training mode ('online', 'batch', 'pbatch'). * `cores`: Number of cores to use for parallel processing. * `init`: Initialization method. * `normalizeDataLayers`: Whether to normalize data layers. * `kohobj`: A `kohonen` object for `nunits`. ### See Also `predict`, `somgrid` ``` -------------------------------- ### Predicting Class based on Alpha Mapping in Supersom Source: https://rwehrens.r-universe.dev/kohonen/doc/manual.html This snippet demonstrates how to use the `predict` method with a supersom object to predict a class based on the 'alpha' mapping. It requires a trained supersom object and new data for prediction. ```r yeast.som2 <- supersom(lapply(yeast, function(x) subset(x, training)), grid = somgrid(4, 6, "hexagonal"), whatmap = c("alpha", "class"), maxNA.fraction = .5) yeast.som2.prediction <- predict(yeast.som2, newdata = lapply(yeast, function(x) subset(x, !training)), whatmap = "alpha") table(yeast$class[!training], yeast.som2.prediction$prediction[["class"]]) ``` -------------------------------- ### Class Vector and Matrix Conversion Source: https://rwehrens.r-universe.dev/kohonen/doc/manual.html Functions to convert between class vectors (factors or integers) and class matrices, with an option to apply a probability threshold. ```APIDOC ## classvec2classmat and classmat2classvec ### Description Functions toggle between a matrix representation, where class membership is indicated with one '1' and for the rest zeros at each row, and a factor. The classification matrix contains one column per class. Conversion from a class matrix to a class vector assigns each row to the column with the highest value. An optional argument can be used to assign only those objects that have a probability higher than a certain threshold (default is 0). ### Arguments `yvec` | class vector. Usually a factor; if it is a vector of integer values, it will be converted to a factor. `ymat` | class matrix: every column corresponds to a class. `threshold` | only classify into a class if the probability is larger than this threshold. ### Value `classvec2classmat` returns the classification matrix, where each column consists of zeros and ones; `classmat2classvec` returns a factor. ### Author(s) Ron Wehrens ### See Also `som`,`xyf`,`supersom` ``` -------------------------------- ### Predict Properties with Kohonen Maps Source: https://rwehrens.r-universe.dev/kohonen/doc/manual.html Syntax for the S3 predict method for kohonen objects. ```R ## S3 method for class 'kohonen' predict(object, newdata = NULL, unit.predictions = NULL, trainingdata = NULL, whatmap = NULL, threshold = 0, maxNA.fraction = object$maxNA.fraction, ...) ``` -------------------------------- ### Near-infrared Data Source: https://rwehrens.r-universe.dev/kohonen/doc/manual.html Description of a dataset containing near-infrared spectra of ternary mixtures measured at different temperatures. ```APIDOC ## Near-infrared data with temperature effects ### Description A data object containing near-infrared spectra of ternary mixtures of ethanol, water and iso-propanol, measured at five different temperatures (30, 40, ..., 70 degrees Centigrade). ### References F. Wulfert , W.Th. Kok, A.K. Smilde: Anal. Chem. 1998, 1761-1767 ``` -------------------------------- ### Train SOM with Grid Source: https://rwehrens.r-universe.dev/kohonen/doc/manual.html Trains a Self-Organizing Map (SOM) using the supersom function with specified training data and a hexagonal grid. The grid defines the topology of the SOM. ```R mygrid = somgrid(5, 5, "hexagonal") som.wines <- supersom(trainingdata, grid = mygrid) ``` -------------------------------- ### Summary Method for Kohonen Objects Source: https://rwehrens.r-universe.dev/kohonen/doc/manual.html The summary method for 'kohonen' objects provides additional details beyond the print method, including data size, distance functions used, and mean distance to codebook vectors, indicating mapping quality. Requires a 'kohonen' object as input. ```r summary(object, ...) ``` -------------------------------- ### Load Powder Pattern Data Source: https://rwehrens.r-universe.dev/kohonen/doc/manual.html Loads the 'degelder' dataset, which contains X-ray powder patterns and associated crystallographic properties. ```R data(degelder)data(degelder) ``` -------------------------------- ### Create a Two-Layered Self-Organizing Map Source: https://rwehrens.r-universe.dev/kohonen/doc/manual.html The `xyf` function is a wrapper for `supersom` designed for creating a SOM with two data layers, `X` and `Y`. It allows for analysis involving two distinct datasets or variable sets. ```r xyf(X, Y, ...) ``` -------------------------------- ### Wine Data Source: https://rwehrens.r-universe.dev/kohonen/doc/manual.html A dataset containing chemical analyses of wines from Italy. ```APIDOC ## Wine Data ### Description A data frame containing 177 rows and thirteen columns; object `vintages` contains the class labels. These data are the results of chemical analyses of wines grown in the same region in Italy (Piedmont) but derived from three different cultivars: Nebbiolo, Barberas and Grignolino grapes. The wine from the Nebbiolo grape is called Barolo. The data contain the quantities of several constituents found in each of the three types of wines, as well as some spectroscopic variables. ### Usage ```R data(wines) ``` ### Source http://kdd.ics.uci.edu ### References M. Forina, C. Armanino, M. Castino and M. Ubigli. Vitis, 25:189-201 (1986) ``` -------------------------------- ### Yeast Cell-Cycle Data Source: https://rwehrens.r-universe.dev/kohonen/doc/manual.html Microarray cell-cycle data for yeast genes. ```APIDOC ## Yeast Cell-Cycle Data ### Description Microarray cell-cycle data for 800 yeast genes, arrested with six different methods, arranged in a list. Additional class information is present as well. ### Usage ```R data(yeast) ``` ### References P. Spellman et al., Mol. Biol. Cell 9, 3273-3297 (1998) ``` -------------------------------- ### Stack trace for data.table error Source: https://rwehrens.r-universe.dev/kohonen/data/yeast The stack trace generated by the webR worker during the fwrite failure. ```text Error: Error in `data.table::fwrite(df, output)`: Column 3's length (14400) is not the same as column 1's length (1600) at js (/cranlike/node_modules/@r-universe/webr/dist/webr-worker.js:13:628) at Dr (/cranlike/node_modules/@r-universe/webr/dist/webr-worker.js:20:103) at un.od (/cranlike/node_modules/@r-universe/webr/dist/webr-worker.js:2:95286) at un.inputOrDispatch (/cranlike/node_modules/@r-universe/webr/dist/webr-worker.js:2:30402) at Object.readConsole (/cranlike/node_modules/@r-universe/webr/dist/webr-worker.js:21:1293) at 15866123 (/cranlike/node_modules/@r-universe/webr/dist/R.js:1634:513018) at runEmAsmFunction (/cranlike/node_modules/@r-universe/webr/dist/R.js:1634:220900) at _emscripten_asm_const_int (/cranlike/node_modules/@r-universe/webr/dist/R.js:1634:220963) at wasm://wasm/052ddb6a:wasm-function[2966]:0x419444 at wasm://wasm/052ddb6a:wasm-function[2995]:0x41adf7 ``` -------------------------------- ### Predict with xyf Model Source: https://rwehrens.r-universe.dev/kohonen/doc/manual.html Trains an xyf model and then predicts using a specific layer ('measurements') for mapping. This shows prediction for a different SOM type (xyf) and how to access predictions by index. ```R xyf.wines <- xyf(Xtraining, vintages[training], grid = mygrid) xyf.prediction <- predict(xyf.wines, Xtest, whatmap = 1) table(vintages[-training], xyf.prediction$predictions[[2]]) ```