Skip to content

Instantly share code, notes, and snippets.

@starhopp3r
Last active September 25, 2017 07:55
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save starhopp3r/891101ea804fe2d61ad293bb48df2dcd to your computer and use it in GitHub Desktop.
Save starhopp3r/891101ea804fe2d61ad293bb48df2dcd to your computer and use it in GitHub Desktop.
import numpy as np
import os
class NeuralNetwork:
def __init__(self):
# Our training data
self.X = np.array([[0, 0, 1], [1, 1, 1], [1, 0, 1], [0, 1, 1]])
self.y = np.transpose(np.array([[0, 1, 1, 1]]))
# Seed random number generator to produce the same
# random numbers evertime the program is executed.
np.random.seed(1)
# Random initial weights. We model a single neuron
# with 3 inputs and 1 output. The weight is a 3x1
# matrix with random values in the range -1 to 1
# with a mean of 0.
self.weights = 2 * np.random.random((3, 1)) - 1
def __sigmoid(self, x):
# Normalizes the weighted sum to a value between
# 0 and 1.
return 1 / (1 + np.exp(-x))
def __sigmoid_derivative(self, x):
# Returns the gradient of the sigmoid curve at the
# current point. Indicates how confident we are
# about the existing weight.
return x * (1 - x)
def neuron(self, inputs, weight=None):
# Check is any custom weights have been supplied
if weight is not None:
return self.__sigmoid(np.dot(inputs, weight))
return self.__sigmoid(np.dot(inputs, self.weights))
def train_network(self, inputs, outputs, epochs):
# Training loop
for epoch in range(epochs):
# Single neuron
outpt = self.neuron(inputs)
# Error
error = outputs - outpt
# Adjustment to make
adjustment = np.dot(np.transpose(inputs), error * self.__sigmoid_derivative(outpt))
# Adjust weights
self.weights += adjustment
def save_model(self):
# Save weights in model.npy file
np.save('model.npy', self.weights)
def run_saved_model(self, inpt):
if not os.path.exists('model.npy'):
# No saved model
print("Couldn't find saved model...")
else:
print("Running saved model...")
# Load saved model
weights = np.load('model.npy')
# Predict
return self.neuron(inpt, weights)
if __name__ == '__main__':
# Initialize neural network
nn = NeuralNetwork()
# Training data
X = nn.X
y = nn.y
# Train network
nn.train_network(X, y, 50000)
# Save model
nn.save_model()
# Run saved model
result = nn.run_saved_model(X)
print(result)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment