Skip to content

Instantly share code, notes, and snippets.

@azizkayumov
Created November 6, 2019 15:31
Show Gist options
  • Save azizkayumov/fe366e44921210a9a09431f654c5ca0e to your computer and use it in GitHub Desktop.
Save azizkayumov/fe366e44921210a9a09431f654c5ca0e to your computer and use it in GitHub Desktop.
import numpy as np
def sigmoid(z):
return 1 / (1 + np.exp(-z))
def sigmoid_derivative(z):
return z * (1 - z)
class Network:
def __init__(self, x, y):
self.x = x
self.y = y
self.weights1 = np.random.randn(2, 5)
self.weights2 = np.random.randn(5, 2)
self.m = len(self.x)
def feed_forward(self, x):
a1 = x
z2 = np.dot(a1, self.weights1)
self.a2 = sigmoid(z2) # 1x5
z3 = np.dot(self.a2, self.weights2)
self.a3 = sigmoid(z3)
return self.a3
def back_prop(self, y):
self.d3 = y - self.a3
self.delta2 = self.d3 * sigmoid_derivative(self.a3)
self.d2 = np.dot(self.delta2, self.weights2.T)
self.delta1 = self.d2 * sigmoid_derivative(self.a2)
def train(self):
self.feed_forward(self.x)
self.back_prop(self.y)
weight_adjustments1 = np.dot(self.x.T, self.delta1)
weight_adjustments2 = np.dot(self.a2.T, self.delta2)
self.weights1 += weight_adjustments1
self.weights2 += weight_adjustments2
def predict(self, new_slope):
o = self.feed_forward([new_slope[0], new_slope[1]])
labels = ["dangerous", "safe"]
guess = 0
max = o[0]
if o[1] > max:
guess = 1
max = o[1]
print("\nTest for a slope with " + str(new_slope[0] * 100) + "° and precipitation of " + str(new_slope[1] * 100) + "%:")
print("This cut-slope is " + labels[guess] + " (" + "{0:.2f}".format(round(max, 2)) + ")")
# slope degrees: for ex. 27° converted to 0.27 to avoid overflow
slopes = [0.27, 0.21, 0.38, 0.18, 0.70, 0.68, 0.36, 0.49, 0.27, 0.50,
0.47, 0.62, 0.44, 0.57, 0.55, 0.36, 0.69, 0.65, 0.67, 0.30,
0.63, 0.41, 0.33, 0.23, 0.22, 0.48, 0.52, 0.36, 0.52, 0.33,
0.18, 0.29, 0.43, 0.62, 0.35, 0.34, 0.27, 0.43, 0.54, 0.21]
# average precipitation: for ex. 60% converted to 0.60
precis = [0.60, 0.56, 0.26, 0.56, 0.10, 0.11, 0.05, 0.34, 0.55, 0.06,
0.58, 0.51, 0.46, 0.02, 0.44, 0.53, 0.24, 0.42, 0.40, 0.20,
0.47, 0.48, 0.20, 0.01, 0.49, 0.13, 0.25, 0.31, 0.10, 0.51,
0.48, 0.51, 0.19, 0.42, 0.28, 0.15, 0.40, 0.60, 0.56, 0.43]
# probability of the maintenance: y[0] - dangerous, y[1] - safe
y = [[1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0,
1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0],
[0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 1,
0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0, 1]]
x = np.array([slopes, precis]).T # transpose from (2x40) to (40x2)
y = np.array(y).T
nn = Network(x, y)
print("\nTraining 15K iterations..")
for i in range(15000):
nn.train()
print("Trained, testing:")
test = [0.42, 0.60]
nn.predict(test) # dangerous
test = [0.22, 0.50]
nn.predict(test) # safe
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment