Skip to content

Instantly share code, notes, and snippets.

@Pyknic
Created September 6, 2018 15:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Pyknic/a53d7289ec84eb3c54474f4fb5ce10d4 to your computer and use it in GitHub Desktop.
Save Pyknic/a53d7289ec84eb3c54474f4fb5ce10d4 to your computer and use it in GitHub Desktop.
MatLab function for correcting errors in input matrices using Hopfield Networks
# hopfield(input, patterns)
#
# Usage Example:
# hopfield([0 0 0;0 0 0;1 1 1], {[1 1 1;0 0 0;0 0 0],[0 0 1;0 0 1; 1 1 1]})
# ans =
# 0 0 1
# 0 0 1
# 1 1 1
#
# Arguments:
# input: square matrix of 0s and 1s
# patterns: cell-array of square matrices with patterns to learn
#
function s = hopfield(input, patterns)
threshold = 1;
p = length(patterns); # The number of patterns
# Preprocess the patterns
for k = 1:p
pattern = patterns{k};
pattern(pattern==0)=-1; # Replace 0 with -1
patterns{k} = pattern(:); # Turn matrix into bit vector
clear pattern
end
n = length(patterns{1}); # The number of bits (same for all patterns)
w = zeros(n); # Weights: n-by-n matrix filled by zeroes
# The diagonal is always zero, so nothing to do.
# The upper half triangle is computes using Hebb's Rule.
for i = 1:n
if i < n
for j = i+1:n
for k = 1:p
w(i,j) += patterns{k}(i)*patterns{k}(j);
end
w(i,j) /= p;
end
end
end
# The bottom half triangle is copied from the upper half.
for i = 1:n
for j = 1:i
w(i,j) = w(j,i);
end
end
# Run updates
s = input;
for t = 1:10
s2 = s;
for i = 1:n
sum = 0;
for j = 1:n
sum += w(i,j)*s(j);
end
if sum >= threshold
s2(i) = 1;
else
s2(i) = -1;
end
end
s = s2;
end
# Replace -1 with 0
s(s==-1)=0;
s = reshape(s, [sqrt(n),sqrt(n)]);
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment