Click here to Skip to main content
Click here to Skip to main content

Hopfield model of neural network for pattern recognition

By , 6 Nov 2006
 

Hopfield Neural Network demo project Hopfield Neural Network demo project

Glossary

  • (A)NN - (Artificial) Neural Network
  • HNN - Hopfield neural networkBackground (optional)

Introduction

The article describes the Hopfield model of neural network. The theory basics, algorithm and program code are provided. The ability of application of Hopfield neural network to pattern recognition problem is shown.

Opening

Here I will not talk about NNs in whole. The main goal of this article is to describe architecture and dynamics of Hopfield Neural network. The base concept of NN, like artificial neurons, synapses, weights, connection matrices and so on, are explained in countless books. If you want to know more about these things, I advise you to start with Simon Haykin “Neural networks” book. The Google search is also useful. And finally you can try out very good article of Anoop Madhusudanan’s, here on CodeProject.

Hopfield neural network (a little bit of theory)

In ANN theory, in most simple case (when threshold functions is equal to one) the Hopfield model is described  as a one-dimensional system of N neurons – spins (si = ± 1, i = 1,2,…,N) that can be oriented along or against the local field. The behavior of such spin system is described by Hamiltonian (also known as the energy of HNN):

Where si is the state of the ith spin and

is an interconnection matrix organized according to the Hebb rule on M randomized patterns, i.e., on N-dimensional binary vectors Sm=(sm1,sm2,… smN) (m=1,2,…M). The diagonal elements of interconnection matrix are assumed to be zero (Ti,i=0). The traditional approach to such a system is that all spins are assumed to be free and their dynamics are defined only by the action of a local field, along which they are oriented. The algorithm of functioning of HNN is described as follows. The initial spin directions (neuron states) are oriented according the components of input vector.     The local field , which acts on the ith spin at time t (this field is produced by all the remaining spins of NN) is calculated as:

The spin energy in this field is . If the spin direction coincides with the direction of the local field (), its position is energetically stable and the spin state remains unchanged at the next time step. Otherwise (), the spin position is unstable, and the local field overturns it, passing spin into the state si(t+1)=-si(t) with the energy (). The energy of the NN is reduced reducing each time any spin flips; i.e., the NN achieves a stable state in a finite number of steps. At some precise conditions each stable states corresponds to one of patterns added to interconnection matrix.

The same in other words

So, digressing from math, let’s consider HNN from the practical point of view. Suppose you have M, N-dimensional binary vectors (fig. 3), and you want to store them in neural network.

 

Fig. 3. The set of binary patterns

In this case, you have to add them into the interconnection matrix, using simple summing (fig. 4).

 

Fig. 4. The formation of the interconnection matrix

Now the network is ready to work. You must set some initial state of NN and run dynamical procedure. The properties of HNN is such that during dynamics it passes into the some stable state which corresponds to the one of the patterns. And NN will pass in that pattern, which is most like the initial state of HNN.

Playing with demo

To see how it works in practice, run demo project (HopfieldRecognizer.exe).

  1. In the main window press "Create Neural Network (100 Neurons)" button. The neural network will be created.
  2. Then press "Add pattern to Neural Network" button and select any 10x10 image (you can find some in ABC folder). Add for example 3 patterns which correspond to A, B and C images.
  3. Select one of the added patterns (for example A) by clicking on it and define the value of initial distortion level in percents (you can leave it equals to 10%).
  4. Press "Run network dynamics" button. And here it is :)

Diving into the code

Let's consider the object model of neural network. It consists of two main classes: Neuron and NeuralNetwork. Neuron is a base class, which contains State property and ChangeState() method. State is an Int32 number, but actually it takes only two values: +1 or -1 (These values are also accessible from static class NeuronStates. Where NeorunStates.AlongField is equal to 1 and NeorunStates.AgainstField is equal to -1). ChangeState() receives value of field acting on the neuron and makes decision, either to change own state or not. ChangeState() returns true if State was changed.

    public class Neuron
    {
        private int state;
        public int State
        {
            get { return state; }
            set { state = value;}
        }
        
        public Neuron()
        {
            int r = new Random().Next(2);
            switch (r)
            {
                case 0: state = NeuronStates.AlongField; break;
                case 1: state = NeuronStates.AgainstField; break;
            }                
        }
       
        public bool ChangeState(Double field)
        {
            bool res = false;
            if (field * this.State < 0)
            {
                this.state = -this.state;
                res = true;
            }
            return res;
        }
    }  

NeuralNetwork class contains the typed list of the neurons, methods for add patterns and run dynamics:

public List<Neuron> Neurons;
public void AddPattern(List<Neuron> Pattern)
public void Run(List<Neuron> initialState)

The class constructor initializes all fields, creates lists and arrays and fills the interconnection matrix with zeros:

        public NeuralNetwork(int n)
        {
            this.n = n;
            neurons = new List<Neuron>(n);
            for (int i = 0; i< n; i++)
            {
                Neuron neuron = new Neuron();
                neuron.State = 0;
                neurons.Add(neuron);
            }

            T = new int[n, n];
            m = 0;

            for (int i = 0; i < n; i++)
                for (int j = 0; j < n; j++)
                {
                    T[i, j] = 0;
                }
        }

The AddPattern() and AddRandomPattern() adds specified (or randomly generated) pattern into interconnection matrix:

 public void AddPattern(List<Neuron> Pattern)
        {
            for (int i = 0; i < n; i++)
                for (int j = 0; j < n; j++)
                {
                    if (i == j) T[i, j] = 0;
                    else T[i, j] += (Pattern[i].State * Pattern[j].State);
                }
            m++;
        }

The Run() method, runs dynamics of HNN:

        public void Run(List<Neuron> initialState)
        {
            this.neurons = initialState;
            int k = 1;
            int h = 0;
                while(k != 0)
                {
                    k = 0;
                    for (int i = 0; i < n; i++)
                    {
                        h = 0;
                        for (int j = 0; j < n; j++)                        
                          h += T[i, j] * (neurons[j].State);
                      
                        if (neurons[i].ChangeState(h))
                        {
                            k++;
                            CalculateEnergy();
                            OnEnergyChanged(new EnergyEventArgs(e,i));
                        }
                    }
                }
                CalculateEnergy();             
        }

Every time when any spin changes its state, the energy of system changes and NN raises EnergyChanged event. This event allows to subscribers to track the NN state in time.

Using the code

To use this code in your project, you have to add reference to HopfieldNeuralNetwork.dll. Then you need to create an instance of the NeuralNetwork class, and subscribe to EnergyChanged event (optional):

NeuralNetwork NN = new NeuralNetwork(100);
NN.EnergyChanged += new EnergyChangedHandler(NN_EnergyChanged);
private void NN_EnergyChanged(object sender, EnergyEventArgs e)
{
  //...
}

After that, you need to add some patterns to the interconnection matrix.

List<Neuron> pattern = new List<Neuron>(100);
//... some pattern forming code goes 
NN.AddPattern(pattern);

And finally, you can run the dynamics of the network:

List<Neuron> initialState = new List<Neuron>(100);
//... some initialState forming code goes
NN.Run(initialState);

Last word

