Bin will be removed on June 1, 2014 in favor of http://gist.github.com. Please save all your pastes before then. So long, and thanks for all the fish!×
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
namespace artificialneuralnetwork
{
  public class HopfieldNetwork
  {
    public HopfieldNetwork ()
    {
    }
 
    public HopfieldNetwork (int size)
    {
      this.WeightMatrix = new Matrix(size, size);
    }
 
    public Matrix LayerMatrix
    {
      get
      {
        return this.WeightMatrix;
      }
    }
 
    public int Size
    {
      get
      {
        return this.WeightMatrix.Rows;
      }
    }
 
    private Matrix WeightMatrix;
 
    public bool [] Present(bool [] pattern)
    {
      bool [] output = new bool [pattern.Length];
      Matrix inputMatrix =
        Matrix.CreateRowMatrix(BiPolarUtil.Bipolar2double(pattern));
 
      for (int col = 0; col < pattern.Length; col++)
      {
        Matrix columnMatrix = this.WeightMatrix.GetCol(col);
        columnMatrix = MatrixMath.Transpose(ref columnMatrix);
 
        double dotProduct = MatrixMath.DotProduct(ref inputMatrix,
          ref columnMatrix);
 
        if (dotProduct > 0)
        {
          output[col] = true;
        }
        else
        {
          output[col] = false;
        }
      }
 
      return output;
    }
 
    public void Train(bool [] pattern)
    {
      if (pattern.Length != this.WeightMatrix.Rows)
      {
        throw new System.Exception("Can't train a pattern of size \""
          + pattern.Length + "\" on a hopfield network of size \""
          + this.WeightMatrix.Rows + "\".");
      }
 
      Matrix m2 = Matrix.CreateRowMatrix(BiPolarUtil.Bipolar2double(pattern));
 
      Matrix m1 = MatrixMath.Transpose(ref m2);
      Matrix m3 = MatrixMath.Multiply(ref m1, ref m2);
 
      Matrix identity = MatrixMath.Identity(m3.Rows);
 
      Matrix m4 = MatrixMath.Subtract(ref m3, ref identity);
 
      this.WeightMatrix = MatrixMath.Add (ref this.WeightMatrix, ref m4);
    }
  }
}