restores
restores

Reputation: 51

Neural Network (Simple)

I was curious as to why I am getting no output printed, as the code has no errors.

import numpy as np


class NN():
    def _init_(self):
        # Seed random number generator, so it generates the same number
        # every time program runs
        np.random.seed(1)

        # Model single neuron, with 3 input connections and 1 output connection
        # Assign random weights to a 3x1 matrix, with values in range -1 to 1
        # and mean of 0
        self.synaptic_weights = 2 * np.random.random((3, 1)) - 1

    # Describes an s shaped curve we pass the weighted sum of the inputs
    # through this function to normalise them between 0 and 1
    def __sigmoid(self, x):
        return 1 / (1 + np.exp(-x))

    # Gradient of the sigmoid curve
    def __sigmoid_derivative(self, x):
        return x * (1 - x)

    def train(self, training_set_input, training_set_output, number_of_training_iterations):
        for iteration in np.xrange(number_of_training_iterations):
            # pass training set through neural net
            output = self.predict(training_set_input)

            error = training_set_output - output

            # multiply error by input and again by the gradient of the sigmoid curve
            adjustment = np.dot(training_set_input.T, error * self.__sigmoid_derivative(output))

            # Adjust the weights
            self.synaptic_weights += adjustment

    def predict(self, inputs):
        # Pass inputs through neural network (single neuron)
        return self.__sigmoid(np.dot(inputs, self.synaptic_weights))


if __name__ == "__NN__":
    # init single neuron neural network
    nn = NN()
    weightz = nn.synaptic_weights
    new_predict = nn.predict(np.array[1, 0, 0])

    print("Random starting synaptic weights")
    print(weightz)

    # T flips the matrix vertically
    training_set_input = np.array([0, 0, 1], [1, 1, 1], [1, 0, 1], [0, 1, 1])
    training_set_output = np.array([0, 1, 0, 0]).T

    # train network using training set
    # do it 10,000 times and make small adjustments each time
    nn.train(training_set_input, training_set_output, 10000)

    print("New starting synaptic weights")
    print(weightz)

    # test
    print("Predicting")
    print(new_predict)

Saved file as NN.py

Upvotes: 2

Views: 664

Answers (1)

ForceBru
ForceBru

Reputation: 44886

Clearly, __name__ is not equal to "__NN__". Rather, it's equal to "__main__".

From the docs:

The __name__ attribute must be set to the fully-qualified name of the module. This name is used to uniquely identify the module in the import system.

Upvotes: 1

Related Questions