chakokuのブログ(rev4)

テック・コミック・DTM・・・ごくまれにチャリ

【DLfS】3.4章、forwardのみのニューラルネットを実装

ゼロから作るDeep Learning、3.4.3章 3層ニューラルネット実装まとめ(P65)
昔、スクラッチニューラルネット(逆伝搬で頓挫)を作ってみたことがあり、その時はnumpyを使わなかったので行列計算はループ回して演算していました。numpyの行列演算ライブラリを使うことで一階層分の計算が一行でできてしまう。。

#!/usr/bin/python3
import numpy as np

def sigmoid(x):
    return 1 / (1 + np.exp(-x))

def identify_function(x):
    return x

def init_network():
    # network
    network = {}
    network['W1'] = np.array([[0.3, 0.4, 0.5], [0.6, 0.7, 0.8]])
    network['B1'] = np.array([0.1, 0.2, 0.3])
    network['W2'] = np.array([[0.3, 0.4], [0.1, 0.2], [0.3, 0.4]])
    network['B2'] = np.array([0.2, 0.1])
    network['W3'] = np.array([[0.1, 0.2], [0.3, 0.4]])
    network['B3'] = np.array([0.1, 0.2])
    return network

def forward(net, x):
    a1 = np.dot(x, net['W1']) + net['B1']
    z1 = sigmoid(a1)
    a2 = np.dot(z1, net['W2']) + net['B2']
    z2 = sigmoid(a2)
    a3 = np.dot(z2, net['W3']) + net['B3']
    y = identify_function(a3)
    return y

x = np.array([0.1, 0.2])
net = init_network()
out = forward(net, x)

print('--input--')
print(x)
print('--output--')
print(out)

#$ ./343_nn.py
#--input--
#[ 0.1  0.2]
#--output--
#[ 0.36494708  0.59654212]