CNN forward propagation

## cnn-forward.py

<pre>
# coding: utf-8
import sys, os
sys.path.append(os.pardir)  # 親ディレクトリのファイルをインポートするための設定
import pickle
from dataset.mnist import load_mnist
from common.layers import *


def softmax(x):
    if x.ndim == 2:
        x = x.T
        x = x - np.max(x, axis=0)
        y = np.exp(x) / np.sum(np.exp(x), axis=0)
        return y.T

    x = x - np.max(x) # オーバーフロー対策
    return np.exp(x) / np.sum(np.exp(x))


def predict(network, x):

    W1, W2, W3 = network['W1'], network['W2'], network['W3']
    b1, b2, b3 = network['b1'], network['b2'], network['b3']

    # -- Convolution --
    pad = 0
    stride = 1

    FN, C, FH, FW = W1.shape
    x = x.reshape(1, 1, 28, 28)  # Special process
    N, C, H, W = x.shape

    out_h = 1 + int((H + 2*pad - FH) / stride)
    out_w = 1 + int((W + 2*pad - FW) / stride)

    col = im2col(x, FH, FW, stride, pad)
    col_W = W1.reshape(FN, -1).T

    out = np.dot(col, col_W) + b1
    out = out.reshape(N, out_h, out_w, -1).transpose(0, 3, 1, 2)

    # -- ReLU 1 --
    pool_h = 2
    pool_w = 2
    stride = 2
    pad = 0

    x = out
    mask = (x <= 0)
    out = x.copy()
    out[mask] = 0

    # -- Pool --
    x = out
    N, C, H, W = x.shape
    out_h = int(1 + (H - pool_h) / stride)
    out_w = int(1 + (W - pool_w) / stride)

    col = im2col(x, pool_h, pool_w, stride, pad)
    col = col.reshape(-1, pool_h * pool_w)

    out = np.max(col, axis=1)
    out = out.reshape(N, out_h, out_w, C).transpose(0, 3, 1, 2)

    # -- Affine --
    x = out
    x = x.reshape(x.shape[0], -1)
    out = np.dot(x, W2) + b2

    # -- ReLU 2 --
    pool_h = 2
    pool_w = 2
    stride = 2
    pad = 0

    x = out
    mask = (x <= 0)
    out = x.copy()
    out[mask] = 0

    # -- Affine --
    x = out
    x = x.reshape(x.shape[0], -1)

    out = np.dot(x, W3) + b3
    return out

(x_train, t_train), (x_test, t_test) = load_mnist(normalize=True, flatten=True, one_hot_label=False)
x =  x_test
t = t_test

with open("params.pkl", 'rb') as f:
    network = pickle.load(f)

accuracy_cnt = 0
for i in range(10000):
    _y = predict(network, x[i])
    y = softmax(_y)
    loss = cross_entropy_error(y, t[i])
    print(str(t[i]) + ":" + str(np.argmax(y)) + " loss:" + str(loss))

print("Accuracy:" + str(float(accuracy_cnt) / len(x)))

</pre>


## dataset/mnist.py

<pre>
# coding: utf-8
try:
    import urllib.request
except ImportError:
    raise ImportError('You should use Python 3.x')
import os.path
import gzip
import pickle
import os
import numpy as np


url_base = 'http://yann.lecun.com/exdb/mnist/'
key_file = {
    'train_img':'train-images-idx3-ubyte.gz',
    'train_label':'train-labels-idx1-ubyte.gz',
    'test_img':'t10k-images-idx3-ubyte.gz',
    'test_label':'t10k-labels-idx1-ubyte.gz'
}

dataset_dir = os.path.dirname(os.path.abspath(__file__))
save_file = dataset_dir + "/mnist.pkl"

train_num = 60000
test_num = 10000
img_dim = (1, 28, 28)
img_size = 784


def _download(file_name):
    file_path = dataset_dir + "/" + file_name
    
    if os.path.exists(file_path):
        return

    print("Downloading " + file_name + " ... ")
    urllib.request.urlretrieve(url_base + file_name, file_path)
    print("Done")
    
def download_mnist():
    for v in key_file.values():
       _download(v)
        
def _load_label(file_name):
    file_path = dataset_dir + "/" + file_name
    
    print("Converting " + file_name + " to NumPy Array ...")
    with gzip.open(file_path, 'rb') as f:
            labels = np.frombuffer(f.read(), np.uint8, offset=8)
    print("Done")
    
    return labels

def _load_img(file_name):
    file_path = dataset_dir + "/" + file_name
    
    print("Converting " + file_name + " to NumPy Array ...")    
    with gzip.open(file_path, 'rb') as f:
            data = np.frombuffer(f.read(), np.uint8, offset=16)
    data = data.reshape(-1, img_size)
    print("Done")
    
    return data
    
def _convert_numpy():
    dataset = {}
    dataset['train_img'] =  _load_img(key_file['train_img'])
    dataset['train_label'] = _load_label(key_file['train_label'])    
    dataset['test_img'] = _load_img(key_file['test_img'])
    dataset['test_label'] = _load_label(key_file['test_label'])
    
    return dataset

def init_mnist():
    download_mnist()
    dataset = _convert_numpy()
    print("Creating pickle file ...")
    with open(save_file, 'wb') as f:
        pickle.dump(dataset, f, -1)
    print("Done!")

def _change_one_hot_label(X):
    T = np.zeros((X.size, 10))
    for idx, row in enumerate(T):
        row[X[idx]] = 1
        
    return T
    

def load_mnist(normalize=True, flatten=True, one_hot_label=False):
    """MNISTデータセットの読み込み
    
    Parameters
    ----------
    normalize : 画像のピクセル値を0.0~1.0に正規化する
    one_hot_label : 
        one_hot_labelがTrueの場合、ラベルはone-hot配列として返す
        one-hot配列とは、たとえば[0,0,1,0,0,0,0,0,0,0]のような配列
    flatten : 画像を一次元配列に平にするかどうか 
    
    Returns
    -------
    (訓練画像, 訓練ラベル), (テスト画像, テストラベル)
    """
    if not os.path.exists(save_file):
        init_mnist()
        
    with open(save_file, 'rb') as f:
        dataset = pickle.load(f)
    
    if normalize:
        for key in ('train_img', 'test_img'):
            dataset[key] = dataset[key].astype(np.float32)
            dataset[key] /= 255.0
            
    if one_hot_label:
        dataset['train_label'] = _change_one_hot_label(dataset['train_label'])
        dataset['test_label'] = _change_one_hot_label(dataset['test_label'])
    
    if not flatten:
         for key in ('train_img', 'test_img'):
            dataset[key] = dataset[key].reshape(-1, 1, 28, 28)

    return (dataset['train_img'], dataset['train_label']), (dataset['test_img'], dataset['test_label']) 


if __name__ == '__main__':
    init_mnist()
</pre>