Коммит e4717ce4 создал по автору Yaroslav's avatar Yaroslav
Просмотр файлов

add comment

владелец d8e24545
%% Cell type:markdown id:8430dbc6 tags:
%% Cell type:markdown id: tags:
# Трёхслойная нейросеть без обучения
%% Cell type:code id:5fa99dae tags:
%% Cell type:code id: tags:
``` python
import numpy as np # расшиение математических возможностей
```
%% Cell type:code id:5805bc21 tags:
%% Cell type:code id: tags:
``` python
ih_wqt = np.array([ # веса первого слоя
[.1, .2,-.1], # hid[0]
[-.1,.1, .9], # hid[l]
[.1, .4, .1]]).T # hid[2]
```
%% Cell type:code id:0cd235ec tags:
%% Cell type:code id: tags:
``` python
hp_wqt = np.array([ # веса второго слоя
[.3, 1.1, -.3], # травмы?
[.1, .2, .0], # победа?
[.0, 1.3, .1] ]).T # печаль?
```
%% Cell type:code id:b1a1a552 tags:
%% Cell type:code id: tags:
``` python
weights = [ih_wqt, hp_wqt] # готовые веса
```
%% Cell type:code id:19207e91 tags:
%% Cell type:code id: tags:
``` python
def neural_network(input, weights):
hid = input.dot(weights[0]) # скалярное умножение входа на веса
pred = hid.dot(weights[1])
return pred # предсказание в виде вероятности
```
%% Cell type:code id:1cc9650c tags:
%% Cell type:code id: tags:
``` python
# мини датасет
toes = np.array([8.5, 9.5, 9.9, 9.0]) # кол-во травм
wlrec = np.array([.65, .8, .8, .9]) # кол-во побед
nfans = np.array([1.2, 1.3, .5, 1.0]) # кол-во печаль
```
%% Cell type:code id:d2a6bed8 tags:
%% Cell type:code id: tags:
``` python
input = np.array([toes[0],wlrec[0],nfans[0]]) # входной 2д слой
pred = neural_network(input, weights) # формирование предсказания
print(pred)
```
%% Output
[0.2135 0.145 0.5065]
%% Cell type:code id:02b6fab3 tags:
%% Cell type:code id: tags:
``` python
commands = ["red", "blue", "green"]
for i in range(len(pred)): # перевод на человеческий язык
if pred[i] > .5: print(commands[i])
```
%% Output
green
%% Cell type:markdown id:778a3c21 tags:
%% Cell type:markdown id: tags:
# Градиентный спуск
%% Cell type:code id:912b31f9 tags:
%% Cell type:code id: tags:
``` python
weight = .5 # веса
goal_pred = .9 # целевая вероятность
input = .5 # входной слой
```
%% Cell type:code id:c892f6ad tags:
%% Cell type:code id: tags:
``` python
for i in range(20): # оно учится
pred = input * weight # предсказание
# большая ошибка станет ещё больше, мелкие не важны
error = (pred - goal_pred) ** 2 # куда промахнулись, перевод в положительное число
# * это маштабирование чистой ошибки для смещения весов
# pred - goal_pred это чистая ошибка без перевода в положительное число
direction_amount = (pred - goal_pred) * input # обращение знака и остановка
# остановка случиться если дать 0 на вход
# обращение знака показывает направление смещения весов
weight = weight - direction_amount # корректировка весов
print(f"Era:{i+1} Error:{error} Prediction:{pred}") # результат эпохи
```
%% Output
Era:1 Error:4.248907230791934e-06 Prediction:0.8979387122396929
Era:2 Error:2.3900103173205486e-06 Prediction:0.8984540341797697
Era:3 Error:1.3443808034926798e-06 Prediction:0.8988405256348273
Era:4 Error:7.562142019645842e-07 Prediction:0.8991303942261205
Era:5 Error:4.25370488605151e-07 Prediction:0.8993477956695903
Era:6 Error:2.392708998404246e-07 Prediction:0.8995108467521927
Era:7 Error:1.3458988116023884e-07 Prediction:0.8996331350641446
Era:8 Error:7.570680815263434e-08 Prediction:0.8997248512981084
Era:9 Error:4.2585079585868274e-08 Prediction:0.8997936384735813
Era:10 Error:2.3954107267068087e-08 Prediction:0.8998452288551859
Era:11 Error:1.3474185337732242e-08 Prediction:0.8998839216413894
Era:12 Error:7.57922925247922e-09 Prediction:0.899912941231042
Era:13 Error:4.2633164545231855e-09 Prediction:0.8999347059232815
Era:14 Error:2.3981155056747285e-09 Prediction:0.8999510294424611
Era:15 Error:1.3489399719440735e-09 Prediction:0.8999632720818458
Era:16 Error:7.587787342170123e-10 Prediction:0.8999724540613844
Era:17 Error:4.2681303799477574e-10 Prediction:0.8999793405460383
Era:18 Error:2.4008233387120123e-10 Prediction:0.8999845054095288
Era:19 Error:1.350463128031958e-10 Prediction:0.8999883790571466
Era:20 Error:7.596355095228145e-11 Prediction:0.8999912842928599
%% Cell type:code id:c9c1e668 tags:
%% Cell type:code id: tags:
``` python
weight, goal_pred, input = (0.0, 0.8, 1.1)
weight, goal_pred, input, alpha = .3, .9, .2, .1
for i in range(4): # катаем мячик по пораболе пока не остановиться в вершине
print("--------- \nWeight:" + str(weight))
pred = input * weight # предсказание
error = (pred - goal_pred) ** 2 # куда промахнулись
# разкрытый direction amount
delta = pred - goal_pred # разность с ожидаемым, чистая ошибка
weight_delta = delta * input # маштабирование
weight = weight - weight_delta # новые веса
# производная как связь в виде касательной для изменения под закономерности в данных,
# показывает скорость изменения ошибки
weight_delta = delta * input # маштабирование
weight = weight - (alpha * weight_delta) # новые веса
# альфа 0.1 смягчает изменение веса и раскатывание мячика
# результат
print(f"Error:{error} Prediction:{pred}")
print(f"Delta:{delta} Weight Delta:{weight_delta}")
```
%% Output
---------
Weight:0.0
Error:0.6400000000000001 Prediction:0.0
Delta:-0.8 Weight Delta:-0.8800000000000001
Weight:0.3
Error:0.7056000000000001 Prediction:0.06
Delta:-0.8400000000000001 Weight Delta:-0.16800000000000004
---------
Weight:0.8800000000000001
Error:0.02822400000000005 Prediction:0.9680000000000002
Delta:0.16800000000000015 Weight Delta:0.1848000000000002
Weight:0.31679999999999997
Error:0.6999664896000001 Prediction:0.06336
Delta:-0.83664 Weight Delta:-0.16732800000000003
---------
Weight:0.6951999999999999
Error:0.0012446784000000064 Prediction:0.76472
Delta:-0.03528000000000009 Weight Delta:-0.0388080000000001
Weight:0.33353279999999996
Error:0.6943779571470337 Prediction:0.06670656
Delta:-0.83329344 Weight Delta:-0.16665868800000003
---------
Weight:0.734008
Error:5.4890317439999896e-05 Prediction:0.8074088
Delta:0.007408799999999993 Weight Delta:0.008149679999999992
Weight:0.35019866879999995
Error:0.6888340435371718 Prediction:0.07003973375999999
Delta:-0.8299602662400001 Weight Delta:-0.16599205324800004
......
%% Cell type:markdown id:8430dbc6 tags:
%% Cell type:markdown id: tags:
# Трёхслойная нейросеть без обучения
%% Cell type:code id:5fa99dae tags:
%% Cell type:code id: tags:
``` python
import numpy as np # расшиение математических возможностей
```
%% Cell type:code id:5805bc21 tags:
%% Cell type:code id: tags:
``` python
ih_wqt = np.array([ # веса первого слоя
[.1, .2,-.1], # hid[0]
[-.1,.1, .9], # hid[l]
[.1, .4, .1]]).T # hid[2]
```
%% Cell type:code id:0cd235ec tags:
%% Cell type:code id: tags:
``` python
hp_wqt = np.array([ # веса второго слоя
[.3, 1.1, -.3], # травмы?
[.1, .2, .0], # победа?
[.0, 1.3, .1] ]).T # печаль?
```
%% Cell type:code id:b1a1a552 tags:
%% Cell type:code id: tags:
``` python
weights = [ih_wqt, hp_wqt] # готовые веса
```
%% Cell type:code id:19207e91 tags:
%% Cell type:code id: tags:
``` python
def neural_network(input, weights):
hid = input.dot(weights[0]) # скалярное умножение входа на веса
pred = hid.dot(weights[1])
return pred # предсказание в виде вероятности
```
%% Cell type:code id:1cc9650c tags:
%% Cell type:code id: tags:
``` python
# мини датасет
toes = np.array([8.5, 9.5, 9.9, 9.0]) # кол-во травм
wlrec = np.array([.65, .8, .8, .9]) # кол-во побед
nfans = np.array([1.2, 1.3, .5, 1.0]) # кол-во печаль
```
%% Cell type:code id:d2a6bed8 tags:
%% Cell type:code id: tags:
``` python
input = np.array([toes[0],wlrec[0],nfans[0]]) # входной 2д слой
pred = neural_network(input, weights) # формирование предсказания
print(pred)
```
%% Output
[0.2135 0.145 0.5065]
%% Cell type:code id:02b6fab3 tags:
%% Cell type:code id: tags:
``` python
commands = ["red", "blue", "green"]
for i in range(len(pred)): # перевод на человеческий язык
if pred[i] > .5: print(commands[i])
```
%% Output
green
%% Cell type:markdown id:778a3c21 tags:
%% Cell type:markdown id: tags:
# Градиентный спуск
%% Cell type:code id:912b31f9 tags:
%% Cell type:code id: tags:
``` python
weight = .5 # веса
goal_pred = .9 # целевая вероятность
input = .5 # входной слой
```
%% Cell type:code id:c892f6ad tags:
%% Cell type:code id: tags:
``` python
for i in range(20): # оно учится
pred = input * weight # предсказание
# большая ошибка станет ещё больше, мелкие не важны
error = (pred - goal_pred) ** 2 # куда промахнулись, перевод в положительное число
# * это маштабирование чистой ошибки для смещения весов
# pred - goal_pred это чистая ошибка без перевода в положительное число
direction_amount = (pred - goal_pred) * input # обращение знака и остановка
# остановка случиться если дать 0 на вход
# обращение знака показывает направление смещения весов
weight = weight - direction_amount # корректировка весов
print(f"Era:{i+1} Error:{error} Prediction:{pred}") # результат эпохи
```
%% Output
Era:1 Error:4.248907230791934e-06 Prediction:0.8979387122396929
Era:2 Error:2.3900103173205486e-06 Prediction:0.8984540341797697
Era:3 Error:1.3443808034926798e-06 Prediction:0.8988405256348273
Era:4 Error:7.562142019645842e-07 Prediction:0.8991303942261205
Era:5 Error:4.25370488605151e-07 Prediction:0.8993477956695903
Era:6 Error:2.392708998404246e-07 Prediction:0.8995108467521927
Era:7 Error:1.3458988116023884e-07 Prediction:0.8996331350641446
Era:8 Error:7.570680815263434e-08 Prediction:0.8997248512981084
Era:9 Error:4.2585079585868274e-08 Prediction:0.8997936384735813
Era:10 Error:2.3954107267068087e-08 Prediction:0.8998452288551859
Era:11 Error:1.3474185337732242e-08 Prediction:0.8998839216413894
Era:12 Error:7.57922925247922e-09 Prediction:0.899912941231042
Era:13 Error:4.2633164545231855e-09 Prediction:0.8999347059232815
Era:14 Error:2.3981155056747285e-09 Prediction:0.8999510294424611
Era:15 Error:1.3489399719440735e-09 Prediction:0.8999632720818458
Era:16 Error:7.587787342170123e-10 Prediction:0.8999724540613844
Era:17 Error:4.2681303799477574e-10 Prediction:0.8999793405460383
Era:18 Error:2.4008233387120123e-10 Prediction:0.8999845054095288
Era:19 Error:1.350463128031958e-10 Prediction:0.8999883790571466
Era:20 Error:7.596355095228145e-11 Prediction:0.8999912842928599
%% Cell type:code id:c9c1e668 tags:
%% Cell type:code id: tags:
``` python
weight, goal_pred, input = (0.0, 0.8, 1.1)
weight, goal_pred, input, alpha = .3, .9, .2, .1
for i in range(4): # катаем мячик по пораболе пока не остановиться в вершине
print("--------- \nWeight:" + str(weight))
pred = input * weight # предсказание
error = (pred - goal_pred) ** 2 # куда промахнулись
# разкрытый direction amount
delta = pred - goal_pred # разность с ожидаемым, чистая ошибка
weight_delta = delta * input # маштабирование
weight = weight - weight_delta # новые веса
# производная как связь в виде касательной для изменения под закономерности в данных,
# показывает скорость изменения ошибки
weight_delta = delta * input # маштабирование
weight = weight - (alpha * weight_delta) # новые веса
# альфа 0.1 смягчает изменение веса и раскатывание мячика
# результат
print(f"Error:{error} Prediction:{pred}")
print(f"Delta:{delta} Weight Delta:{weight_delta}")
```
%% Output
---------
Weight:0.0
Error:0.6400000000000001 Prediction:0.0
Delta:-0.8 Weight Delta:-0.8800000000000001
Weight:0.3
Error:0.7056000000000001 Prediction:0.06
Delta:-0.8400000000000001 Weight Delta:-0.16800000000000004
---------
Weight:0.8800000000000001
Error:0.02822400000000005 Prediction:0.9680000000000002
Delta:0.16800000000000015 Weight Delta:0.1848000000000002
Weight:0.31679999999999997
Error:0.6999664896000001 Prediction:0.06336
Delta:-0.83664 Weight Delta:-0.16732800000000003
---------
Weight:0.6951999999999999
Error:0.0012446784000000064 Prediction:0.76472
Delta:-0.03528000000000009 Weight Delta:-0.0388080000000001
Weight:0.33353279999999996
Error:0.6943779571470337 Prediction:0.06670656
Delta:-0.83329344 Weight Delta:-0.16665868800000003
---------
Weight:0.734008
Error:5.4890317439999896e-05 Prediction:0.8074088
Delta:0.007408799999999993 Weight Delta:0.008149679999999992
Weight:0.35019866879999995
Error:0.6888340435371718 Prediction:0.07003973375999999
Delta:-0.8299602662400001 Weight Delta:-0.16599205324800004
......
Поддерживает Markdown
0% или .
You are about to add 0 people to the discussion. Proceed with caution.
Сначала завершите редактирование этого сообщения!
Пожалуйста, зарегистрируйтесь или чтобы прокомментировать