Seq2Seq の疑問を解決するために論文を読む

疑問1 encoder の input について

Seq2Seq encoder に sentence を input するときに Word Embeddings をするのだけど、input が [word_vec1, word_vec2, ..., word_vecn] のように word vector の sequence になるような気がするが自信なし。
Decoder/Encoder を提案した https://arxiv.org/abs/1406.1078 | Learning Phrase Representations using RNN Encoder-Decoder for Statistical Machine Translation を読むと。"We used rank-100 matrices, equivalent to learning an embedding of dimension 100 for each word." と書いてあるから合っているっぽい。


追記
"Each word of the source phrase is embedded in a 500-dimensional vector space: e(xi) ∈ R500." と書いてあるから正解。

疑問2: encoder / decoder の間でやり取りする c について

C は fixed vector であるという記述と、encoder の hidden state そのものが decoder に渡ると読めるものもある。どちらだろうか。前述のオリジナル論文だと "The encoder is an RNN that reads each symbol of an input sequence x sequentially. As it reads each symbol, the hidden state of the RNN changes according to Eq. (1). After reading the end of the sequence (marked by an end-of-sequence sym- bol), the hidden state of the RNN is a summary c of the whole input sequence.
The decoder of the proposed model is another RNN which is trained to generate the output se- quence by predicting the next symbol yt given the hidden state h⟨t⟩." とかいてあるから hidden state h と C は同じものを指しているような気がする。

追記
c = tanh Vh⟨N⟩ だった。

疑問3: decoder の output も word_vector なの?

decoder を train するときに y として与えられる正解データの sentence/word もやはり word_vector なんだろうか?それとも vector of (index of word)?
"e(y)" として論文の後半に出てくるから embedding だ。


ただし decoder の出力自体は j 番目の word の probability を計算しているので全 vocabulary から選んでる?(まだわからない)

unk の扱いについて

unk は vector でどこに存在するのか?

Sequence to Sequence Learning with Neural Networks を読む

論文を流し読み、途中でメモを諦めた。word embeddings をどのタイミングでやっているかわからなかった。基礎知識だから省略されたのかな。

Introduction

  • Input sequence を 1 timestamp ずつ読んで large fixed vector を得る(Input の長さは可変長だが fixed vector になるのがポイント)
  • Input は逆順にすると成績が良くなる
  • translation は「言い換え」になることが多いので LSTM translation の objective が「意味を学ぶ」方向へ向かうことになる

The model

  • LSTM は Input Sequence を fixed dimensional representation v にしてから処理する
  • LSTM を2つ使う。1つは Input Sequence 用、もうひとつは Output Sequence 用。そうすることでパラメータを増やしつつ妥当な計算コストをいじできる
  • 4 layers の LSTM を使用
  • Input sequence を逆順にすると良くなる。abc を αβγ にマッピングするのではなくて cba を αβγ にマッピングするように LSTM を train する。そうすると a は α に b は βに近くなって良い。

作業ログ LSTM 途中

Keras LSTM で足し算

http://peterroelants.github.io/posts/rnn_implementation_part02/ を Keras で。一部元コードをそのまま使ってる。

# Porting http://peterroelants.github.io/posts/rnn_implementation_part02/ using Keras
import sys
import os
import numpy as np
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Activation
from keras.layers import Dropout
from keras.layers import LSTM
from keras.callbacks import ModelCheckpoint
from keras.utils import np_utils

version = 2
weights_dir = "/Users/higepon/Desktop/{0}".format(version)
nb_timestamps = 7
nb_variables = 2

def printSample(x1, x2, t, y=None):
    print(y)
    """Print a sample in a more visual way."""
    x1 = ''.join([str(int(d)) for d in x1])
    x2 = ''.join([str(int(d)) for d in x2])
    t = ''.join([str(int(d[0])) for d in t])
    if not y is None:
        y = ''.join([str(int(d)) for d in y])
    print('x1:   {:s}   {:2d}'.format(x1, int(''.join(reversed(x1)), 2)))
    print('x2: + {:s}   {:2d} '.format(x2, int(''.join(reversed(x2)), 2)))
    print('      -------   --')
    print('t:  = {:s}   {:2d}'.format(t, int(''.join(reversed(t)), 2)))
    if not y is None:
        print('y:  = {:s} {:s}'.format(y, "o" if y == t else "x"))

def create_dataset(nb_samples, sequence_len):
    """Create a dataset for binary addition and return as input, targets."""
    max_int = 2**(sequence_len-1) # Maximum integer that can be added
    format_str = '{:0' + str(sequence_len) + 'b}' # Transform integer in binary format
    nb_inputs = 2  # Add 2 binary numbers
    nb_outputs = 1  # Result is 1 binary number
    X = np.zeros((nb_samples, sequence_len, nb_inputs))  # Input samples
    T = np.zeros((nb_samples, sequence_len, nb_outputs))  # Target samples
    # Fill up the input and target matrix
    for i in range(nb_samples):
        # Generate random numbers to add
        nb1 = np.random.randint(0, max_int)
        nb2 = np.random.randint(0, max_int)
        # Fill current input and target row.
        # Note that binary numbers are added from right to left, but our RNN reads 
        #  from left to right, so reverse the sequence.
        X[i,:,0] = list(reversed([int(b) for b in format_str.format(nb1)]))
        X[i,:,1] = list(reversed([int(b) for b in format_str.format(nb2)]))
        T[i,:,0] = list(reversed([int(b) for b in format_str.format(nb1+nb2)]))
    return X, T

def train():
    # X shape: (2000, 7, 2)
    #  2000: train samples
    #  7: bits
    #  2: x1 and x2
    X_train, T_train = create_dataset(2000, nb_timestamps)
    print('X_train shape: {0}'.format(X_train.shape))
    print('T_train shape: {0}'.format(T_train.shape))
    
    T_train = np.reshape(T_train, (2000, nb_timestamps))
    model = create_model()

    os.makedirs(weights_dir, exist_ok=True)

    filepath = weights_dir + "/{loss:.4f}"
    checkpoint = ModelCheckpoint(filepath, monitor='loss', verbose=1, save_best_only=True, mode='min')
    callbacks_list = [checkpoint]
    # fit the model
    model.fit(X_train, T_train, nb_epoch=8000, batch_size=128, callbacks=callbacks_list)

def create_model():
    model = Sequential()
    model.add(LSTM(10, input_shape=(nb_timestamps, nb_variables)))
#    model.add(Dropout(0.2))
    model.add(Dense(nb_timestamps, activation='relu'))
    model.compile(loss='mean_squared_error', optimizer='adam')
    return model

def best_model_path():
    files = os.listdir(weights_dir)
    files.sort()
    return "{0}/{1}".format(weights_dir, files[0])
    
def predict():
    model = create_model()
    model.load_weights(best_model_path())
    
    # # x1:   1010010   37
    # # x2: + 1101010   43
    # #      -------   --
    # # t:  = 0000101   80
    # x = np.array([1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0]).reshape(1, 7, 2)
    # prediction = model.predict(x, verbose=0)
    # print(np.around(prediction))

    nb_test = 5
    Xtest, Ttest = create_dataset(nb_test, nb_timestamps)
    # Push test data through network
    Y = np.around(model.predict(Xtest))
    # Print out all test examples
    for i in range(Xtest.shape[0]):
        printSample(Xtest[i,:,0], Xtest[i,:,1], Ttest[i,:,:], Y[i,:])
        print('')

if len(sys.argv) == 2:
    if sys.argv[1] == "--train":
        train()
    elif sys.argv[1] == "--predict":
        predict()
    else:
        print("specify --train or --predict")
else:
        print("specify --train or --predict")

exit(-1)

むだ死にしない技術を読んだ

ピロリ菌は知っていたけど。こういった、ある程度科学的根拠が追いやすい知識集をWebで作ったらいいと思った。

むだ死にしない技術
むだ死にしない技術
posted with amazlet at 17.02.20
マガジンハウス (2016-12-20)
売り上げランキング: 1,831

Deep Work を読んだ - 大事なことに集中する―――気が散るものだらけの世界で生産性を最大化する科学的方法

omo さんがおすすめしていた Deep Work を熟読した。Deep Work とは「長期間中断しない難しい知的作業」のこと。その Deep Work がいかに大事か。そしてもっと時間を費やすべきかという内容。Deep Work と対極にあるのが Shallow Work。Twitter/Facebook/Instagram で過ごす時間、メールをチェックする時間など。Deep Work を邪魔するもの。


