Difference between revisions of "User:Chase-san/KohonenMap"

From Robowiki
Jump to navigation Jump to search
m (license)
m (minor update)
Line 3: Line 3:
  
 
This and all my other code in which I display on the robowiki falls under the [http://en.wikipedia.org/wiki/Zlib_License ZLIB License].
 
This and all my other code in which I display on the robowiki falls under the [http://en.wikipedia.org/wiki/Zlib_License ZLIB License].
 
===org.csdgn.nn.SOM===
 
<syntaxhighlight>
 
package org.csdgn.nn;
 
 
import java.util.Arrays;
 
import java.util.Random;
 
 
import org.csdgn.nn.density.StandardDensity;
 
import org.csdgn.nn.distance.EulerDistanceSquared;
 
import org.csdgn.utils.VDA;
 
 
/**
 
* An Optimized Self-Organizing Map implementation.
 
* This makes use of the VDA class.
 
*
 
* @author Chase
 
*
 
*/
 
public class SOM {
 
private static final double cutoff = 1.0e-4;
 
private final VDA<double[]> vda;
 
private final int inputSize;
 
private DensityFunction density = new StandardDensity();
 
private DistanceFunction distance = new EulerDistanceSquared();
 
private boolean wrap = false;
 
private double learningRate = 0.8;
 
private int[] BMU;
 
 
/**
 
* @param mapSize
 
*            Size of the neighborhood. Example: {10,10} produces a 2
 
*            dimensional map, each dimension having 10 nodes. Total nodes
 
*            would be 100.
 
* @param input
 
*            The length of the input vector (2D only)
 
* @param output
 
*            The length of the output vector (2D only)
 
*/
 
public SOM(int[] mapSize, int input, int output) {
 
this.vda = new VDA<double[]>(mapSize);
 
this.inputSize = input;
 
Object[] obj = vda.getBackingArray();
 
for(int i = 0; i < obj.length; ++i) {
 
obj[i] = new double[input + output];
 
}
 
}
 
 
/**
 
* Initializes the map to random values
 
*/
 
public final void initialize() {
 
Random r = new Random();
 
initialize(r);
 
}
 
 
/**
 
* Initializes the map with the given random function. Uses the nextDouble
 
* function.
 
*/
 
public final void initialize(Random random) {
 
Object[] tmp = vda.getBackingArray();
 
for(Object o : tmp) {
 
double[] tmp2 = (double[])o;
 
for(int i = 0; i < tmp2.length; ++i) {
 
tmp2[i] = random.nextDouble();
 
}
 
}
 
}
 
 
/**
 
* Initializes the map nodes to the given values.
 
*/
 
public final void initialize(double[] in, double[] out) {
 
Object[] tmp = vda.getBackingArray();
 
for(Object o : tmp) {
 
double[] array = (double[])o;
 
for(int i = 0; i < array.length; ++i) {
 
if(i < inputSize) {
 
array[i] = in[i];
 
} else {
 
array[i] = out[i - inputSize];
 
}
 
}
 
}
 
}
 
 
/**
 
* Initializes the map nodes to the given values.
 
*/
 
public final void initialize(Random input, double[] out) {
 
Object[] tmp = vda.getBackingArray();
 
for(Object o : tmp) {
 
double[] array = (double[])o;
 
for(int i = 0; i < array.length; ++i) {
 
if(i < inputSize) {
 
array[i] = input.nextDouble();
 
} else {
 
array[i] = out[i - inputSize];
 
}
 
}
 
}
 
}
 
 
/**
 
* Finds the Best Matching Unit for the given input.
 
*/
 
public final void findBMInput(double[] input) {
 
if(input.length != inputSize)
 
return;
 
 
double bestDistance = Double.MAX_VALUE;
 
Object[] backArray = vda.getBackingArray();
 
int[] size = vda.getSize();
 
int[] pos = new int[size.length];
 
for(Object o : backArray) {
 
double[] array = (double[])o;
 
double dist = distance.calculate(array, input);
 
if(dist < bestDistance) {
 
bestDistance = dist;
 
BMU = pos.clone();
 
}
 
next(pos, size);
 
}
 
 
// return BMU;
 
// return BMU.clone();
 
}
 
 
/**
 
* Finds the Worst Matching Unit for the given input.
 
*/
 
public final void findWMInput(double[] input) {
 
if(input.length != inputSize)
 
return;
 
 
double worstDistance = Double.MIN_VALUE;
 
Object[] backArray = vda.getBackingArray();
 
int[] size = vda.getSize();
 
int[] pos = new int[size.length];
 
for(Object o : backArray) {
 
double[] array = (double[])o;
 
double dist = distance.calculate(array, input);
 
if(dist > worstDistance) {
 
worstDistance = dist;
 
BMU = pos.clone();
 
}
 
next(pos, size);
 
}
 
}
 
 
public final void setMatchingIndex(int... index) {
 
if(index.length != vda.getSize().length)
 
throw new IllegalArgumentException("Incorrect or Bad Dimensionality.");
 
BMU = index.clone();
 
}
 
 
/**
 
* This returns the input of the last found BMU or WMU.
 
*
 
* @return the input vector
 
*/
 
public final double[] getInput() {
 
if(BMU == null)
 
throw new UnsupportedOperationException("BMU/WMU must be found first.");
 
return Arrays.copyOf(vda.get(BMU), inputSize);
 
}
 
 
/**
 
* This returns the output of the last found BMU or WMU.
 
*
 
* @return the output vector
 
*/
 
public final double[] getOutput() {
 
if(BMU == null)
 
throw new UnsupportedOperationException("BMU/WMU must be found first.");
 
double[] bmu = vda.get(BMU);
 
double[] output = new double[bmu.length - inputSize];
 
System.arraycopy(bmu, inputSize, output, 0, bmu.length - inputSize);
 
return output;
 
}
 
 
/**
 
* Sets the learning rate of this KohonenMap
 
*
 
* @param rate
 
*            value between 0 and 1
 
*/
 
public final void setLearningRate(double rate) {
 
learningRate = Math.max(Math.min(rate, 1), 0);
 
}
 
 
/**
 
* Returns the current rate of learning
 
*
 
* @return the learning rate
 
*/
 
public final double getLearningRate() {
 
return learningRate;
 
}
 
 
/**
 
* Sets the map to wrap its updates (slightly more costly)
 
*/
 
public final void setWraps(boolean n) {
 
wrap = n;
 
}
 
 
/**
 
* Returns if the current map wraps
 
*
 
* @return
 
*/
 
public final boolean isWrapping() {
 
return wrap;
 
}
 
 
/**
 
* Sets the density function this map uses for updating nearby nodes. If
 
* unset it uses the StandardDensity class.
 
*
 
* @param func
 
*            the Density Function
 
*/
 
public final void setDensityFunction(DensityFunction func) {
 
this.density = func;
 
}
 
 
/**
 
* Sets the distance function used to find the best or worst matching unit.
 
* If not set, the map uses the EulerDistanceSquared class.<br>
 
* The neighborhood distance is Manhattan Distance.
 
*
 
* @param func
 
*/
 
public final void setDistanceFunction(DistanceFunction func) {
 
this.distance = func;
 
}
 
 
/**
 
* Updates the map with the given data. Uses the last found BMU or WMU.
 
*
 
* @param input
 
*            input vector
 
* @param output
 
*            expected output vector
 
*/
 
public final void train(double input[], double output[]) {
 
if(BMU == null)
 
throw new UnsupportedOperationException("BMU/WMU must be found first.");
 
 
Object[] backArray = vda.getBackingArray();
 
int[] size = vda.getSize();
 
int[] pos = new int[size.length];
 
 
for(Object o : backArray) {
 
double[] array = (double[])o;
 
double distance = neighborhood(pos, BMU);
 
 
if(wrap) {
 
int[] tpos = pos.clone();
 
int[] npos = BMU.clone();
 
for(int i = 0; i < tpos.length; ++i) {
 
tpos[i] += size[i] / 2;
 
npos[i] += size[i] / 2;
 
if(tpos[i] > size[i])
 
tpos[i] -= size[i];
 
if(npos[i] > size[i])
 
npos[i] -= size[i];
 
}
 
double ndist = neighborhood(tpos, npos);
 
if(ndist < distance)
 
distance = ndist;
 
}
 
 
double neighborhood = density.calculate(distance) * learningRate;
 
 
/* Changes below this point benefits are negligible */
 
if(neighborhood < cutoff) {
 
next(pos, size);
 
continue;
 
}
 
 
for(int i = 0; i < array.length; ++i) {
 
if(i < inputSize) {
 
array[i] = weight(array[i], input[i], neighborhood);
 
} else {
 
array[i] = weight(array[i], output[i - inputSize], neighborhood);
 
}
 
}
 
 
next(pos, size);
 
}
 
}
 
 
private static final double neighborhood(int[] p, int[] q) {
 
if(p == null || q == null)
 
return 0;
 
int len = Math.min(p.length, q.length);
 
int output = 0;
 
for(int i = 0; i < len; ++i)
 
output += Math.abs(p[i] - q[i]);
 
return output;
 
}
 
 
private final double weight(double c, double t, double n) {
 
return c + n * (t - c);
 
}
 
 
private static final void next(int[] pos, int[] size) {
 
++pos[pos.length - 1];
 
for(int i = pos.length - 1; i > 0; --i) {
 
if(pos[i] >= size[i]) {
 
++pos[i - 1];
 
pos[i] = 0;
 
}
 
}
 
}
 
}
 
</syntaxhighlight>
 
  
 
===org.csdgn.nn.KohonenMap===
 
===org.csdgn.nn.KohonenMap===
Line 329: Line 9:
  
 
import java.util.Random;
 
import java.util.Random;
import org.csdgn.nn.density.StandardDensity;
+
import org.csdgn.nn.distance.EulerDistanceSquared;
 
 
 
 
/**
 
/**
 
  * A Self-Organizing Map implementation.
 
  * A Self-Organizing Map implementation.
Line 348: Line 26:
 
public class KohonenMap {
 
public class KohonenMap {
 
private static final double cutoff = 1e-4;
 
private static final double cutoff = 1e-4;
+
 
/**
 
/**
 
* Holds the neighborhood layout;
 
* Holds the neighborhood layout;
 
*/
 
*/
public final Node[] map;
+
private final Node[] map;
public final int[] mapSize;
+
private final int[] mapSize;
public double learningRate = 0.8;
+
private double learningRate = 0.8;
private DensityFunction density;
+
private Density density;
private DistanceFunction distance;
+
private Distance distance;
 
private boolean wrap = false;
 
private boolean wrap = false;
 
private int BMU;
 
private int BMU;
+
 
/**
 
/**
 
* @param mapSize Size of the neighborhood. Example: {10,10} produces a 2 dimensional  
 
* @param mapSize Size of the neighborhood. Example: {10,10} produces a 2 dimensional  
Line 371: Line 49:
 
for(int m : mapSize) size *= m;
 
for(int m : mapSize) size *= m;
 
this.map = new Node[size];
 
this.map = new Node[size];
+
 
this.mapSize = mapSize.clone();
 
this.mapSize = mapSize.clone();
+
this.density = new StandardDensity();
+
this.density = new Density.Simple();
this.distance = new EulerDistanceSquared();
+
this.distance = new Distance.EulerSq();
+
 
int[] pos = new int[mapSize.length];
 
int[] pos = new int[mapSize.length];
 
for(int i=0; i<map.length; ++i) {
 
for(int i=0; i<map.length; ++i) {
Line 382: Line 60:
 
/* Setup the location of each node, for speed reasons. */
 
/* Setup the location of each node, for speed reasons. */
 
System.arraycopy(pos, 0, this.map[i].position, 0, pos.length);
 
System.arraycopy(pos, 0, this.map[i].position, 0, pos.length);
+
 
/* Update the position marker */
 
/* Update the position marker */
 
++pos[0];
 
++pos[0];
Line 393: Line 71:
 
}
 
}
 
}
 
}
+
 
/**
 
/**
 
* Initializes the map to random values
 
* Initializes the map to random values
Line 401: Line 79:
 
initialize(r);
 
initialize(r);
 
}
 
}
+
 
/**
 
/**
 
* Initializes the map with the given random function.
 
* Initializes the map with the given random function.
Line 414: Line 92:
 
}
 
}
 
}
 
}
+
 
/**
 
/**
 
* Finds the Best Matching Unit for the given input.
 
* Finds the Best Matching Unit for the given input.
 
* @return the BMUs identifier
 
* @return the BMUs identifier
 
*/
 
*/
public final int findBMInput(double[] input) {
+
public final int findInputBMU(double[] input) {
 
BMU = 0;
 
BMU = 0;
+
 
double distance = Double.MAX_VALUE;
 
double distance = Double.MAX_VALUE;
 
for(int i=0; i<map.length; ++i) {
 
for(int i=0; i<map.length; ++i) {
double dist = this.distance.calculate(map[i].input, input);
+
double dist = this.distance.distance(map[i].input, input);
+
 
if(dist < distance) {
 
if(dist < distance) {
 
distance = dist;
 
distance = dist;
Line 433: Line 111:
 
return BMU;
 
return BMU;
 
}
 
}
+
 
/**
 
/**
 
* Finds the Best Matching Unit for the given output.
 
* Finds the Best Matching Unit for the given output.
 
* @return the BMUs identifier
 
* @return the BMUs identifier
 
*/
 
*/
public final int findBMOutput(double[] output) {
+
public final int findOutputBMU(double[] output) {
 
BMU = 0;
 
BMU = 0;
 
double distance = Double.MAX_VALUE;
 
double distance = Double.MAX_VALUE;
 
for(int i=0; i<map.length; ++i) {
 
for(int i=0; i<map.length; ++i) {
double dist = this.distance.calculate(map[i].output, output);
+
double dist = this.distance.distance(map[i].output, output);
 
if(dist < distance) {
 
if(dist < distance) {
 
distance = dist;
 
distance = dist;
Line 450: Line 128:
 
return BMU;
 
return BMU;
 
}
 
}
+
 
/**
 
/**
 
* Finds the Worst Matching Unit for the given input
 
* Finds the Worst Matching Unit for the given input
 
* @return the WMUs identifier
 
* @return the WMUs identifier
 
*/
 
*/
public final int findWMInput(double[] input) {
+
public final int findInputWMU(double[] input) {
 
BMU = 0;
 
BMU = 0;
 
double distance = Double.MIN_VALUE;
 
double distance = Double.MIN_VALUE;
 
for(int i=0; i<map.length; ++i) {
 
for(int i=0; i<map.length; ++i) {
double dist = this.distance.calculate(map[i].input, input);
+
double dist = this.distance.distance(map[i].input, input);
 
if(dist > distance) {
 
if(dist > distance) {
 
distance = dist;
 
distance = dist;
Line 467: Line 145:
 
return BMU;
 
return BMU;
 
}
 
}
+
 
/**
 
/**
 
* Finds the Worst Matching Unit for the given output
 
* Finds the Worst Matching Unit for the given output
 
* @return the WMUs identifier
 
* @return the WMUs identifier
 
*/
 
*/
public final int findWMOutput(double[] output) {
+
public final int findOutputWMU(double[] output) {
 
BMU = 0;
 
BMU = 0;
 
double distance = Double.MIN_VALUE;
 
double distance = Double.MIN_VALUE;
 
for(int i=0; i<map.length; ++i) {
 
for(int i=0; i<map.length; ++i) {
double dist = this.distance.calculate(map[i].output, output);
+
double dist = this.distance.distance(map[i].output, output);
 
if(dist > distance) {
 
if(dist > distance) {
 
distance = dist;
 
distance = dist;
Line 484: Line 162:
 
return BMU;
 
return BMU;
 
}
 
}
+
 
/**
 
/**
 
* Sets the Matched index to the set value.
 
* Sets the Matched index to the set value.
Line 492: Line 170:
 
BMU = Math.max(0,Math.min(index, map.length-1));
 
BMU = Math.max(0,Math.min(index, map.length-1));
 
}
 
}
+
 
/**
 
/**
 
* This returns the input of the last found BMU or WMU.
 
* This returns the input of the last found BMU or WMU.
Line 500: Line 178:
 
return this.map[BMU].input;
 
return this.map[BMU].input;
 
}
 
}
+
 
/**
 
/**
 
* This returns the output of the last found BMU or WMU.
 
* This returns the output of the last found BMU or WMU.
Line 508: Line 186:
 
return this.map[BMU].output;
 
return this.map[BMU].output;
 
}
 
}
+
 
/**
 
/**
 
* This returns the input of the given ID.
 
* This returns the input of the given ID.
Line 518: Line 196:
 
return new double[0];
 
return new double[0];
 
}
 
}
+
 
/**
 
/**
 
* This returns the output of the given ID.
 
* This returns the output of the given ID.
Line 528: Line 206:
 
return new double[0];
 
return new double[0];
 
}
 
}
+
 
/**
 
/**
 
* Sets the learning rate of this KohonenMap
 
* Sets the learning rate of this KohonenMap
Line 536: Line 214:
 
learningRate = Math.max(Math.min(rate, 1),0);
 
learningRate = Math.max(Math.min(rate, 1),0);
 
}
 
}
+
 
/**
 
/**
 
* Returns the current rate of learning
 
* Returns the current rate of learning
Line 544: Line 222:
 
return learningRate;
 
return learningRate;
 
}
 
}
+
 
/**
 
/**
 
* Sets the map to wrap its updates (slightly more costly)
 
* Sets the map to wrap its updates (slightly more costly)
Line 551: Line 229:
 
wrap = n;
 
wrap = n;
 
}
 
}
+
 
/**
 
/**
 
* Returns if the current map wraps
 
* Returns if the current map wraps
Line 559: Line 237:
 
return wrap;
 
return wrap;
 
}
 
}
+
 
/**
 
/**
 
* Sets the density function this map uses for updating nearby nodes.
 
* Sets the density function this map uses for updating nearby nodes.
Line 565: Line 243:
 
* @param func the Density Function
 
* @param func the Density Function
 
*/
 
*/
public final void setDensityFunction(DensityFunction func) {
+
public final void setDensityFunction(Density func) {
 
this.density = func;
 
this.density = func;
 
}
 
}
+
 
/**
 
/**
 
* Sets the distance function used to find the best or worst matching unit.
 
* Sets the distance function used to find the best or worst matching unit.
Line 575: Line 253:
 
* @param func
 
* @param func
 
*/
 
*/
public final void setDistanceFunction(DistanceFunction func) {
+
public final void setDistanceFunction(Distance func) {
 
this.distance = func;
 
this.distance = func;
 
}
 
}
+
 
/**
 
/**
 
* Updates the map with the given data. Uses the last found
 
* Updates the map with the given data. Uses the last found
Line 591: Line 269:
 
}
 
}
 
}
 
}
+
 
/**
 
/**
 
* This uses Manhattan Distance.
 
* This uses Manhattan Distance.
Line 603: Line 281:
 
return output;  
 
return output;  
 
}
 
}
+
 
private final class Node {
 
private final class Node {
 
/** Location in the neighborhood */
 
/** Location in the neighborhood */
Line 611: Line 289:
 
/** Output vector */
 
/** Output vector */
 
private final double[] output;
 
private final double[] output;
+
 
public Node(int mapSize, int inputSize, int outputSize) {
 
public Node(int mapSize, int inputSize, int outputSize) {
 
position = new int[mapSize];
 
position = new int[mapSize];
Line 617: Line 295:
 
output = new double[outputSize];
 
output = new double[outputSize];
 
}
 
}
+
 
private final double weight(double c, double t, double n) {
 
private final double weight(double c, double t, double n) {
 
return c + n * (t - c) * learningRate;
 
return c + n * (t - c) * learningRate;
 
}
 
}
+
 
private final void update(int[] pos, double[] in, double[] out) {
 
private final void update(int[] pos, double[] in, double[] out) {
 
double distance = neighborhood(pos,position);
 
double distance = neighborhood(pos,position);
Line 636: Line 314:
 
if(ndist < distance) distance = ndist;
 
if(ndist < distance) distance = ndist;
 
}
 
}
+
double neighborhood = density.calculate(distance);
+
double neighborhood = density.density(distance);
+
 
/* Changes below this point benefits are negligible */
 
/* Changes below this point benefits are negligible */
 
if(neighborhood < cutoff) return;
 
if(neighborhood < cutoff) return;
+
 
for(int i=0; i<input.length; ++i)
 
for(int i=0; i<input.length; ++i)
 
input[i] = weight(input[i], in[i], neighborhood);
 
input[i] = weight(input[i], in[i], neighborhood);
+
 
for(int i=0; i<output.length; ++i)
 
for(int i=0; i<output.length; ++i)
 
output[i] = weight(output[i], out[i], neighborhood);
 
output[i] = weight(output[i], out[i], neighborhood);
 
}
 
}
+
 
}
 
}
 
}
 
}
 
</syntaxhighlight>
 
</syntaxhighlight>
  
 
+
===org.csdgn.nn.Density===
===org.csdgn.nn.DensityFunction===
 
 
<syntaxhighlight>
 
<syntaxhighlight>
 
package org.csdgn.nn;
 
package org.csdgn.nn;
  
public interface DensityFunction {
+
public abstract class Density {
 
/**
 
/**
 
* Calculates the density at the given point, where x is a certain distance from the center of the distribution.
 
* Calculates the density at the given point, where x is a certain distance from the center of the distribution.
 
*/
 
*/
public double calculate(double x);
+
public abstract double density(double x);
}
+
</syntaxhighlight>
+
public static class Normal extends Density {
===org.csdgn.nn.DistanceFunction===
+
private final double multi;
<syntaxhighlight>
+
private final double variance;
package org.csdgn.nn;
+
private final double mean;
 
+
public Normal() {
/**
+
this(1,0);
* A function for determining the distance between two double arrays.
+
}
* @author Chase
+
public Normal(double variance, double mean) {
*/
+
this.multi = 1.0 / Math.sqrt(2*Math.PI*variance);
public interface DistanceFunction {
+
this.variance = variance;
public double calculate(double[] p, double[] q);
+
this.mean = mean;
}
+
}
</syntaxhighlight>
+
@Override
===org.csdgn.nn.density.StandardDensity===
+
public double density(double x) {
<syntaxhighlight>
+
double e = ((x - mean)*(x - mean)) / (2*variance);
package org.csdgn.nn.density;
+
return multi*Math.exp(-e);
 
+
}
import org.csdgn.nn.DensityFunction;
 
 
 
/**
 
* <math>density(x) = 2^{-x^2}</math>
 
*/
 
public final class StandardDensity implements DensityFunction {
 
/**
 
* <math>density(x) = 2^{-x^2}</math>
 
*/
 
@Override
 
public double calculate(double x) {
 
return Math.pow(2, -(x*x));
 
 
}
 
}
}
 
</syntaxhighlight>
 
===org.csdgn.nn.density.NormalDistribution===
 
<syntaxhighlight>
 
package org.csdgn.nn.density;
 
 
import org.csdgn.nn.DensityFunction;
 
 
public final class NormalDistribution implements DensityFunction {
 
private final double multi;
 
private final double variance;
 
private final double mean;
 
 
 
public NormalDistribution() {
+
public static class Simple extends Density {
this(1,0);
+
/**
 +
* <math>density(x) = 2^{-x^2}</math>
 +
*/
 +
@Override
 +
public double density(double x) {
 +
return Math.pow(2, -(x*x));
 +
}
 
}
 
}
public NormalDistribution(double variance, double mean) {
 
this.multi = 1.0 / Math.sqrt(2*Math.PI*variance);
 
this.variance = variance;
 
this.mean = mean;
 
}
 
@Override
 
public double calculate(double x) {
 
double e = ((x - mean)*(x - mean)) / (2*variance);
 
return multi*Math.exp(-e);
 
}
 
 
 
}
 
}
 
</syntaxhighlight>
 
</syntaxhighlight>
===org.csdgn.nn.distance.EulerDistanceSquared===
+
 
 +
===org.csdgn.nn.Distance===
 
<syntaxhighlight>
 
<syntaxhighlight>
package org.csdgn.nn.distance;
+
package org.csdgn.nn;
  
import org.csdgn.nn.DistanceFunction;
+
public abstract class Distance {
 +
public abstract double distance(double[] p, double[] q);
  
public class EulerDistanceSquared implements DistanceFunction {
+
public static class EulerSq extends Distance {
/**
+
/**
* <math>distSqr(p,q) = \sum_{i=0}^n (p_i - q_i)^2</math> where <math>n</math> is the
+
* <math>distSqr(p,q) = \sum_{i=0}^n (p_i - q_i)^2</math> where
* size of the smaller of <math>p</math> or <math>q</math>
+
* <math>n</math> is the size of the smaller of <math>p</math> or
*/
+
* <math>q</math>
@Override
+
*/
public final double calculate(double[] p, double[] q) {
+
@Override
if(p == null || q == null) return 0;
+
public double distance(double[] p, double[] q) {
int len = Math.min(p.length, q.length);
+
if (p == null || q == null)
double k,output = 0;
+
return 0;
for(int i=0; i<len; ++i)
+
int len = Math.min(p.length, q.length);
output += (k=(p[i] - q[i]))*k;
+
double k, output = 0;
return output;
+
for (int i = 0; i < len; ++i)
 +
output += (k = (p[i] - q[i])) * k;
 +
return output;
 +
}
 
}
 
}
  
 +
public static class Euler extends EulerSq {
 +
/**
 +
* <math>dist(p,q) = \sqrt_{\sum_{i=0}^n (p_i - q_i)^2}</math> where
 +
* <math>n</math> is the size of the smaller of <math>p</math> or
 +
* <math>q</math>
 +
*/
 +
@Override
 +
public double distance(double[] p, double[] q) {
 +
return Math.sqrt(super.distance(p, q));
 +
}
 +
}
 
}
 
}
 
</syntaxhighlight>
 
</syntaxhighlight>

Revision as of 02:35, 30 March 2012

This is my implementation of a Self-organizing map. It is untested, but it should work just fine.

This and all my other code in which I display on the robowiki falls under the ZLIB License.

org.csdgn.nn.KohonenMap

package org.csdgn.nn;

import java.util.Random;
 
/**
 * A Self-Organizing Map implementation.
 * 
 * Requires: <br>
 * org.csdgn.nn.DensityFunction<br>
 * org.csdgn.nn.DistanceFunction<br>
 * org.csdgn.nn.density.StandardDensity<br>
 * org.csdgn.nn.distance.EulerDistanceSquared
 * 
 * TODO: Optimize for speed.
 * 
 * @author Chase
 *
 */
public class KohonenMap {
	private static final double cutoff = 1e-4;
 
	/**
	 * Holds the neighborhood layout;
	 */
	private final Node[] map;
	private final int[] mapSize;
	private double learningRate = 0.8;
	private Density density;
	private Distance distance;
	private boolean wrap = false;
	private int BMU;
 
	/**
	 * @param mapSize Size of the neighborhood. Example: {10,10} produces a 2 dimensional 
	 * map, each dimension having 10 nodes. Total nodes would be 100.
	 * @param input The length of the input vector (2D only)
	 * @param output The length of the output vector (2D only)
	 */
	public KohonenMap(int[] mapSize, int input, int output) {
		/* Setup the map */
		int size = 1;
		for(int m : mapSize) size *= m;
		this.map = new Node[size];
 
		this.mapSize = mapSize.clone();
 
		this.density = new Density.Simple();
		this.distance = new Distance.EulerSq();
 
		int[] pos = new int[mapSize.length];
		for(int i=0; i<map.length; ++i) {
			this.map[i] = new Node(mapSize.length,input,output);
			/* Setup the location of each node, for speed reasons. */
			System.arraycopy(pos, 0, this.map[i].position, 0, pos.length);
 
			/* Update the position marker */
			++pos[0];
			for(int j=0;j<pos.length-1;++j) {
				if(pos[j] >= mapSize[j]) {
					++pos[j+1];
					pos[j] = 0;
				}
			}
		}
	}
 
	/**
	 * Initializes the map to random values
	 */
	public final void initialize() {
		Random r = new Random();
		initialize(r);
	}
 
	/**
	 * Initializes the map with the given random function.
	 * Uses the nextDouble function.
	 */
	public final void initialize(Random random) {
		for(Node n : map) {
			for(int i = 0; i < n.input.length; ++i)
				n.input[i] = random.nextDouble();
			for(int i = 0; i < n.output.length; ++i)
				n.output[i] = random.nextDouble(); 
		}
	}
 
	/**
	 * Finds the Best Matching Unit for the given input.
	 * @return the BMUs identifier
	 */
	public final int findInputBMU(double[] input) {
		BMU = 0;
 
		double distance = Double.MAX_VALUE;
		for(int i=0; i<map.length; ++i) {
			double dist = this.distance.distance(map[i].input, input);
 
			if(dist < distance) {
				distance = dist;
				BMU = i;
			}
		}
		return BMU;
	}
 
	/**
	 * Finds the Best Matching Unit for the given output.
	 * @return the BMUs identifier
	 */
	public final int findOutputBMU(double[] output) {
		BMU = 0;
		double distance = Double.MAX_VALUE;
		for(int i=0; i<map.length; ++i) {
			double dist = this.distance.distance(map[i].output, output);
			if(dist < distance) {
				distance = dist;
				BMU = i;
			}
		}
		return BMU;
	}
 
	/**
	 * Finds the Worst Matching Unit for the given input
	 * @return the WMUs identifier
	 */
	public final int findInputWMU(double[] input) {
		BMU = 0;
		double distance = Double.MIN_VALUE;
		for(int i=0; i<map.length; ++i) {
			double dist = this.distance.distance(map[i].input, input);
			if(dist > distance) {
				distance = dist;
				BMU = i;
			}
		}
		return BMU;
	}
 
	/**
	 * Finds the Worst Matching Unit for the given output
	 * @return the WMUs identifier
	 */
	public final int findOutputWMU(double[] output) {
		BMU = 0;
		double distance = Double.MIN_VALUE;
		for(int i=0; i<map.length; ++i) {
			double dist = this.distance.distance(map[i].output, output);
			if(dist > distance) {
				distance = dist;
				BMU = i;
			}
		}
		return BMU;
	}
 
	/**
	 * Sets the Matched index to the set value.
	 * @param index
	 */
	public final void setMatchIndex(int index) {
		BMU = Math.max(0,Math.min(index, map.length-1));
	}
 
	/**
	 * This returns the input of the last found BMU or WMU.
	 * @return the input vector
	 */
	public final double[] getInput() {
		return this.map[BMU].input;
	}
 
	/**
	 * This returns the output of the last found BMU or WMU.
	 * @return the output vector
	 */
	public final double[] getOutput() {
		return this.map[BMU].output;
	}
 
	/**
	 * This returns the input of the given ID.
	 * @return the input vector
	 */
	public final double[] getInput(int id) {
		if(id > 0 && id < map.length)
			return this.map[id].input;
		return new double[0];
	}
 
	/**
	 * This returns the output of the given ID.
	 * @return the output vector
	 */
	public final double[] getOutput(int id) {
		if(id > 0 && id < map.length)
			return this.map[id].output;
		return new double[0];
	}
 
	/**
	 * Sets the learning rate of this KohonenMap
	 * @param rate value between 0 and 1
	 */
	public final void setLearningRate(double rate) {
		learningRate = Math.max(Math.min(rate, 1),0);
	}
 
	/**
	 * Returns the current rate of learning
	 * @return the learning rate 
	 */
	public final double getLearningRate() {
		return learningRate;
	}
 
	/**
	 * Sets the map to wrap its updates (slightly more costly)
	 */
	public final void setWraps(boolean n) {
		wrap = n;
	}
 
	/**
	 * Returns if the current map wraps
	 * @return
	 */
	public final boolean isWrapping() {
		return wrap;
	}
 
	/**
	 * Sets the density function this map uses for updating nearby nodes.
	 * If unset it uses the StandardDensity class.
	 * @param func the Density Function
	 */
	public final void setDensityFunction(Density func) {
		this.density = func;
	}
 
	/**
	 * Sets the distance function used to find the best or worst matching unit.
	 * If unset, this map uses the EulerDistanceSquared class.<br>
	 * The neighborhood distance is Manhattan Distance.
	 * @param func
	 */
	public final void setDistanceFunction(Distance func) {
		this.distance = func;
	}
 
	/**
	 * Updates the map with the given data. Uses the last found
	 * BMU or WMU.
	 * @param input input vector
	 * @param output expected output vector
	 */
	public final void train(double input[], double output[]) {
		Node bmu = map[BMU];
		for(int i=0; i<map.length; ++i) {
			map[i].update(bmu.position, input, output);
		}
	}
 
	/**
	 * This uses Manhattan Distance.
	 */
	private static final double neighborhood(int[] p, int[] q) {
		if(p == null || q == null) return 0;
		int len = Math.min(p.length, q.length);
		int output = 0;
		for(int i=0; i<len; ++i)
			output += Math.abs(p[i] - q[i]);
		return output; 
	}
 
	private final class Node {
		/** Location in the neighborhood */
		private final int[] position;
		/** Input vector */
		private final double[] input;
		/** Output vector */
		private final double[] output;
 
		public Node(int mapSize, int inputSize, int outputSize) {
			position = new int[mapSize];
			input = new double[inputSize];
			output = new double[outputSize];
		}
 
		private final double weight(double c, double t, double n) {
			return c + n * (t - c) * learningRate;
		}
 
		private final void update(int[] pos, double[] in, double[] out) {
			double distance = neighborhood(pos,position);
			if(wrap) {
				int[] tpos = pos.clone();
				int[] npos = position.clone();
				for(int i=0; i<tpos.length; ++i) {
					tpos[i] += mapSize[i]/2;
					npos[i] += mapSize[i]/2;
					if(tpos[i] > mapSize[i]) tpos[i] -= mapSize[i];
					if(npos[i] > mapSize[i]) npos[i] -= mapSize[i];
				}
				double ndist = neighborhood(tpos,npos);
				if(ndist < distance) distance = ndist;
			}
 
			double neighborhood = density.density(distance);
 
			/* Changes below this point benefits are negligible */
			if(neighborhood < cutoff) return;
 
			for(int i=0; i<input.length; ++i)
				input[i] = weight(input[i], in[i], neighborhood);
 
			for(int i=0; i<output.length; ++i)
				output[i] = weight(output[i], out[i], neighborhood);
		}
 
	}
}

org.csdgn.nn.Density

package org.csdgn.nn;

public abstract class Density {
	/**
	 * Calculates the density at the given point, where x is a certain distance from the center of the distribution.
	 */
	public abstract double density(double x);
	
	public static class Normal extends Density {
		private final double multi;
		private final double variance;
		private final double mean;
		public Normal() {
			this(1,0);
		}
		public Normal(double variance, double mean) {
			this.multi = 1.0 / Math.sqrt(2*Math.PI*variance);
			this.variance = variance;
			this.mean = mean;
		}
		@Override
		public double density(double x) {
			double e = ((x - mean)*(x - mean)) / (2*variance);
			return multi*Math.exp(-e);
		}
	}
	
	public static class Simple extends Density {
		/**
		 * <math>density(x) = 2^{-x^2}</math>
		 */
		@Override
		public double density(double x) {
			return Math.pow(2, -(x*x));
		}
	}
}

org.csdgn.nn.Distance

package org.csdgn.nn;

public abstract class Distance {
	public abstract double distance(double[] p, double[] q);

	public static class EulerSq extends Distance {
		/**
		 * <math>distSqr(p,q) = \sum_{i=0}^n (p_i - q_i)^2</math> where
		 * <math>n</math> is the size of the smaller of <math>p</math> or
		 * <math>q</math>
		 */
		@Override
		public double distance(double[] p, double[] q) {
			if (p == null || q == null)
				return 0;
			int len = Math.min(p.length, q.length);
			double k, output = 0;
			for (int i = 0; i < len; ++i)
				output += (k = (p[i] - q[i])) * k;
			return output;
		}
	}

	public static class Euler extends EulerSq {
		/**
		 * <math>dist(p,q) = \sqrt_{\sum_{i=0}^n (p_i - q_i)^2}</math> where
		 * <math>n</math> is the size of the smaller of <math>p</math> or
		 * <math>q</math>
		 */
		@Override
		public double distance(double[] p, double[] q) {
			return Math.sqrt(super.distance(p, q));
		}
	}
}