Last active
October 24, 2019 08:00
-
-
Save azizkayumov/e60424addacca8a047010775e84e4b95 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
import math | |
def sigmoid(x): | |
return 1 / (1 + math.exp(-x)) | |
def hypothesis(weights, x): | |
h = np.dot(weights, x) | |
return sigmoid(h) | |
def decision(probability): | |
if probability >= 0.5: | |
return "dangerous" | |
return "safe" | |
def cost_derivative(weights, x, y, feature_x): | |
s = 0 | |
m = len(x[0]) | |
for i in range(m): | |
s += (hypothesis(weights, x[:, i]) - y[i]) * feature_x[i] | |
return s / m | |
def train(x, y, a, number_of_iterations): | |
i = 0 | |
n = len(x) # number of features | |
weights = [0] * n | |
while i < number_of_iterations: | |
temp_weights = [0] * n | |
for j in range(n): | |
temp_weights[j] = weights[j] - a * cost_derivative(weights, x, y, x[j]) | |
if temp_weights == weights: | |
return weights | |
for j in range(n): | |
weights[j] = temp_weights[j] | |
i += 1 | |
return weights | |
# slope degrees: for ex. 27° converted to 0.27 to avoid overflow | |
slopes = [0.27, 0.21, 0.38, 0.18, 0.7, 0.68, 0.36, 0.49, 0.27, 0.5, | |
0.47, 0.62, 0.44, 0.57, 0.55, 0.36, 0.69, 0.65, 0.67, 0.3, | |
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.6, 0.56, 0.26, 0.56, 0.1, 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.4, 0.2, | |
0.47, 0.48, 0.2, 0.01, 0.49, 0.13, 0.25, 0.31, 0.1, 0.51, | |
0.48, 0.51, 0.19, 0.42, 0.28, 0.15, 0.4, 0.6, 0.56, 0.43] | |
# probability of the maintenance: for ex. 45% converted to 0.45 | |
output = [0.54, 0.49, 0.35, 0.48, 0.35, 0.35, 0.2, 0.44, 0.51, 0.26, | |
0.59, 0.6, 0.5, 0.25, 0.53, 0.52, 0.44, 0.55, 0.54, 0.28, | |
0.57, 0.51, 0.29, 0.13, 0.45, 0.3, 0.39, 0.38, 0.29, 0.5, | |
0.43, 0.49, 0.32, 0.54, 0.35, 0.26, 0.41, 0.59, 0.6, 0.41] | |
bias = [] | |
for i in range(len(slopes)): | |
bias.append(1) | |
x = np.array([bias, slopes, precis]) | |
w = train(x, output, 0.7, 1500) | |
print("weights = " + str(w)) | |
prob = hypothesis(w, [1, 0.22, 0.50]) | |
print("\nTest for a slope with 22° and precipitation of 50%:") | |
print("Probability: " + str(prob)) # ~0.454 | |
print("This cut slope is " + decision(prob)) # safe | |
prob = hypothesis(w, [1, 0.42, 0.60]) | |
print("\nTest for a slope with 52° and precipitation of 60%:") | |
print("Probability: " + str(prob)) # ~0.594 | |
print("This cut slope is " + decision(prob)) # dangerous |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment