1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

numpy-sigmoid学習

Last updated at Posted at 2019-12-28

#numpy-sigmoid学習
自己学習の備忘。
numpy-sigmoidを理解するために図と学習用コードを並べる
ニューラルネットワークの全体像.jpg

活性化関数にシグモイド関数を使った場合に以下のようになる

python

import numpy as np


# シグモイド関数の定義
def sigmoid(a):
    return 1 / (1 + np.exp(-a))


# 一層目
x1 = np.array([[1], [2]])
w1 = np.array([[0.4, 0.3], [0.7, 0.6]])
a1 = w1.dot(x1)

# 二層目
x2 = sigmoid(a1)
w2 = np.array([[0.2, 0.3], [1, 0.7]])
a2 = w2.dot(x2)

# 出力値と正解値
y = sigmoid(a2)
t = np.array([[1], [0]])
print(y)

# 入力値、パラメーター、合算値を配列化
X = [x1, x2]
A = [a1, a2]
W = [w1, w2]

# パラメーターが何層あるかのサイズの取得
max_layer = len(X)


# 活性化関数の微分
def f(a):
    return (1 - sigmoid(a)) * sigmoid(a)


# 更新式の公式gの実装
def g(l, j):
    if max_layer == l:
        return (y[j] - t[j]) * f(A[l - 1][j])
    else:
        output = 0
        m = A[l - 1].shape[0]
        for i in range(m):
            output += g(l + 1, i) * W[l][j, i] * f(A[l - 1][j])
        return output


# パラメーターwによる誤差関数の微分
def diff(j, k, l):
    return g(l, j) * X[l - 1][k]


# パラメーターを100回学習
for _ in range(100):
    for l in range(len(X)):
        for j in range(W[l].shape[0]):
            for k in range(W[l].shape[1]):
                W[l][j, k] = W[l][j, k] - diff(j, k, l + 1)
    A[0] = W[0].dot(X[0])
    X[1] = sigmoid(A[0])
    A[1] = W[1].dot(X[1])
    y = sigmoid(A[1])

print(y)

[[0.60041131]
[0.79248709]]
[[0.91175343]
[0.08878309]]

shapeを調べた件

python
#range.shapeを理解する shapeは行と桁を返すようだ
import numpy as np
a = np.array([[1,2,3],[4,5,6],[4,5,6],[4,5,6]])
a.shape

(4, 3)

要するに配列の大きさです。この結果は4*3(4行3列)の配列であることを表します。
a.shape[0]はこの例なら4になります。a.shape[1]なら3

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?