TensorFlowで input:100, output:100のネットワークでの学習を検討 v0.7 / v0.7 > dropoutを使おうとしている

```txt:動作環境
GeForce GTX 1070 (8GB)
ASRock Z170M Pro4S [Intel Z170chipset]
Ubuntu 14.04 LTS desktop amd64
TensorFlow v0.11
cuDNN v5.1 for Linux
CUDA v8.0
Python 2.7.6
IPython 5.1.0 -- An enhanced Interactive Python.
gcc (Ubuntu 4.8.4-2ubuntu1~14.04.3) 4.8.4
```

TensorFlowを使って、input:100, output:100程度のネットワークの学習をしようかと作業中。

v0.6 / v0.4: http://qiita.com/7of9/items/7394f4326a88500a67b9

## データ生成コード > v0.7

`NUM_FILEOUT = 100`を`NUM_FILEOUT = 10000`にしてみた。

## 学習コード > v0.7

dropoutを使ってみた。

dropout使用には @shngt さんの記事を参考にさせていただきました。
http://qiita.com/shngt/items/f532601b4f059ce8584f

```learn_in100out100.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import tensorflow as tf
import tensorflow.contrib.slim as slim
import numpy as np

'''
v0.7 Feb. 22, 2017
    - treat each hidden layer to handle dropout instead of slim.stack()
v0.6 Feb. 19, 2017
    - add sys.stdout.flush() to immediately print
v0.5 Feb. 18, 2017
    - add fc_drop()
v0.4 Feb. 15, 2017
    - fix bug > ZeroDivisionError: float division by zero @ shuffle_batch()
v0.3 Feb. 15, 2017
    - tweak [batch_size] for shuffle_batch()
v0.2 Feb. 15, 2017
    - fix bug > different dimensions for placeholder and network
v0.1 Feb. 06, 2017
    - read [test_in.csv],[test_out.csv]
'''

'''
codingrule:PEP8
'''


def fc_drop(inputs, *args, **kwargs):
    # Thanks to: http://qiita.com/shngt/items/f532601b4f059ce8584f
    net = slim.fully_connected(inputs, *args, **kwargs)
    return slim.dropout(net, 0.5)

filename_inp = tf.train.string_input_producer(["test_in.csv"])
filename_out = tf.train.string_input_producer(["test_out.csv"])
NUM_INP_NODE = 100
NUM_OUT_NODE = 100

# parse csv
# a. input node
reader = tf.TextLineReader()
key, value = reader.read(filename_inp)
deflist = [[0.] for idx in range(NUM_INP_NODE)]
input1 = tf.decode_csv(value, record_defaults=deflist)
# b. output node
key, value = reader.read(filename_out)
deflist = [[0.] for idx in range(NUM_OUT_NODE)]
output1 = tf.decode_csv(value, record_defaults=deflist)
# c. pack
# inputs = tf.pack([input1])
inputs = input1
# outputs = tf.pack([output1])
outputs = output1

batch_size = 2
inputs_batch, output_batch = tf.train.shuffle_batch(
    [inputs, outputs], batch_size, capacity=10, min_after_dequeue=batch_size)

input_ph = tf.placeholder("float", [None, 100])
output_ph = tf.placeholder("float", [None, 100])

# network
# a. with stack
# hiddens = slim.stack(input_ph, slim.fully_connected, [7, 7, 7],
#                     activation_fn=tf.nn.sigmoid, scope="hidden")
# b. without stack
# sgm = tf.nn.sigmoid
# hiddens = slim.fully_connected(input_ph, 7, activation_fn=sgm, scope='hidden1')
# hiddens = slim.fully_connected(hiddens, 7, activation_fn=sgm, scope='hidden2')
# hiddens = slim.fully_connected(hiddens, 7, activation_fn=sgm, scope='hidden3')
# c. without stack, with dropout
sgm = tf.nn.sigmoid
hiddens = slim.fully_connected(input_ph, 7, activation_fn=sgm, scope='hidden1')
drpout = slim.stack(hiddens, fc_drop, [7, 7], scope='hd_fc1')
hiddens = slim.fully_connected(drpout, 7, activation_fn=sgm, scope='hidden2')
drpout = slim.stack(hiddens, fc_drop, [7, 7], scope='hd_fc2')
hiddens = slim.fully_connected(drpout, 7, activation_fn=sgm, scope='hidden3')


# a. without dropout
# prediction = slim.fully_connected(
#    hiddens, 100, activation_fn=None, scope="output")
# b. with dropout
drpout = slim.stack(hiddens, fc_drop, [100, 100], scope='fc')
prediction = slim.fully_connected(
    drpout, 100, activation_fn=None, scope="output")
loss = tf.contrib.losses.mean_squared_error(prediction, output_ph)

train_op = slim.learning.create_train_op(loss, tf.train.AdamOptimizer(0.001))

init_op = tf.initialize_all_variables()

with tf.Session() as sess:
    coord = tf.train.Coordinator()
    threads = tf.train.start_queue_runners(sess=sess, coord=coord)

    try:
        sess.run(init_op)
        for idx in range(10000):
            # for idx in range(100000):
            inpbt, outbt = sess.run([inputs_batch, output_batch])
            _, t_loss = sess.run(
                [train_op, loss],
                feed_dict={input_ph: inpbt, output_ph: outbt})

            if (idx+1) % 100 == 0:
                print("%d,%f" % (idx+1, t_loss))
                sys.stdout.flush()
    finally:
        coord.request_stop()

    coord.join(threads)

```

### 学習結果

Jupyterコード

```py:check_result_170215.ipynb
%matplotlib inline

'''
v0.1 Feb. 16, 2017
'''

import numpy as np
import matplotlib.pyplot as plt

# data1 = np.loadtxt('res.learn.170215', delimiter=',')
# data1 = np.loadtxt('res.learn.N=1000_170216', delimiter=',')
data1 = np.loadtxt('res.withStack_170222', delimiter=',')

# data2 = np.loadtxt('res.learn.N=1000_dropout@output_170218', delimiter=',')
# data2 = np.loadtxt('res.learn.N=1000_dropout@output_longrun_170218', delimiter=',')
# data2 = np.loadtxt('res.withoutStack_170222', delimiter=',')
data2 = np.loadtxt('res.withoutStack_withDropout_170222', delimiter=',')

input1 = data1[:,0]
output1 = data1[:,1]
input2 = data2[:,0]
output2 = data2[:,1]

fig = plt.figure()
ax1 = fig.add_subplot(2,1,1)
ax2 = fig.add_subplot(2,1,2)

ax1.scatter(input1,output1)
ax2.scatter(input2,output2)


ax1.set_xlabel('step')
ax1.set_ylabel('Error')
ax1.set_xlim(0, 10000)
ax1.set_ylim(0, 0.2)
ax1.grid(True)

ax2.set_xlabel('step')
ax2.set_ylabel('Error')
ax2.set_xlim(0, 10000)
ax2.set_ylim(0, 0.2)
ax2.grid(True)

fig.show()
```

![qiita.png](https://qiita-image-store.s3.amazonaws.com/0/32870/1fff0a9d-f4bd-759a-978f-e5702d70cb0e.png)

上はoutput layerのみdropoutを適用した結果。
下はhidden layerにもdropoutを適用した結果。

ともに、期待している誤差の減少傾向は見られない。

このあたりのネットワーク構築の知識は関連論文などの情報を整理した方がいいのかもしれない。