Deep Learning from scratch 1-3 chapters

1. Introduction to Python


1.2. Installation


pyenv

brew info pyenv
brew install pyenv

anaconda

pyenv install --list
pyenv install anaconda3-4.3.1
pyenv global anaconda3-4.3.1

1.5. NumPy

pip install numpy

1.6. MatPlotLib

pip install matplotlib

01.py


import numpy as np
import matplotlib.pyplot as plt
from matplotlib.image import imread

x = np.arange(0, 6, 0.1)
y1 = np.sin(x)
y2 = np.cos(x)

plt.plot(x, y1, label="sin")
plt.plot(x, y2, label="cos", linestyle="--")
plt.xlabel("x")
plt.ylabel("y")
plt.show()

img = imread('/Users/atsushi/lena.png')
plt.imshow(img)
plt.show()

2. Perceptron


2.3. Implementation of Perceptron


2.3.1 Easy implementation

my_and.py


def my_and(x1, x2):
    w1, w2, theta = 0.5, 0.5, 0.8
    tmp = x1 * w1 + x2 * w2
    if tmp <= theta:
        return 0
    else:
        return 1

print('and')
print(my_and(0, 0))
print(my_and(1, 0))
print(my_and(0, 1))
print(my_and(1, 1))

2.3.3 Implementation of weights and biases

and.py


def and_perceptron(x1, x2):
    x = np.array([x1, x2])
    w = np.array([0.5, 0.5])
    b = -0.7
    value = np.sum(w * x) + b
    if value > 0:
        return 1
    else:
        return 0

print('and perceptron')
print(and_perceptron(0, 0))
print(and_perceptron(1, 0))
print(and_perceptron(0, 1))
print(and_perceptron(1, 1))

nand.py


def nand_perceptron(x1, x2):
    x = np.array([x1, x2])
    w = np.array([-0.5, -0.5])
    b = 0.7
    value = np.sum(w * x) + b
    if value > 0:
        return 1
    else:
        return 0

print('nand perceptron')
print(nand_perceptron(0, 0))
print(nand_perceptron(1, 0))
print(nand_perceptron(0, 1))
print(nand_perceptron(1, 1))

or.py


def or_perceptron(x1, x2):
    x = np.array([x1, x2])
    w = np.array([1, 1])
    b = -0.7
    value = np.sum(w * x) + b
    if value > 0:
        return 1
    else:
        return 0

print('or perceptron')
print(or_perceptron(0, 0))
print(or_perceptron(1, 0))
print(or_perceptron(0, 1))
print(or_perceptron(1, 1))

2.5 Multilayer Perceptron


2.5.2 Implementation of XOR gate

xor.py


def xor_perceptron(x1, x2):
    x3 = nand_perceptron(x1, x2)
    x4 = or_perceptron(x1, x2)
    return and_perceptron(x3, x4)

print('xor perceptron')
print(xor_perceptron(0, 0))
print(xor_perceptron(1, 0))
print(xor_perceptron(0, 1))
print(xor_perceptron(1, 1))

2.6 From NAND to computer

nand_only_xor.py


def nand_only_xor_perceptron(x1, x2):
    x3 = nand_perceptron(x1, x2)
    x4 = nand_perceptron(x1, x3)
    x5 = nand_perceptron(x2, x3)
    return nand_perceptron(x4, x5)

print('nand only xor perceptron')
print(nand_only_xor_perceptron(0, 0))
print(nand_only_xor_perceptron(1, 0))
print(nand_only_xor_perceptron(0, 1))
print(nand_only_xor_perceptron(1, 1))

3. Neural network


3.1. From Perceptron to Neural Network


3.1.2 Review of Perceptron

y = h(b + w_1 x_1 + w_2 x_2)
h(x) = \left\{
\begin{array}{ll}
0 & (x \leq 0) \\
1 & (x > 0)
\end{array}
\right.

3.1.3 Introducing activation function

a = b + w_1 x_1 + w_2 x_2
y = h(a)

3.2 Activation function


3.2.1 Sigmoid function

h(x) = \frac{1}{1 + \exp(-x)}
(-\infty, \infty) \rightarrow (0,1)

3.2.2 Implementation of step function

step_func.py


def step_func(x):
    if x > 0:
        return 1
    else:
        return 0

print('step_function')
print(step_func(-1))
print(step_func(0))
print(step_func(1))
print(step_func(2))

step_function.py


def step_function(x):
    y = x > 0
    return y.astype(np.int)

print('step_function')
print(step_function(np.array([-1, 0, 1, 2])))

3.2.3 Step function graph

step_funtion.py


def step_function(x):
    return np.array(x > 0, dtype = np.int)

x = np.arange(-5.0, 5.0, 0.1)
y = step_function(x)
plt.plot(x, y)
plt.ylim(-0.1, 1.1)
plt.show()

3.2.4 Implementation of sigmoid function

sigmoid.py


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

print('sigmoid')
print(sigmoid(np.array([-1, 0, 1, 2])))

x = np.arange(-5.0, 5.0, 0.1)
y = sigmoid(x)
plt.plot(x, y)
plt.ylim(-0.1, 1.1)
plt.show()

3.2.5 Comparison of sigmoid function and step function

diff.py


x = np.arange(-5.0, 5.0, 0.1)
y = sigmoid(x)
z = step_function(x)
plt.plot(x, y)
plt.plot(x, z)
plt.ylim(-0.1, 1.1)
plt.show()

3.2.6 Non-linear function


3.2.7 ReLU function

h(x) = \left\{
\begin{array}{ll}
x & (x > 0) \\
0 & (x \leq 0)
\end{array}
\right.

relu.py


def relu(x):
    return np.maximum(0, x)

print('relu')
print(relu(np.array([-1, 0, 1, 2])))

x = np.arange(-5.0, 5.0, 0.1)
y = relu(x)
plt.plot(x, y)
plt.ylim(-0.1, 5.1)
plt.show()

3.3 Multidimensional calculation


3.4 3-layer neural network


3.4.3 Implementation Summary

init_network.py


def init_network():
    return {'W1': np.array([[0.1, 0.3, 0.5], [0.2, 0.4, 0.6]]),
            'b1': np.array([0.1, 0.2, 0.3]),
            'W2': np.array([[0.1, 0.4], [0.2, 0.5], [0.3, 0.6]]),
            'b2': np.array([0.1, 0.2]),
            'W3': np.array([[0.1, 0.3], [0.2, 0.4]]),
            'b3': np.array([0.1, 0.2])}

identity_function.py


def identity_function(x):
    return x

forward.py


def forward(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
    return identity_function(a3)

test.py


network = init_network()
x = np.array([1.0, 0.5])
y = forward(network, x)
print(y)
x = np.array([0.0, 0.1])
y = forward(network, x)
print(y)

3.5 Output layer design


3.5.1 Identity and softmax functions

y_k = \frac{\exp(a_k)}{\exp(a_1) + \cdots + \exp(a_n)} = \frac{\exp(a_k)}{\sum_{i = 1}^{n} \exp(a_i)}
(i) \quad 0 < y_k < 1\\
(ii) \quad y_1 + \cdots + y_n = 1

softmax.py


def softmax(a):
    exp_a = np.exp(a)
    sum_exp_a = np.sum(exp_a)
    return exp_a / sum_exp_a

a = np.array([0.3, 2.0, 4.0])
print(softmax(a))

3.5.2 Precautions for implementing Softmax

y_k = \frac{\exp(a_k)}{\sum_{i = 1}^{n} \exp(a_i)} = \frac{C \exp(a_k)}{C \sum_{i = 1}^{n} \exp(a_i)}\\
= \frac{\exp(\log C) \exp(a_k)}{\exp(\log C) \sum_{i = 1}^{n} \exp(a_i)}\\
= \frac{\exp(a_k + \log C)}{\sum_{i = 1}^{n} \exp(a_i + \log C)}

softmax.py


def softmax(a):
    c = np.max(a)
    exp_a = np.exp(a - c)
    sum_exp_a = np.sum(exp_a)
    return exp_a / sum_exp_a

a = np.array([100, 1000, 10000])
print(softmax(a))

3.6 Handwritten digit recognition


3.6.1 MNIST dataset

git clone https://github.com/oreilly-japan/deep-learning-from-scratch.git
cd deep-learning-from-scratch/ch03
python mnist_show.py

hoge


img_show(x_train[1].reshape(28, 28))

3.6.2 Neural network inference processing

python neuralnet_mnist.py

hoge


print(network['W1'])
img_show((x[1] * 255).reshape(28, 28))
predict(network, x[1])
print(t[1])

3.6.3 Batch processing

python neuralnet_mnist_batch.py 

https://github.com/oreilly-japan/deep-learning-from-scratch

Recommended Posts

Deep Learning from scratch 1-3 chapters
Deep Learning from scratch
Deep learning from scratch (cost calculation)
Deep Learning memos made from scratch
"Deep Learning from scratch 2" Self-study memo (No. 21) Chapters 3 and 4
[Learning memo] Deep Learning made from scratch [Chapter 7]
Deep learning from scratch (forward propagation edition)
Deep learning / Deep learning from scratch 2-Try moving GRU
Deep learning / Deep learning made from scratch Chapter 6 Memo
[Learning memo] Deep Learning made from scratch [Chapter 5]
[Learning memo] Deep Learning made from scratch [Chapter 6]
"Deep Learning from scratch" in Haskell (unfinished)
Deep learning / Deep learning made from scratch Chapter 7 Memo
[Windows 10] "Deep Learning from scratch" environment construction
Learning record of reading "Deep Learning from scratch"
[Deep Learning from scratch] About hyperparameter optimization
"Deep Learning from scratch" Self-study memo (Part 12) Deep learning
[Learning memo] Deep Learning made from scratch [~ Chapter 4]
"Deep Learning from scratch" Self-study memo (9) MultiLayerNet class
Deep Learning from scratch ① Chapter 6 "Techniques related to learning"
Good book "Deep Learning from scratch" on GitHub
Deep Learning from scratch Chapter 2 Perceptron (reading memo)
[Learning memo] Deep Learning from scratch ~ Implementation of Dropout ~
Python vs Ruby "Deep Learning from scratch" Summary
"Deep Learning from scratch" Self-study memo (10) MultiLayerNet class
"Deep Learning from scratch" Self-study memo (No. 11) CNN
Deep learning / LSTM scratch code
[Deep Learning from scratch] I implemented the Affine layer
"Deep Learning from scratch" Self-study memo (No. 19) Data Augmentation
Application of Deep Learning 2 made from scratch Spam filter
Deep Learning
[Deep Learning from scratch] I tried to explain Dropout
Deep Learning / Deep Learning from Zero 2 Chapter 4 Memo
Deep Learning / Deep Learning from Zero Chapter 3 Memo
Deep Learning / Deep Learning from Zero 2 Chapter 5 Memo
Deep Learning / Deep Learning from Zero 2 Chapter 7 Memo
Deep Learning / Deep Learning from Zero 2 Chapter 8 Memo
Deep Learning / Deep Learning from Zero Chapter 5 Memo
Deep Learning / Deep Learning from Zero Chapter 4 Memo
Deep Learning / Deep Learning from Zero 2 Chapter 3 Memo
Deep Learning / Deep Learning from Zero 2 Chapter 6 Memo
Deep learning tutorial from environment construction
[Deep Learning from scratch] Implementation of Momentum method and AdaGrad method
An amateur stumbled in Deep Learning from scratch Note: Chapter 1
Making from scratch Deep Learning ❷ An amateur stumbled Note: Chapter 5
Making from scratch Deep Learning ❷ An amateur stumbled Note: Chapter 2
Create an environment for "Deep Learning from scratch" with Docker
An amateur stumbled in Deep Learning from scratch Note: Chapter 3
An amateur stumbled in Deep Learning from scratch Note: Chapter 7
An amateur stumbled in Deep Learning from scratch Note: Chapter 5
Making from scratch Deep Learning ❷ An amateur stumbled Note: Chapter 7
Making from scratch Deep Learning ❷ An amateur stumbled Note: Chapter 1
Making from scratch Deep Learning ❷ An amateur stumbled Note: Chapter 4
"Deep Learning from scratch" self-study memo (No. 18) One! Meow! Grad-CAM!
"Deep Learning from scratch" self-study memo (No. 19-2) Data Augmentation continued
An amateur stumbled in Deep Learning from scratch Note: Chapter 4
An amateur stumbled in Deep Learning from scratch Note: Chapter 2
I tried to implement Perceptron Part 1 [Deep Learning from scratch]
"Deep Learning from scratch" self-study memo (No. 15) TensorFlow beginner tutorial
Making from scratch Deep Learning ❷ An amateur stumbled Note: Chapter 6
[Deep Learning from scratch] Main parameter update methods for neural networks