内容は耳が痛いものばかり。自分がどれだけ「Twitter に時間を費やすこと」を正当化していたかよくわかった。自分でも気づいているものばかりで、当たり前に思える内容だが、他人に指摘されると自分の甘さがよく分かる内容だった。少しずつ Shallow Work を減らしていきたいと思う。

大事なことに集中する―――気が散るものだらけの世界で生産性を最大化する科学的方法

How to run ptb_word_lm.py

古いバージョンの 0.12.1 の頃は models が同梱されていたのでこれを使う。現在は tensorflow/tensorflow と tensorflow/models に分かれてしまったのでバージョンミスマッチなどで全然動かない。

sudo -H pip install tensorflow-0.12.1-cp35-cp35m-macosx_10_11_x86_64.whl
python ptb_word_lm.py --data_path=~/Dropbox/TensorFlow/simple-examples/data

below didn't work **

version 確認する

>>> import tensorflow as tf
>>> tf.__version__
'0.12.1'
>>> 

0.12.1 よりも nightly build で example を走らせよと書いてあるので。
https://github.com/tensorflow/tensorflow/archive/v1.0.0-rc1.zipをダウンロード。

% brew cask install java
% brew install bazel
$ sudo easy_install -U six
$ sudo easy_install -U numpy
$ sudo easy_install wheel
$ sudo easy_install ipython
% cd tensorflow-1.0.0-rc1/ 
% ./configure # だいたいデフォルトの y/n で答える
% bazel build --config opt //tensorflow/tools/pip_package:build_pip_package
% bazel-bin/tensorflow/tools/pip_package/build_pip_package /tmp/tensorflow_pkg
$ sudo pip install /tmp/tensorflow_pkg/tensorflow-1.0.0rc1-cp35-cp35m-macosx_10_6_x86_64.whl
>>> import tensorflow as tf
>>> tf.__version__
'1.0.0-rc1
% wget https://github.com/tensorflow/models/archive/master.zip
% cd models-master/tutorials/rnn/ptb
% brew cask install java
% brew install bazel
$ sudo easy_install -U six
$ sudo easy_install -U numpy
$ sudo easy_install wheel
$ sudo easy_install ipython

Download tensorflow-master.zip
unzip it
cd tensorflow-master.zip
% ./configure
Please specify the location of python. [Default is /Users/higepon/.pyenv/versions/anaconda3-4.1.1/envs/tensorflow/bin/python]: 
Please specify optimization flags to use during compilation when bazel option "--config=opt" is specified [Default is -march=native]: 
Do you wish to build TensorFlow with Google Cloud Platform support? [y/N] 
No Google Cloud Platform support will be enabled for TensorFlow
Do you wish to build TensorFlow with Hadoop File System support? [y/N] 
No Hadoop File System support will be enabled for TensorFlow
Do you wish to build TensorFlow with the XLA just-in-time compiler (experimental)? [y/N] 
No XLA support will be enabled for TensorFlow
Found possible Python library paths:
  /Users/higepon/.pyenv/versions/anaconda3-4.1.1/envs/tensorflow/lib/python3.5/site-packages
Please input the desired Python library path to use.  Default is [/Users/higepon/.pyenv/versions/anaconda3-4.1.1/envs/tensorflow/lib/python3.5/site-packages]

Using python library path: /Users/higepon/.pyenv/versions/anaconda3-4.1.1/envs/tensorflow/lib/python3.5/site-packages
Do you wish to build TensorFlow with OpenCL support? [y/N] 
No OpenCL support will be enabled for TensorFlow
Do you wish to build TensorFlow with CUDA support? [y/N] 
No CUDA support will be enabled for TensorFlow
Configuration finished

% bazel build --config opt //tensorflow/tools/pip_package:build_pip_package
% bazel-bin/tensorflow/tools/pip_package/build_pip_package /tmp/tensorflow_pkg
$ sudo pip install /tmp/tensorflow_pkg/tensorflow-0.12.1-cp35-cp35m-macosx_10_6_x86_64.whl

above didn't work

ImportError: dlopen(/Users/higepon/.pyenv/versions/anaconda3-4.1.1/envs/tensorflow/lib/python3.5/site-packages/tensorflow/python/_pywrap_te
nsorflow.so, 10): Symbol not found: ___cpu_model

https://github.com/tensorflow/tensorflow/issues/7223