Implement a three-layer neural network in Python and Ruby by referring to the code in Chapter 3 of the book "Deep Learning from scratch-The theory and implementation of deep learning learned in Python".
An external library is used in the calculation process. Use NumPy for Python and Numo :: NArray for Ruby.
If you need to build an environment, see here. → Python vs Ruby "Deep Learning from scratch" Chapter 1 Graph of sin and cos functions http://qiita.com/niwasawa/items/6d9aba43f3cdba5ca725
Python
import numpy as np
#Weight and bias initialization
def init_network():
network = {}
network['W1'] = np.array([[0.1, 0.3, 0.5], [0.2, 0.4, 0.6]])
network['b1'] = np.array([0.1, 0.2, 0.3])
network['W2'] = np.array([[0.1, 0.4], [0.2, 0.5], [0.3, 0.6]])
network['b2'] = np.array([0.1, 0.2])
network['W3'] = np.array([[0.1, 0.3], [0.2, 0.4]])
network['b3'] = np.array([0.1, 0.2])
return network
#Convert input signal to output
def forword(network, x):
W1, W2, W3 = network['W1'], network['W2'], network['W3']
b1, b2, b3 = network['b1'], network['b2'], network['b3']
a1 = np.dot(x, W1) + b1
z1 = sigmoid(a1)
a2 = np.dot(z1, W2) + b2
z2 = sigmoid(a2)
a3 = np.dot(z2, W3) + b3
y = identity_function(a3)
return y
#Identity function
def identity_function(x):
return x
#Sigmoid function
def sigmoid(x):
return 1 / (1 + np.exp(-x))
#Run
network = init_network()
x = np.array([1.0, 0.5]) #Input layer
y = forword(network, x)
print(y)
Ruby
require 'numo/narray'
#Weight and bias initialization
def init_network()
network = {}
network['W1'] = Numo::DFloat[[0.1, 0.3, 0.5], [0.2, 0.4, 0.6]]
network['b1'] = Numo::DFloat[0.1, 0.2, 0.3]
network['W2'] = Numo::DFloat[[0.1, 0.4], [0.2, 0.5], [0.3, 0.6]]
network['b2'] = Numo::DFloat[0.1, 0.2]
network['W3'] = Numo::DFloat[[0.1, 0.3], [0.2, 0.4]]
network['b3'] = Numo::DFloat[0.1, 0.2]
network
end
#Convert input signal to output
def forword(network, x)
w1 = network['W1']; w2 = network['W2']; w3 = network['W3']
b1 = network['b1']; b2 = network['b2']; b3 = network['b3']
a1 = x.dot(w1) + b1
z1 = sigmoid(a1)
a2 = z1.dot(w2) + b2
z2 = sigmoid(a2)
a3 = z2.dot(w3) + b3
identity_function(a3)
end
#Identity function
def identity_function(x)
x
end
#Sigmoid function
def sigmoid(x)
1 / (1 + Numo::NMath.exp(-x)) # Numo::Returns DFloat
end
#Run
network = init_network()
x = Numo::DFloat[1.0, 0.5] #Input layer
y = forword(network, x)
puts y.to_a.join(' ')
Python
[ 0.31682708 0.69627909]
Ruby
0.3168270764110298 0.6962790898619668
--Python vs Ruby "Deep Learning from scratch" Summary --Qiita http://qiita.com/niwasawa/items/b8191f13d6dafbc2fede
Recommended Posts