TheAlgorithms-Python
63 строки · 1.6 Кб
1"""
2Forward propagation explanation:
3https://towardsdatascience.com/forward-propagation-in-neural-networks-simplified-math-and-code-version-bbcfef6f9250
4"""
5
6import math
7import random
8
9
10# Sigmoid
11def sigmoid_function(value: float, deriv: bool = False) -> float:
12"""Return the sigmoid function of a float.
13
14>>> sigmoid_function(3.5)
150.9706877692486436
16>>> sigmoid_function(3.5, True)
17-8.75
18"""
19if deriv:
20return value * (1 - value)
21return 1 / (1 + math.exp(-value))
22
23
24# Initial Value
25INITIAL_VALUE = 0.02
26
27
28def forward_propagation(expected: int, number_propagations: int) -> float:
29"""Return the value found after the forward propagation training.
30
31>>> res = forward_propagation(32, 450_000) # Was 10_000_000
32>>> res > 31 and res < 33
33True
34
35>>> res = forward_propagation(32, 1000)
36>>> res > 31 and res < 33
37False
38"""
39
40# Random weight
41weight = float(2 * (random.randint(1, 100)) - 1)
42
43for _ in range(number_propagations):
44# Forward propagation
45layer_1 = sigmoid_function(INITIAL_VALUE * weight)
46# How much did we miss?
47layer_1_error = (expected / 100) - layer_1
48# Error delta
49layer_1_delta = layer_1_error * sigmoid_function(layer_1, True)
50# Update weight
51weight += INITIAL_VALUE * layer_1_delta
52
53return layer_1 * 100
54
55
56if __name__ == "__main__":
57import doctest
58
59doctest.testmod()
60
61expected = int(input("Expected value: "))
62number_propagations = int(input("Number of propagations: "))
63print(forward_propagation(expected, number_propagations))
64