Last active
October 24, 2019 05:21
-
-
Save azizkayumov/d46ab008cd25dad229b26418c4f3ffb0 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 | |
def hypothesis(weights, x): | |
return np.dot(weights, x) | |
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° is converted to 2.7 to avoid overflow | |
slopes = [2.7, 2.1, 3.8, 1.8, 7.0, 6.8, 3.6, 4.9, 2.7, 5.0, | |
4.7, 6.2, 4.4, 5.7, 5.5, 3.6, 6.9, 6.5, 6.7, 3.0, | |
6.3, 4.1, 3.3, 2.3, 2.2, 4.8, 5.2, 3.6, 5.2, 3.3, | |
1.8, 2.9, 4.3, 6.2, 3.5, 3.4, 2.7, 4.3, 5.4, 2.1] | |
# life spans: years with good condition until the first maintenance | |
output = [7.4, 9.5, 5.2, 11.1, 2.8, 2.9, 5.5, 4.0, 7.4, 4.0, | |
4.2, 3.2, 4.5, 3.5, 3.6, 5.5, 2.8, 3.0, 2.9, 6.6, | |
3.1, 4.8, 6.0, 8.6, 9.0, 4.1, 3.8, 5.5, 3.8, 6.0, | |
11.1, 6.8, 4.6, 3.2, 5.7, 5.8, 7.4, 4.6, 3.7, 9.5] | |
bias = [] | |
for i in range(40): | |
bias.append(1) | |
input = np.array([bias, slopes]) | |
w = train(input, output, 0.03, 1500) | |
print("weights = " + str(w)) # 11.178870048530353, -1.3534671476175058 | |
years = hypothesis(w, [1, 2.2]) | |
print("Estimate a slope life span with 22°: " + str(years)) # ~8.2 years |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment