Example #1
0
def hopfield_learn_view(request):
    schema = SchemaHopfieldLearn()
    myform = Form(schema, buttons=('submit',))
    js_tags, css_tags = get_resources(request, myform)
    result = {'title': u"Hopfield učenje", "js_tags": js_tags,
              "css_tags": css_tags, "hopfield_learn": True}
    appstruct = {
        'vhod': [[0, 0, 1, 1],
                 [0, 1, 0, 1]]
    }
    if 'submit' in request.POST:
        controls = request.POST.items()
        try:
            appstruct = myform.validate(controls)
            #print appstruct
            nn = Hopfield(text_output=[])
            nn.learn(appstruct['vhod'])
            result["text_izhod"] = nn.text_output
            #print appstruct
        except ValidationFailure, e:
            result['form'] = e.render()
            return result
        except Exception, e:
            #print e
            request.ext.flash_error(unicode(e), title="Napaka pri podatkih")
            result["form"] = myform.render(appstruct=appstruct)
            return result
Example #2
0
def hopfield_energy_view(request):
    schema = SchemaHopfieldEnergy()
    myform = Form(schema, buttons=('submit',))
    js_tags, css_tags = get_resources(request, myform)
    result = {'title': u"Hopfield računanje energije", "js_tags": js_tags,
              "css_tags": css_tags, "hopfield_energy": True}
    appstruct = {
        'vhod': [[1, 1, -1, -1]],
        'utez': [[0, 1, 0, -2],
                 [1, 0, -2, 0],
                 [0, -2, 0, -3],
                 [-2, 0, -3, 0]]
    }
    if 'submit' in request.POST:
        controls = request.POST.items()
        try:
            appstruct = myform.validate(controls)
            #print appstruct
            nn = Hopfield(text_output=[])
            nn.weight_matrix = appstruct['utez']
            #nn.calc_energy(appstruct['vhod'], appstruct['multiply'])
            nn.calc_energy(appstruct['vhod'])
            result["text_izhod"] = nn.text_output
            #print appstruct
        except ValidationFailure, e:
            result['form'] = e.render()
            return result
        except Exception, e:
            #print e
            request.ext.flash_error(unicode(e), title="Napaka pri podatkih")
            result["form"] = myform.render(appstruct=appstruct)
            return result
def fit_hopfield(params):
    # get params
    n_label = params.get('n_label', None)
    n_sample = params['n_sample']
    fit_mode = params['fit_mode']

    # load dataset
    dataset = load_alphabet()

    # target_name
    target_names = params.get('target_names', None)
    if target_names is None:
        target_names = dataset.target_names[:n_label]

    # transform data
    dataset.data = binarize(dataset.data, binary_values=(-1,1))

    # create train data
    X, y = create_train_data(data=dataset.data,
                             target=dataset.target,
                             target_names=target_names,
                             n_sample=n_sample)
    print_train_data(X, y, target_names)

    # fit hopfield
    hf = Hopfield(mode=fit_mode)
    hf.fit(X, y, watch_weight=False)

    # set params
    params['img_shape'] = dataset.image_shape

    return hf, X, y, target_names, params
Example #4
0
def for_test(train_matrixs, output_dir, noise_max, noise_step):
    sim = []
    acc = []
    for noise in range(5, noise_max + 1, noise_step):
        sim_sub = []
        acc_sub = []
        print("noise {}%".format(noise))
        #各条件に対して10回試行して平均をとる
        for _ in range(0, 10):
            test_matrix = add_noise(train_matrixs[0], noise)
            hop = Hopfield(train_matrixs, test_matrix, max_time=100)
            output = hop.predict()
            print("check")
            simularity = evaluate_sim(train_matrixs, output)
            accurate = evaluate_acc(train_matrixs, output)
            print("accurate: ", accurate, " simularity: ", simularity)
            sim_sub.append(simularity)
            acc_sub.append(accurate)
        sim.append(np.mean(np.array(sim_sub)))
        acc.append(np.mean(np.array(acc_sub)))
        #最後の1回を図示
        print("show")
        os.makedirs(output_dir, exist_ok=True)
        show_result(train_matrixs, test_matrix, output,
                    output_dir + "/" + str(noise) + ".png")
    print(sim)
    print(acc)
    return sim, acc
Example #5
0
def hopfield_view(request):
    schema = SchemaHopfield()
    myform = Form(schema, buttons=('submit',))
    js_tags, css_tags = get_resources(request, myform)
    result = {'title': u"Hopfield", "js_tags": js_tags,
              "css_tags": css_tags, "hopfield": True}
    appstruct = {
        'utez': [[0, 1, -1],
                 [1, 0, 1],
                 [-1, 1, 0]]
    }
    if 'submit' in request.POST:
        controls = request.POST.items()
        try:
            appstruct = myform.validate(controls)
            #print appstruct
            nn = Hopfield(appstruct['function_type'], text_output=[])
            nn.weight_matrix = appstruct['utez']
            nn.get_stable_states()
            result["tabela"] = nn.table
            result["text_izhod"] = nn.text_output
            #print appstruct
        except ValidationFailure, e:
            result['form'] = e.render()
            return result
        except Exception, e:
            #print e
            request.ext.flash_error(unicode(e), title="Napaka pri podatkih")
            result["form"] = myform.render(appstruct=appstruct)
            return result
Example #6
0
def main():
    n = 4
    hyperparameter = 0.1
    c = Cities(n)
    h = Hopfield(c.c, hyperparameter)
    #h.go_to_minimum()
    #h.plot_energy()
    h.show_shortest_route()
Example #7
0
def main():
    text = t.poemToProse(t.getText('texts/wiki1.txt'))
    words = t.textToWords(text)
    # print(len(words))
    uniq = frequencyVector(m.getNouns(words))
    print(uniq[0], uniq[1])
    matrix = matchMatrix(uniq[0], t.textToSenteces(text))
    #print(np.linalg.det(matrix))
    # print(np.linalg.svd(matrix)[2][8])
    # print(matrix[2].sum())
    #print(np.linalg.det(matrix_shit))
    # print(np.linalg.det(matrix - np.identity(matrix.shape[0])))
    # print(np.linalg.eigvals(matrix_shit))
    hopfield = Hopfield(matrix, uniq[1])
    hopfield.train()

    # print(hopfield.result)

    print(showResults(hopfield.result, uniq[0]))
Example #8
0
yesNo = str(raw_input())
view = False
if yesNo == 'Y' or yesNo == 'y':
	view = True

userInput = userInput.replace(" ", "")

fileList = userInput.split(",")

patterns = []

for image in fileList:
    array = convert_image(image)
    patterns.append(array)

hop = Hopfield()

hop.memorize_patterns(patterns, view = view)

print("Training complete. Do you want to see the weight matrices? [Y/N]")
yesNo = str(raw_input())
if yesNo == 'Y' or yesNo == 'y':
    hop.show_patterns()

print("Stating restoration...")

corruptedImage = convert_image('corrupted.png')
originalCorr = corruptedImage
newImage = hop.update(corruptedImage)

i = 0
Example #9
0
File: main.py Project: dajuda/USP
#Converte valores de 0-1 para -1 a 1
def fix_values(pattern):
    pattern = pattern * 2
    pattern = pattern - 1
    return pattern


#Exibe uma janela contendo a imagem do padrão
def display(pattern, nameFile):
    plt.imshow(pattern, cmap=plt.cm.binary, interpolation='nearest')
    plt.savefig(nameFile)


if __name__ == '__main__':

    hop = Hopfield()

    #Le arquivos de treinamento e teste
    train_patterns = readPatterns("train_letters.txt")
    test_patterns = readPatterns("test_letters.txt")

    #Mostra imagens dos padrões de entrada para memorização
    for i in range(len(train_patterns)):
        display(train_patterns[i].reshape(10, 10), 'padrao_' + str(i) + '.png')

    #Mostra imagens dos padrões para teste da rede
    #for i in range(len(test_patterns)):
        display(test_patterns[i].reshape(10, 10), 'teste_' + str(i) + '.png')

    train_patterns = fix_values(train_patterns)
    test_patterns = fix_values(test_patterns)
Example #10
0
    count, width, height = [int(x) for x in f.readline().split()]  # header
    dim = width * height

    for _ in range(count):
        f.readline()  # skip empty line
        x = np.empty((height, width))
        #print('x shape ', x.shape)
        for r in range(height):
            x[r, :] = np.array(list(f.readline().strip())) == '#'

        patterns.append(2 * x.flatten() -
                        1)  # flatten to 1D vector, rescale {0,1} -> {-1,+1}

util_setup(width, height)

model = Hopfield(dim)
model.train(patterns)


def flip_positions(input, positions):
    flipped = 0
    new_noise = input.copy()
    for pos in positions:
        new_noise[pos] = -new_noise[pos]
        flipped += 1
    return new_noise


def discrete_noise_correction(input):
    all_inputs = []
    for noise_amount in [0, 7, 14, 21]:
Example #11
0
try: 
    matplotlib.rcParams['text.usetex'] = True
except: 
    pass 

if __name__=="__main__": 
    # mnist image parameters 
    image_width, image_height = 28, 28 
    vectorized_image_length = image_height * image_width

    # model size parameters 
    num_neurons = vectorized_image_length
    num_memories = 3

    # instantiate a network 
    net = Hopfield(num_neurons) 

    # generate some sample memories 
    images, _, _, _ = mnist() 
    images = images.reshape(-1, vectorized_image_length)
    memories = [binarize(images[i + 1], thresh=176).ravel() for i in range(num_memories)]

    # add the memories to the network 
    net.add_memories(memories)
    
    # corrupt one of the memories 
    memory = memories[0]
    noise_std = 0.1
    noise_vec = npr.choice([-1., 1.], replace=True, size=num_neurons, p=[noise_std, 1. - noise_std])
    corrupted_memory = np.multiply(memory, noise_vec)
Example #12
0
if not os.path.exists(SAVE_FOLDER):
    os.makedirs(SAVE_FOLDER)

# load pictures into a numpy float 2D array, 1 row per picture
with open('../../datasets/pict.dat', 'r') as source:
    data = source.read().strip('\n')
    data = data.split(',')
    pics = np.array([
        np.array(data[i:i + PICTURE_SIZE]).astype(np.float)
        for i in range(0, len(data), 1024)
    ])
print(f'Successfully loaded {len(pics)} pictures.\n')

# create model
my_model = Hopfield(PICTURE_SIZE, debug_mode=DEBUG)

# learn first three pictures
print("Learning pictures p1, p2, and p3.")
my_model.learn_patterns(pics[0:3])

# from copy import deepcopy

# test = deepcopy(pics[0])


#  Function to generate noisy samples
def add_noise(pattern, proportion):
    noisy = pattern.copy()
    nflips = int(proportion * pattern.shape[0])
    indexes = np.random.choice(pattern.shape[0], nflips,
Example #13
0
File: main.py Project: tokenlab/USP
#Converte valores de 0-1 para -1 a 1
def fix_values(pattern):
    pattern = pattern * 2
    pattern = pattern - 1
    return pattern


#Exibe uma janela contendo a imagem do padrão
def display(pattern):
    plt.imshow(pattern, cmap=plt.cm.binary, interpolation='nearest')
    plt.show()


if __name__ == '__main__':

    hop = Hopfield()

    #Le arquivos de treinamento e teste
    train_patterns = readPatterns("train_letters_4.txt")
    test_patterns = readPatterns("test_letters_4.txt")

    #Mostra imagens dos padrões de entrada para memorização
    #for i in range(len(train_patterns)):
    #    display(train_patterns[i].reshape(10, 10))

    #Mostra imagens dos padrões para teste da rede
    #for i in range(len(test_patterns)):
    #    display(test_patterns[i].reshape(10, 10))

    train_patterns = fix_values(train_patterns)
    test_patterns = fix_values(test_patterns)
Example #14
0
def init_network(coeffs=(0.95, 0.3)):
    network = Hopfield()
    network.W = calculate_weights(coeffs)
    return network
Example #15
0
step = 1

# Create logdir name
logdir = "logs/{}-{}".format(
    os.path.basename(__file__),
    datetime.datetime.now().strftime("%Y-%m-%d_%H%M%S"))
if not os.path.exists("logs"):
    os.mkdir("logs")  # TF 1.6 will do this by itself

image_matrix = dataset.get_image_matrix_rgb()
network = Network()
network.construct(
    logdir, ["original", "result", "result_valid", "result_mean", "var"] +
    [f"result_colors/result_color_{i}" for i in range(len(b))])
network.visualize_image(image_matrix, "original")
hopfield = Hopfield(image_matrix, b=b, alpha=alpha, beta=beta, strmost=strmost)

while True:

    # recompute strmost

    _new_strmost = 1.0 * (step * batchsize - strmost_increase_after) / \
                           (strmost_increase_until - strmost_increase_after) * \
                           (strmost_final - strmost) + strmost

    if _new_strmost > strmost:
        hopfield.strmost = _new_strmost

    print("{}: strmost={:.1f}".format(step * batchsize, hopfield.strmost))

    t = time.time()
Example #16
0
class Main():
    def __init__(self, ):
        self.settings = Settings()
        self.hopfield = None
        self.setupFigures([self.settings.xSize, self.settings.ySize])
        self.workspacePatterns = []
        self.learnedPatterns = []

    def resetEveryting(self):
        self.noOfWorkspace = 0
        self.noOfLearned = 0
        self.currentWorkspace = 0
        self.currentLearned = 0
        self.workspacePatterns.clear()
        self.learnedPatterns.clear()
        self.hopfield.unlearnAll()
        self.figLearned.clear()
        self.figWorkspace.clear()
        self.figIO.clear()
        self.workspaceToolsEnable(False)
        self.learnedToolsEnable(False)
        self.ioToolsEnable(False)

    def setupFigures(self, dim):
        self.figWorkspace = Figures(dim)
        self.figLearned = Figures(dim)
        self.figIO = Figures(dim)
        self.hopfield = Hopfield(dim)

    def applyDimensions(self, dim):
        self.resetEveryting()
        self.settings.ySize, self.settings.xSize = dim
        self.updateCountLabels()
        self.hopfield = Hopfield([self.settings.ySize, self.settings.xSize])
        #self.setupFigures(dim)

    def loadPatternsText(self, filename):
        try:
            loadedPatterns = iofunc.readMatrixTextMultipleFiles(filename)
            self.loadPatterns(loadedPatterns)
        except:
            QtWidgets.QMessageBox.warning(
                mainWindow, 'File error',
                "Bad input file fromat, see help for more info.")

    def loadPatternImage(self, filenames):
        try:
            for filename in filenames:
                loadedPattern = iofunc.readMatrixImage(filename)
                self.loadPatterns([loadedPattern])
        except:
            QtWidgets.QMessageBox.warning(
                mainWindow, 'File error',
                "Bad input file fromat, see help for more info.")

    def loadPatterns(self, loadedPatterns):
        #if the imported image is of different dimensions than loaded, reset all
        arr = self.figWorkspace.image.get_array()
        if len(loadedPatterns[0]) > 150 or len(loadedPatterns[0][0]) > 150:
            QtWidgets.QMessageBox.warning(
                mainWindow, 'Size error',
                "Only patterns up to 150 pixels in either dimension can be loaded."
            )
            return
        if (len(arr) != len(loadedPatterns[0])) or (len(arr[0]) != len(
                loadedPatterns[0][0])):
            self.applyDimensions(
                [len(loadedPatterns[0]),
                 len(loadedPatterns[0][0])])
            mainWindow.spnXSize.setValue(self.settings.xSize)
            mainWindow.spnYSize.setValue(self.settings.ySize)
            mainWindow.updateCanvasLearned()

        self.workspacePatterns.extend(loadedPatterns)

        self.figWorkspace.showPattern(self.workspacePatterns[-1])
        self.noOfWorkspace = len(self.workspacePatterns)
        self.currentWorkspace = len(self.workspacePatterns) - 1
        self.updateCountLabels()
        self.workspaceToolsEnable(True)
        mainWindow.lblDrawErase.show()
        mainWindow.updateCanvasWorkspace()

    def saveWorkspacePatternText(self, filename):
        iofunc.writeMatrixText(filename,
                               [self.workspacePatterns[self.currentWorkspace]])

    def saveAllWorkspacePatternsText(self, filename):
        iofunc.writeMatrixText(filename, self.workspacePatterns)

    def saveOutputText(self, filename):
        iofunc.writeMatrixText(filename, [self.figIO.arr])

    def learnFromFileText(self):
        pass

    def updateCountLabels(self):
        if not self.learnedPatterns:
            mainWindow.lblLearned.setText("0/0")
        else:
            mainWindow.lblLearned.setText(
                "%d/%d" % (self.currentLearned + 1, self.noOfLearned))
        if not self.workspacePatterns:
            mainWindow.lblWorkspace.setText("0/0")
        else:
            mainWindow.lblWorkspace.setText(
                "%d/%d" % (self.currentWorkspace + 1, self.noOfWorkspace))

    #workspace
    def showNextWorkspace(self):
        if not self.workspacePatterns:
            return
        self.currentWorkspace = rollover(0, self.noOfWorkspace - 1,
                                         self.currentWorkspace + 1)
        self.showWorkspaceNumber(self.currentWorkspace)

    def showPreviousWorkspace(self):
        if not self.workspacePatterns:
            return
        self.currentWorkspace = rollover(0, self.noOfWorkspace - 1,
                                         self.currentWorkspace - 1)
        self.showWorkspaceNumber(self.currentWorkspace)

    def showWorkspaceNumber(self, number):
        if not self.workspacePatterns:
            return
        self.figWorkspace.showPattern(self.workspacePatterns[number])
        self.updateCountLabels()
        mainWindow.updateCanvasWorkspace()

    #learned
    def showNextLearned(self):
        if not self.learnedPatterns:
            return
        self.currentLearned = rollover(0, self.noOfLearned - 1,
                                       self.currentLearned + 1)
        self.showLearnedNumber(self.currentLearned)

    def showPreviousLearned(self):
        if not self.learnedPatterns:
            return
        self.currentLearned = rollover(0, self.noOfLearned - 1,
                                       self.currentLearned - 1)
        self.showLearnedNumber(self.currentLearned)

    def showLearnedNumber(self, number):
        if not self.learnedPatterns:
            self.figLearned.clear()
            mainWindow.updateCanvasLearned()
            return
        self.figLearned.showPattern(self.learnedPatterns[number])
        self.updateCountLabels()
        mainWindow.updateCanvasLearned()

    #---
    def learnPattern(self, _=None, pattern=None):
        if pattern is None:
            pattern = self.workspacePatterns[self.currentWorkspace]
        self.hopfield.learnPattern(pattern.copy())
        self.learnedPatterns.append(pattern.copy())
        self.noOfLearned = len(self.learnedPatterns)
        self.currentLearned = self.noOfLearned - 1
        self.showLearnedNumber(self.currentLearned)
        self.learnedToolsEnable(True)
        mainWindow.updateCanvasLearned()

    def learnAllPatterns(self):
        for pattern in self.workspacePatterns:
            self.learnPattern(pattern=pattern)

    def unlearnPattern(self):
        if not self.learnedPatterns:
            return
        self.hopfield.unlearnPattern(self.currentLearned)
        del self.learnedPatterns[self.currentLearned]
        if not self.learnedPatterns:
            self.figLearned.clear()
            self.learnedToolsEnable(False)
            mainWindow.updateCanvasLearned()
        self.noOfLearned = len(self.learnedPatterns)
        self.updateCountLabels()
        self.showPreviousLearned()

    def unlearnAllPatterns(self):
        for _ in range(len(self.learnedPatterns)):
            self.unlearnPattern()

    #workspace control
    def newWorkspacePattern(self, _=None, pattern=None):
        mainWindow.lblDrawErase.show()
        self.workspaceToolsEnable(True)
        if pattern is None:
            pattern = np.ones([self.settings.ySize, self.settings.xSize],
                              dtype=np.int16)

        self.workspacePatterns.append(pattern)
        self.figWorkspace.showPattern(self.workspacePatterns[-1])
        self.noOfWorkspace = len(self.workspacePatterns)
        self.currentWorkspace = len(self.workspacePatterns) - 1
        self.updateCountLabels()
        mainWindow.updateCanvasWorkspace()

    def deleteWorkspacePattern(self):
        if not self.workspacePatterns:
            return
        pass
        del self.workspacePatterns[self.currentWorkspace]
        if not self.workspacePatterns:
            self.figWorkspace.clear()
            mainWindow.updateCanvasWorkspace()
            self.workspaceToolsEnable(False)
            mainWindow.lblDrawErase.hide()
        self.noOfWorkspace = len(self.workspacePatterns)
        self.updateCountLabels()
        self.showPreviousWorkspace()

    def clearWorkspacePattern(self):
        if not self.workspacePatterns:
            return
        self.workspacePatterns[self.currentWorkspace].fill(1)
        self.figWorkspace.showPattern(
            self.workspacePatterns[self.currentWorkspace])
        mainWindow.updateCanvasWorkspace()

    def duplicateWorkspacePattern(self):
        self.newWorkspacePattern(
            pattern=self.workspacePatterns[self.currentWorkspace].copy())

    # IO control
    def setWorkspaceAsInput(self):
        if not self.workspacePatterns:
            return
        self.figIO.showPattern(
            self.workspacePatterns[self.currentWorkspace].copy())
        self.ioToolsEnable(True)
        mainWindow.updateCanvasIO()

    def saveOutputToWorkspace(self):
        self.newWorkspacePattern(pattern=self.figIO.arr.copy())

    def distort(self):
        if not self.learnedPatterns:
            return
        pattern = self.learnedPatterns[self.currentLearned].copy()
        for pixel in np.nditer(pattern, op_flags=['readwrite']):
            if np.random.rand() * 100 < self.settings.distortion:
                pixel[...] = 1 - pixel
        self.figIO.showPattern(pattern)
        self.ioToolsEnable(True)
        mainWindow.updateCanvasIO()

    def solveFinished(self):
        self.hopfieldThread.exit()
        self.settings.animationRunningFlag = False
        self.solvingInProgress(False)
        mainWindow.btnSolve.setText("Reconstruct!")
        mainWindow.btnSetAsInput.setEnabled(True)
        mainWindow.actionWorkspaceSetAsInput.setEnabled(True)

    def solve(self):
        if self.settings.animationRunningFlag:
            self.settings.animationRunningFlag = False
            return

        self.hopfield.setInitialState(self.figIO.arr.copy())
        self.hopfieldThread = HopfieldThread(self.hopfield, self.figIO,
                                             mainWindow.canvasIO,
                                             self.settings)
        self.hopfieldThread.finished.connect(self.solveFinished)
        self.settings.animationRunningFlag = True

        self.solvingInProgress(True)
        mainWindow.btnSolve.setText("Stop")
        mainWindow.btnSetAsInput.setDisabled(True)
        mainWindow.actionWorkspaceSetAsInput.setDisabled(True)

        self.hopfieldThread.start()

    def workspaceToolsEnable(self, enable=True):
        mainWindow.btnSetAsInput.setEnabled(enable)
        mainWindow.actionWorkspaceSetAsInput.setEnabled(enable)
        mainWindow.btnDeletePattern.setEnabled(enable)
        mainWindow.btnClearPattern.setEnabled(enable)
        mainWindow.actionWorkspaceDuplicate.setEnabled(enable)
        mainWindow.actionWorkspaceDelete.setEnabled(enable)
        mainWindow.actionWorkspaceDeleteAll.setEnabled(enable)
        mainWindow.actionWorkspaceClear.setEnabled(enable)
        mainWindow.btnLearn.setEnabled(enable)
        mainWindow.btnLearnAll.setEnabled(enable)
        mainWindow.actionNetworkLearnWorkspace.setEnabled(enable)
        mainWindow.actionNetworkLearnAllWorkspace.setEnabled(enable)
        mainWindow.actionWorkspaceSaveCurrent.setEnabled(enable)
        mainWindow.actionWorkspaceSave.setEnabled(enable)

    def learnedToolsEnable(self, enable=True):
        mainWindow.btnDistort.setEnabled(enable)
        mainWindow.actionNetworkDistort.setEnabled(enable)
        mainWindow.btnUnlearn.setEnabled(enable)
        mainWindow.actionNetworkUnlearn.setEnabled(enable)
        mainWindow.actionNetworkUnlearnAll.setEnabled(enable)

    def ioToolsEnable(self, enable=True):
        mainWindow.btnSolve.setEnabled(enable)
        mainWindow.actionSolve.setEnabled(enable)
        mainWindow.btnSaveToWorkspace.setEnabled(enable)
        mainWindow.actionNetworkSaveToWorkspace.setEnabled(enable)
        mainWindow.actionNetworkSaveToFile.setEnabled(enable)

    def solvingInProgress(self, enable=True):
        mainWindow.btnSetAsInput.setEnabled(not enable)
        mainWindow.btnDistort.setEnabled(not enable)
        mainWindow.btnUnlearn.setEnabled(not enable)
        mainWindow.actionNetworkUnlearn.setEnabled(not enable)
        mainWindow.actionNetworkUnlearnAll.setEnabled(not enable)
        mainWindow.btnLearn.setEnabled(not enable)
        mainWindow.btnLearnAll.setEnabled(not enable)
        mainWindow.actionNetworkSaveToFile.setEnabled(not enable)
Example #17
0
from hopfield import Hopfield
import argparse

if ( __name__ == '__main__' ):
	parser = argparse.ArgumentParser()
	parser.add_argument('-r', "--row", 
		help = "Number of rows for the pattern engine (int)", type = int)
	parser.add_argument('-c', "--col", 
		help = "Number of columns for the pattern engine (int)", type = int)
	parser.add_argument('-o', "--order", nargs = '*',
		help = "List specifying visiting order of each node", type = int)

	args = parser.parse_args()

	row = args.row
	col = args.col
	order = args.order

	# print("row = ", row)
	# print("col = ", col)
	# print("order = ", order)

	test = Hopfield(row = row, col = col, order = order)
	test.run()
Example #18
0
from data import heart, broken
import numpy as np
from hopfield import Hopfield
import matplotlib.pyplot as plt

h, w = heart.shape

hpd = Hopfield()

# Reshaping the data to match requirements of Hopfield.
full = heart.flatten().reshape(-1, 1).T
brkn = broken.flatten().reshape(-1, 1).T

hpd.fit(full)

recreated_heart = hpd.sequential_predict(brkn, 800)

plt.imshow(recreated_heart.reshape(h, w), cmap="Reds")
plt.show()
Example #19
0
 def applyDimensions(self, dim):
     self.resetEveryting()
     self.settings.ySize, self.settings.xSize = dim
     self.updateCountLabels()
     self.hopfield = Hopfield([self.settings.ySize, self.settings.xSize])
Example #20
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue May 29 22:55:20 2018

@author: hielke
"""

from hopfield import Hopfield
import numpy as np

vector = np.matrix([1, -1, 1, -1, 1, 1, 1, 1])

hp = Hopfield(hebbian)
Example #21
0
 def setupFigures(self, dim):
     self.figWorkspace = Figures(dim)
     self.figLearned = Figures(dim)
     self.figIO = Figures(dim)
     self.hopfield = Hopfield(dim)
Example #22
0
def train(train_data):
    model = Hopfield(0, 25)
    model.update(train_data)
    return model
Example #23
0
network = Network()
network.construct(logdir, ["original_greyscale", "original_rgb", "result"])

#visualize.copy_image(image_filename, "out_image_original.png")
#visualize.clear_image("out_image.png")

image_matrix = dataset.get_image_matrix_grayscale()
image_matrix_rgb = dataset.get_image_matrix_rgb()

#visualize.visualize_image_matrix_grayscale(image_matrix, "out_image_original_gray.png")
#for i in range(10):
network.visualize_image(image_matrix_rgb, "original_rgb")
network.visualize_image(image_matrix, "original_greyscale")

hopfield = Hopfield(image_matrix, alpha=alpha, strmost=strmost)

while True:

    # recompute strmost

    _new_strmost = 1.0 * (step * batchsize - strmost_increase_after) / \
                           (strmost_increase_until - strmost_increase_after) * \
                           (strmost_final - strmost) + strmost

    if _new_strmost > strmost:
        hopfield.strmost = _new_strmost

    #hopfield.recompute_random()
    hopfield.recompute_random_batch(batchsize)
Example #24
0
                if not sol.dot(
                        z[i, :]) * vector[i] > err:  # prediction incorrect
                    sol += rate * z[i, :] * vector[i]
                    still_wrong = True
        if not still_wrong:
            print("We are good")
            break

    triu = zip(*np.triu_indices(len(vector), 1))
    weights = np.matlib.zeros((len(vector), len(vector)))
    for ind, iu in enumerate(triu):
        weights[iu] = sol[ind]

    weights += weights.T

    tresh = -1 * sol[-len(vector):]

    return weights, tresh


weights, tresh = hopfield_perceptron(matrix)
np.savetxt('weights.txt', weights)
np.savetxt('tresh.txt', tresh)

hp = Hopfield.with_tresh(weights, tresh)
pprint(hp.list_attractors())

#plt.close('all')
#for state in hp.list_attractors():
#    hp.plot_neuron_states(4, 2, state)