The HNN was proposed in 1982, and it is not the best solution for pattern recognition problem. It is very sensible for correlations between patterns. If you’ll try to add some very similar patterns to matrix (for example B and C from (ABC folder), they are flows together and form new pattern called chimera. It is also sensible for number of patterns stored in the interconnection matrix. It couldn’t be more than 10-14% from number of neurons. In spite of such disadvantages the HNN and its modern modifications is simple and popular algorithms.

License

This article, along with any associated source code and files, is licensed under The GNU General Public License (GPLv3)

About the Author

Bashir Magomedov
Software Developer (Senior)
United Kingdom United Kingdom
Member
Work: HSBC (http://www.hsbc.co.uk/).
Regalia: PhD in CS, MCAD, MCPD: Web Developer, MCTS: .Net Framework 2.0., 3.5.
Interests: Programming, artificial intelligence, C#, .NET, HTML5, ASP.NET, SQL, LINQ.
Marital Status: Married, daughter
Blog: http://www.magomedov.co.uk

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 5mvpKanasz Robert6 Nov '12 - 0:01 
very good article and well explained. good job bashir
GeneralHow do I change to recognize binary pattern?membershamlen6 Jun '11 - 13:56 
Hi,
 
Thanks for the posting. I am a newbie to AI world. I would like to understand, how could I change your algorithm to recognize binary pattern. For example,
 
I may have set of data as below
 
Day | Data
--- | ----
1 | 101010
2 | 110011
3 | 101110
4 | 011010
5 | 001100
 
I would like to predict the data for day 6. I have 1000 set of historical data. Please advice if this is achievable using your algorithm. I would appreciate if you could direct me to the right path.
 
Thanks
 
-Balan Sinniah-
Balan

GeneralMy vote of 5memberFilip D'haene26 May '11 - 4:39 
Excellent article!
 
Thanks for sharing. Smile | :)
GeneralHopfield NN for pattern recognition in visual prologmemberngelina15 Nov '10 - 23:02 
hi..
i wan to disscusss about hopfield NN for pattern recog in vis-pro.
can u give me advice about the algorithm?
thx Smile | :)
QuestionYou asked me about the procedure NN_EnergyChanged()memberphamvanloi_nd30 Mar '10 - 23:05 
Hi!
You asked me about the procedure NN_EnergyChanged(object sender, EnergyEventArgs e)
 
Why in the procedure CreateNNBut_Click(object sender, EventArgs e)you call procedure NN_EnergyChanged.
 
NN.EnergyChanged += new EnergyChangedHandler(NN_EnergyChanged);
 
I do not really understand this function.
 
Hope you can explain techniques are not for me!
 
thank you very much.
 
wish you a happy day! OMG | :OMG:
GeneralYou asked me about the procedure NN_EnergyChanged(object sender, EnergyEventArgs e)memberphamvanloi_nd30 Mar '10 - 23:03 
Hi!
You asked me about the procedure NN_EnergyChanged(object sender, EnergyEventArgs e)
 
Why in the procedure CreateNNBut_Click(object sender, EventArgs e)you call procedure NN_EnergyChanged.
 
NN.EnergyChanged += new EnergyChangedHandler(NN_EnergyChanged);
 
I do not really understand this function.
 
Hope you can explain techniques are not for me!
 
thank you very much.
 
wish you a happy day! OMG | :OMG:
GeneralNeural networkmemberSajanakiSasiri7 Dec '09 - 19:06 
How can i design a neural network for image recognition with mathLab?
What is the neural network technology?
QuestionAssociation Between Input and Reference PatternsmemberJackEMoore8 Nov '09 - 11:40 
In the example with patterns A, B, C, what is a good algorithm way to associate the result after the NN has acheived a stable state with the particular reference pattern?
GeneralQuestionmembersandreli20 Jun '09 - 0:23 
Can you please show the method CalculateEnergy
GeneralRe: QuestionmemberBashir Magomedov20 Jun '09 - 0:38 
What do you mean by show? You can see it in the code. Just download it. Please do not hesitate to ask if you need some details ot explanation about this method.
QuestionQuestionmemberdennykidz717 Jun '09 - 21:18 
What the Neuron Index..For what?
AnswerRe: QuestionmemberBashir Magomedov17 Jun '09 - 21:27 
Have you meant something certain by index? If not I can answer in general. To iterate trough all the neurons of system and either change the state of particular neuron or remain it unchanged.
 
Everything is possible!

GeneralAbout Hopfield Neural network Source codemembermonisha10129 Jul '08 - 23:58 
I find out the code for Hopfield neural network from ur site....its demo working fine...but i need this code in C language instead of C++ language [D'Oh!]
GeneralAskmemberamal_kh2 Jul '08 - 21:00 
Can i ask you how did you use neural network in your project, i mean what was the input layer,hiddden layer, the function that you used and the output layer?
GeneralRe: AskmemberBashir Magomedov2 Jul '08 - 21:14 
The deal is that this is not a multi-layer perceptron (as you might thought), but Hopfiled neural network (HNN). This is a special kind of neural network for pattern recognition and it doesn't have any layers. In general case each neuron of HNN has activation function but here (for the simplicity) it was reduced to bipolar function when each neuron can be either + or - 1.
 
Please read the article carefully, all these points were stated in it, and do not hesitate to contact me in future if you need help.
 
Everything is possible!

GeneralHopfieldNeuralNetwork_demo is not workingmembermohammadnassif16 May '08 - 8:00 
pleas help me i download the project and try to run
from this icon : HopfieldRecognizer.exe
but the project dont run and return this message:
The application failed to initialize properly(0xc0000135).Click on ok to terminate the application.
 
pleas help me and tell me whats i can do.
 
thanks
GeneralRe: HopfieldNeuralNetwork_demo is not workingmemberBashir Magomedov16 May '08 - 19:12 
It seems that you do not have .NET Framework installed on your machine. Please install .NET 2.0 (or later) Framework and try again.Cool | :cool:
 
Everything is possible!

Generalpleas help mememberyasamin4 Apr '08 - 20:43 
hi
I'm yasamina
Ihave aproject in nural network Iwant to make astndared or model back propagation network but Idont have any idea how i can do this if any one have a code or idea pleas giv it to me
thank you
Generalhimemberlulukuku27 Nov '07 - 5:16 
thank you very much,i saw it.Smile | :)
QuestionQuestion!!memberlulukuku25 Nov '07 - 22:44 
in the program of you,i don't see method you create neural's images(about 100 neuron)! you can explain for me!!!D'Oh! | :doh: thanks you very much.
AnswerRe: Question!!memberBashir Magomedov25 Nov '07 - 22:51 
Roll eyes | :rolleyes:
Here is requested code. This method is an event handler of "Create neural network (100 Neurons)" button. You can find it in the frmMain class (MainForm.cs file).
 

private void CreateNNBut_Click(object sender, EventArgs e)
{
NN = new NeuralNetwork(imageDim*imageDim);
panelStoredImages.Controls.Clear();
NN.EnergyChanged += new EnergyChangedHandler(NN_EnergyChanged);
Random rnd = new Random();
int r = 0;
imNNState.pixels = new int[imageDim, imageDim];
for (int i = 0; i < imageDim; i++)
for (int j = 0; j < imageDim; j++)
{
r = rnd.Next(2);
if (r == 0) imNNState.pixels[i, j] = Color.Black.ToArgb();
else if (r == 1) imNNState.pixels[i, j] = Color.White.ToArgb();
}
patternSelected = false;
butAddPattern.Enabled = true;
butRunDynamics.Enabled = false;
imNNState.Visible = true;
imNNState.Invalidate();
UpdatePropertiesPB();
}

 
Thank you for your attention

QuestionERROR!!!memberlulukuku24 Nov '07 - 20:52 
i meet ERROR "Warning 1 Could not find type 'ImageMagnifier.ImageMagnifier'. Please make sure that the assembly that contains this type is referenced. If this type is a part of your development project, make sure that the project has been successfully built. 0 0
" and "Warning 2 The variable 'imNNState' is either undeclared or was never assigned. C:\Documents and Settings\Administrator\Desktop\HopfieldRecognizer\MainForm.Designer.cs 175 0
"
You can hepl me solve problems !!!D'Oh! | :doh:
where do i find "'ImageMagnifier.ImageMagnifier'" ?
Thanks you very much!!Smile | :)
AnswerRe: ERROR!!!memberBashir Magomedov24 Nov '07 - 23:18 
Dear lulukuku!
This class (ImageMagnifier) is needed only for demo-project and located in the root folder of the project. It is possible that references are out of date, so you should remove reference from project and add it again by yourself.
If you are looking for the source-codes of this control, you can try out following link:
http://www.codeproject.com/cs/miscctrl/ImageMagnifier.asp[^]
 
Sincerely yours, Bashir

Generalhelp me!memberlulukuku23 Nov '07 - 5:46 
please,help me!i need informaiton for hopfield model of neural network for pattern recognition. you can send me all code "Hopfield model of neural network for pattern recognition ".thanks you very much!!Confused | :confused:
GeneralRe: help me!memberBashir Magomedov24 Nov '07 - 23:11 
Dear lulukuku!
You can find a lot information on the subject in the Internet. Basically, you can look through the reference section of current article. All source codes and demo-application are avaliable from this site. Please do not histance to contact me any time in future.
Sincerely yours, Bashir.
 
Thank you for your attention

QuestionLicense numbermemberGrimmsimon23 Jan '07 - 2:45 
Hello to everyone,
 
can I use this sample to create a program,
I want to load a picture in this porgram and this program scan the picture and write if there is a License number in a textbox or something else?
 
Greetz Simon
 
Sorry for my very bad english
AnswerRe: License numbermemberpeter.modzelewski23 Jan '07 - 6:47 
emm what textbox
textbox on the picture?
 
D programmer

AnswerRe: License numbermemberBashir Magomedov4 Feb '07 - 22:41 
I soupose that it will be problematic...
Hopfield like neural networks are very sensible to rotation/stretching kind's of distortions. So you have to be very carefull whaen scanning images, but it is very dificult to do. To use HNN, first you need to preprocess acquied image to get invariant representetion for rotations and stretching (for instance using wavelet analysys) and then try to store and recognize this representation using HNN.

 

 
Thank you for your attention

Generalhimemberpeter.modzelewski17 Jan '07 - 23:26 
some things here are like a bit strange
i's working but
doing random state in neuron constructor and then making it zerio is a bit silly don't you think?;)
you also don't seam to use threshold array despite mantioning it
run and addPattern are a bit like annoing, it could be just an array of short/int values. and this same as output, it woul make it more usefull
on some parameters -1/1 values are worse then 0/1.. it would be nice to make it configurable Wink | ;)
 
anyway you're programm helped me a lot Wink | ;) so i guess writing what i needed to change would be fair Wink | ;)
 
D programmer

GeneralRe: himemberBashir Magomedov4 Feb '07 - 22:46 
You are right...
Here is considered the most simple kind of HNN, without thresholds and with only bipolar inputs (1;-1), coresponding to first Hopfiled's work (1982).
I'll consider the other modifications of HNN, I hope, in the nearest future.
Thank you for your comment.
 
Thank you for your attention

QuestionOCRmemberdavidbeseke14 Nov '06 - 1:53 
I would like to try to use your example to build an OCR engine. Do you know of any good articles / C# examples for segmenting and cleaning scanned images?
AnswerRe: OCRmemberBashir Magomedov14 Nov '06 - 21:23 
The Hopfield model is not actually oriented for OCR systems. Why? Because it has a lot of disadvantages such as small memory capacity and high percent of recognition error. Especially they appears when image is handwritten.
Actually, this question lies out of my knowledge, so I can't give any
references to you Sigh | :sigh: . But you can try to search on Amazon.
 
http://www.amazon.com/s/ref=nb_ss_gw/104-4072748-7898361?url=search-alias%3Dstripbooks&field-keywords=OCR&Go.x=14&Go.y=6;P

 
Thank you for your attention

GeneralWorks OK NowmemberRB Starkey23 Oct '06 - 5:30 
Many thanks for the magnifyer dll - works wonderfully - nice example.
Thanks again
Ray Starkey
 
Ray Starkey
ACCESSible IT Limited
Coventry, UK

QuestionImageMagnifiermemberRB Starkey16 Oct '06 - 21:18 
I can't compile because this component is missing - can you tell me where to find it please.
 
Thanks
 
Ray Starkey
ACCESSible IT Limited
Coventry, UK

AnswerRe: ImageMagnifiermemberBashir Magomedov16 Oct '06 - 22:03 
Hmmm, strange. It should be in HopfieldRecognizer\bin\Debug\ folder...
Ok, I have already uploaded new version, in which all required assembles are in the project’s root folder. So you can remove references (if needed) and add new by hand. Cool | :cool:

 
Thank you for your attention

GeneralRe: ImageMagnifiermemberCBrauer17 Oct '06 - 12:28 
It is true that ImageMagnifier.dll is in the bin\Debug folder.
I guess we are asking for the source.
 
Charles
GeneralRe: ImageMagnifiermemberBashir Magomedov17 Oct '06 - 19:56 
Oh, in such way it is not a problem. The ImageMagnifier control with sources is available at http://www.codeproject.com/cs/miscctrl/ImageMagnifier.asp[^]
 
Thank you for your attention

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web01 | 2.6.130523.1 | Last Updated 7 Nov 2006
Article Copyright 2006 by Bashir Magomedov
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid