Antonio Gulli, Sujit Pal:直感 Deep Learning

作成日:2020-09-02
最終更新日:

概要

サポートページには、本書のコードが置かれている。
https://github.com/oreilly-japan/deep-learning-with-keras-ja/

感想

第1章 1エポックが遅い

このコードを試すには、keras をインストールしないといけない。 しかし、keras のインストールは第2章で述べられている。 そのため、まず、第2章から読むことにした。四苦八苦の末、 第1章のサンプルコードは動いた。しかし、遅い。本書 p.16 の結果では1エポックの所要時間が 0s だったのが、 私の環境では1エポックの所要時間が短くとも2秒、長いと10秒かかっている。速い PC がほしい。

第2章 keras が入れられない

本書では Keras および keras の土台となる Tensorflow を Python 上で使うことを前提としている。 Tensorflow および Keras は、本書では pip を使ってインストールする方法が書かれていて、私もそれに従った。 なお、私の環境は、 WSL2 でインストールした Ubuntu 20.04 である。 ところが、Python で keras をインポートしようとして、Python が異常終了した。

$ ipython
(中略)
In [1]: from keras.datasets import mnist
Illegal instruction
$

原因は、pip を使ってインストールされる Tensorflow のバイナリに問題があったためである。 より詳しく言うと、Tensorflow のバージョン 1.6 以上では AVX 命令を使っているにもかかわらず、 インストールされたマシンの CPU は AVX 命令をサポートしていないためである。 私の PC の CPU は Intel Celeron 1005M @ 1.90GHz、 Tensorflow は 2.4.1 であった。仕方がない。Tensorflow を戻すことにする。

$ pip3 uninstall keras
(中略)
$ pip3 uninstall tensorflow
(中略)

pip ではなく、conda を使うと、バージョンを指定せずとも問題ないという情報もある。 だめでもともと、やってみよう。

$ conda install tensorflow
(中略)
$ ipython
(中略)
In [1]: import tensorflow
In [2]

Illegal Instruction が出ない。大丈夫だ。keras も conda で入れてみよう。

$ conda install keras
(中略)
$ ipython
(中略)
In [1]: import tenworflow
In [2]: import keras
In [3]: tensorflow.__version__
Out[3]: '2.2.0'
In [4]: keras.__version__
Out[3]: '2.4.3'

次に、p.66 以降述べられている、Quiver が使えるかどうか、インストールを試みた。 まず、conda install からやってみる。

$ conda install quiver_engine
Collecting package metadata (current_repodata.json): done
Solving environment: failed with initial frozen solve. Retrying with flexible solve.

CondaError: KeyboardInterrupt

failed が出たらまずインストールは無理である。次に、pip を試してみよう。

$ pip3 install quiver_engine
Collecting quiver_engine
  Using cached quiver_engine-0.1.4.1.4.tar.gz (398 kB)
    ERROR: Command errored out with exit status 1:
(中略)
  Downloading quiver_engine-0.1.4.1.2.tar.gz (398 kB)
     |████████████████████████████████| 398 kB 5.1 MB/s
    ERROR: Command errored out with exit status 1:
(中略)
WARNING: Discarding →
  https://files.pythonhosted.org/packages/8f/d6/(中略)/quiver_engine-0.1.4.1.2.tar.gz(中略) →
   (from https://pypi.org/simple/quiver-engine/). Command errored out with exit status 1: →	
   python setup.py egg_info Check the logs for full command output.
  Downloading quiver_engine-0.1.4.1.1.tar.gz (398 kB)
     |████████████████████████████████| 398 kB 4.5 MB/s
    ERROR: Command errored out with exit status 1:
(中略)
  Downloading quiver_engine-0.1.3.2.3.tar.gz (3.2 kB)
Requirement already satisfied: keras in /home/username/anaconda3/lib/python3.8/site-packages (from quiver_engine) (2.4.3)
(中略)
Successfully built quiver-engine
Installing collected packages: flask-cors, quiver-engine
Successfully installed flask-cors-3.0.10 quiver-engine-0.1.3.2.3
$ pip3 list | grep quiver
quiver-engine                      0.1.3.2.3

では、quiver.py というコードが動作するか、試してみよう。

$ python3 quiver.py
Traceback (most recent call last):
  File "quiver.py", line 4, in <module>
    from quiver_engine import server
  File "/home/username/anaconda3/lib/python3.8/site-packages/quiver_engine/server.py", line 13, in <module>
    from gevent.wsgi import WSGIServer
ModuleNotFoundError: No module named 'gevent.wsgi'
$ 

しかし、gevent というパッケージはインストールされている。なぜだ。

$ conda list | grep gevent
gevent 21.1.1 py38h27cfd23_1

調べてみると、こんな回答があった。

	Try using:
	from gevent.pywsgi import WSGIServer

	Instead of:	
	from gevent.wsgi import WSGIServer

この英語なら私もわかる。だが、果たしてこれができるのだろうか。 私のホームディレクトリ配下のファイルとはいえ、ライブラリ:
~/anaconda3/lib/python3.8/site-packages/quiver_engine/server.py
を書き換えるのはためらうが、自分のだからいいだろう。さて、書き換えたらどうなったか。

$ python3 quiver.py
(中略)
File "/home/username/anaconda3/lib/python3.8/site-packages/quiver_engine/server.py", line 16, in 
    <module> from scipy.misc import imsave
ImportError: cannot import name 'imsave' from 'scipy.misc' 
  (/home/username/anaconda3/lib/python3.8/site-packages/scipy/misc/__init__.py)

このエラーは、既視感がある。しかし、結局検索してしまった。鳥頭だ。
scipy.misc の imsave は廃止されたので、かわりに imageio.imwrite を使う必要がある。 それにしても、まだ scipy.misc の imsave が残っていたとは噴飯ものだが、 最新の quiver_engine 0.1.4.1.4 では修正されているのかもしれない。 そうすると、なぜこの最新版が入れられなかったということになるが、その理由の解明は私の能力を超える。
https://intellectual-curiosity.tokyo/2019/06/22/quiver_engine%E3%81%A7%E3%80%8Cimporterror-cannot-import-name-imsave-from-scipy-misc%E3%80%8D%E3%81%AE%E5%AF%BE%E5%BF%9C/
にしたがって、quiver_engine/server.py を書き換えた。こんどはどうか。

$ python3 quiver.py
(中略)
File "/home/username/anaconda3/lib/python3.8/site-packages/quiver_engine/server.py", line 19, in <module>
    from imagenet_utils import decode_predictions
ModuleNotFoundError: No module named 'imagenet_utils'

調べてみると、次の文章が見つかった。

Try importing it like:

from keras.applications.vgg16 import preprocess_input, decode_prediction
This is the standard way according to the Keras Applications doc page. 
More reference about Keras Applications can be found there also.

Note: Be aware that it is decode_prediction and not decode_predictions in plural.

quiver_engine/server.py で、imagenet_utils を読み込んでいる箇所を見てみると、
from imagenet_utils import decode_predictions
となって、複数形になっていた。まったくもう。これをこう修正する。
from imagenet_utils import decode_prediction
しかし、出てくるのは同じエラーだった。

$ python3 quiver.py
(中略)
File "/home/username/anaconda3/lib/python3.8/site-packages/quiver_engine/server.py", line 19, in <module>
    from imagenet_utils import decode_prediction
ModuleNotFoundError: No module named 'imagenet_utils'

さらに執念深く探れば解決するのだろうが、私にとってはこれが限界だ。あきらめる。

もっといえば、それぞれの章で適用されるモジュールのバージョンをサポートページの requirements.txt からとってきて、 この環境でやればよかったのだろう。

ということで、もう一押しして、conda を使った環境を作った。そうして、やっと起動する一歩手前まで来た。 注意すべきことがいくつかある。まず、quiver_engine は Python 3.7 以上では動かない。 Python 3.6.* を指定する必要がある。また、他のソフトウェア(ライブラリ、モジュール)のバージョンは固定しない。 そして、quiver_engine は最新版の 0.1.4.1.4 でも画像保存にいまだに scipy.misc の imsave を使っているので、 環境構築時に必要なライブラリとして imageio を含める必要がある。conda で環境を構築するのであれば、 環境名を ch02 として、
(base) $ conda create -n ch02 python=3.6 keras tensorflow gevent h5py quiver_engine imageio
としなければならない。さて、こうした環境を作ってみたらどんな結果が得られるだろうか。

(base) $ conda activate ch02
(ch02) $ python quiver.sh
(中略)
Downloading data from https://storage.googleapis.com/tensorflow/keras-applications/vgg16/vgg16_weights_tf_dim_ordering_tf_kernels.h5
553467904/553467096 [==============================] - 142s 0us/step
Starting webserver from: /home/username/anaconda3/envs/ch02/lib/python3.6/site-packages/quiver_engine
Traceback (most recent call last):
  File "quiver.py", line 10, in <module>
    input_folder='./sample_images', temp_folder='./tmp', port=8000)
  File "/home/username/anaconda3/envs/ch02/lib/python3.6/site-packages/quiver_engine/server.py", line 160, in launch
    temp_folder=temp_folder, input_folder=input_folder),
  File "/home/username/anaconda3/envs/ch02/lib/python3.6/site-packages/quiver_engine/server.py", line 40, in get_app
    get_evaluation_context = get_evaluation_context_getter()
  File "/home/username/anaconda3/envs/ch02/lib/python3.6/site-packages/quiver_engine/server.py", line 171, in get_evaluation_context_getter
    return tf.get_default_graph().as_default
AttributeError: module 'tensorflow' has no attribute 'get_default_graph'
(ch02) $ 

module 'tensorflow' has no attribute 'get_default_graph' というエラーについては下記でまとめられている。
https://qiita.com/white1107/items/67ec0826a07a84442d31
なお、私の環境については、Python=3.6.12, tensorflow=2.2.0, keras=2.4.3 である。 エラーが出ているのは quiver_engine/server.py の中なので、 ソースコードを変更したくないのが本音である。 また、tensorflow や keras といったソフトウェアのバージョンを上げ下げしたくはないのが正直なところである。 結局、quiver を動かすことはあきらめた。

第3章 opencv はどこで使うのか

サポートページの requirements.txt を見ると、ライブラリが次のようになっている。

keras==2.1.6
tensorflow==1.8.0
h5py==2.7.1
Pillow==4.3.0
opencv-python==3.3.1.11

opencv-python もあるが、どこで使うのかわからなかった。

cifar10_net.py を実行するにあたり、私の環境では1エポックあたり 4、5分かかっている。


第4章 敵対的とは

第4章は GAN と WaveNet という表題である。GAN とは、Generative Adversarial Network : 敵対的生成ネットワークの略である。敵対的、というと「敵対的買収」という文脈でしか聞いたことがなかったが、 本書を読むとなるほどと思うのだった。ちなみに」「敵対的買収」を英語でいうと hostile takeover だ。

ここでいう adversarial というのは、生成モデルと識別モデルを敵対者として競わせることで、 生成・識別の能力をともに向上させる、 ということからきている。生成モデルには贋作の作成者を、識別モデルには鑑定士を想定することによって、 敵対性を帯びている。

私のような気の弱い者には、敵対者というと困ってしまう。きっと「永遠のライバル」のような想定ならばいいのだろうが、 そうするとランダムノイズからもっともらしいモノを作るというプロセスが抜け落ちてしまうのかもしれない。 それでも、星飛雄馬の魔球を打とうと努力する花形満や左門豊作やオズマを想像するほうが、私は楽しい。

さて、GAN を生成するためには、keras-adversrial というライブラリを使うと都合がよさそうだ。 本書では github のコードを直接インストールするようになっているが、conda ではインストールできないだろうか。 (base) $ conda search keras-adversarial
(中略)
PackagesNotFoundError: The following packages are not available from current channels:
- keras-adversarial
(中略)

pip ではどうだろうか。

(base) $ pip3 install keras-adversarial
Collecting keras-adversarial
Downloading keras_adversarial-0.0.3-py2.py3-none-any.whl (15 kB)
Requirement already satisfied: Keras in /home/username/anaconda3/lib/python3.8/site-packages (from keras-adversarial) (2.4.3)
Requirement already satisfied: numpy>=1.9.1 in /home/username/anaconda3/lib/python3.8/site-packages (from Keras->keras-adversarial) (1.19.2)
Requirement already satisfied: scipy>=0.14 in /home/username/anaconda3/lib/python3.8/site-packages (from Keras->keras-adversarial) (1.6.1)
Requirement already satisfied: pyyaml in /home/username/anaconda3/lib/python3.8/site-packages (from Keras->keras-adversarial) (5.4.1)
Requirement already satisfied: h5py in /home/username/anaconda3/lib/python3.8/site-packages (from Keras->keras-adversarial) (2.10.0)
Requirement already satisfied: six in /home/username/anaconda3/lib/python3.8/site-packages (from h5py->Keras->keras-adversarial) (1.15.0)
Installing collected packages: keras-adversarial
Successfully installed keras-adversarial-0.0.3

インストールできたようにみえる。では、p.120 の example_gan_convolutional.py は実行できるだろうか。

(base) $ python3 example_gan_convolutional.py
Traceback (most recent call last):
  File "example_gan_convolutional.py", line 13, in <module>
    from keras_adversarial.image_grid_callback import ImageGridCallback
  File "/home/username/anaconda3/lib/python3.8/site-packages/keras_adversarial/__init__.py", line 1, in <module>
    from .adversarial_utils import gan_targets, build_gan, normal_latent_sampling, eliminate_z, fix_names, simple_gan
  File "/home/username/anaconda3/lib/python3.8/site-packages/keras_adversarial/adversarial_utils.py", line 6, in <module>
    from .backend import unpack_assignment, variable_key
  File "/home/username/anaconda3/lib/python3.8/site-packages/keras_adversarial/backend/__init__.py", line 5, in <module>
    from .tensorflow_backend import unpack_assignment, clone_replace, map_params, variable_key
  File "/home/username/anaconda3/lib/python3.8/site-packages/keras_adversarial/backend/tensorflow_backend.py", line 2, in <module>
    from tensorflow.contrib.graph_editor import select
ModuleNotFoundError: No module named 'tensorflow.contrib'

このエラーの原因としては、tensorflow.contrib が tensorflow1.x.x にしかないことから来ているものと思われる。
https://teratail.com/questions/306640
私の環境では tensorflow は 2.2.0 である。また、requirements.txt は次の通りである。

keras==2.1.2
tensorflow==1.8.0
h5py==2.7.1
matplotlib==2.1.1
PIllow==5.1.0
pandas==0.22.0

tensorflow の 1.x.x で一番新しいのは 1.15.0 である。これをもとにして ch04 の環境を作ってみるのがいいかもしれない。 このとき、Python も 3.6 にしなければならない。以下の私の環境は次の通り。

さて、どうだろうか。

(base) $ conda create -n ch04 python=3.6 tensorflow=1.15.0 keras h5py matplotlib pillow pandas

(base) $ conda activate -n ch04

この結果、ch04 の環境は次の通りとなっている。
keras=2.3.1, tensorflow=1.15.0, h5py=2.10.10 matplotlib=3.3.4 pillow=8.1.0, pandas=1.1.5

(ch04) $ pip3 install keras-adversarial
(ch04) $ python3 example_gan_convolutional.py
Using TensorFlow backend.
Traceback (most recent call last):
  File "example_gan_convolutional.py", line 16, in <module>
	from image_utils import dim_ordering_fix, dim_ordering_input, dim_ordering_reshape, dim_ordering_unfix
ModuleNotFoundError: No module named 'image_utils'
(ch04) $ pip3 install image_utils

Traceback (most recent call last): File "example_gan_convolutional.py", line 16, in <module> from image_utils import dim_ordering_fix, dim_ordering_input, dim_ordering_reshape, dim_ordering_unfix ImportError: cannot import name 'dim_ordering_fix'

ここまできて、image_utils.py がカレントのディレクトリにないことがわかった。 本書 p.120 にも書いてあるのに、恥ずかしい話である。 github からカレントのディレクトリにコピーして再度試してみる。

(ch04) $ python3 example_gan_convolutional.py
Using TensorFlow backend.
WARNING:tensorflow:From /home/username/anaconda3/envs/ch04/lib/python3.6/site-packages/tensorflow_core/python/ops/resource_variable_ops.py:→
    1630: calling BaseResourceVariable.__init__ (from tensorflow.python.ops.resource_variable_ops) with constraint is deprecated and will be removed in a future version.
Instructions for updating:
If using Keras pass *_constraint arguments to layers.
Traceback (most recent call last):
  File "example_gan_convolutional.py", line 94, in <module>
    generator = model_generator()
  File "example_gan_convolutional.py", line 29, in model_generator
    H = dim_ordering_reshape(nch, 14)(H)
  File "/mnt/c/Users/username/documents/program/deeplearning_keras/image_utils.py", line 37, in dim_ordering_reshape
    if K.image_dim_ordering() == 'th':
AttributeError: module 'keras.backend' has no attribute 'image_dim_ordering'

https://teratail.com/questions/315709
を見て、カレントディレクトリの image_utils.py の 7, 14, 21, 28, 35, 42 行目の
if K.image_dim_ordering() == 'th':

if K.image_data_format() == 'channels_first'
に修正した。

再度挑戦したところ、それらしい表示が出てきたが、最後は失敗だった:

Total params: 15,345,154
Trainable params: 15,244,418
Non-trainable params: 100,736
__________________________________________________________________________________________________
Traceback (most recent call last):
  File "example_gan_convolutional.py", line 110, in 
    player_names=["generator", "discriminator"])
  File "/home/username/anaconda3/envs/ch04/lib/python3.6/site-packages/keras_adversarial/adversarial_model.py", line 44, in __init__
    self.layers = []
  File "/home/username/anaconda3/envs/ch04/lib/python3.6/site-packages/keras/engine/network.py", line 323, in __setattr__
    super(Network, self).__setattr__(name, value)
  File "/home/username/anaconda3/envs/ch04/lib/python3.6/site-packages/keras/engine/base_layer.py", line 1245, in __setattr__
    super(Layer, self).__setattr__(name, value)
AttributeError: can't set attribute

ここであきらめることにする。


第5章 単語分散表現はうまくいくか

p。152の word2vec_gensim.py を試してみた。

(base) $ python3 word2vec_gensim.py
(中略)
FileNotFoundError: [Errno 2] No such file or directory: 'data/text8'

お恥ずかしい。 p.149 にあった文を見落としていた。 http://mattmahoney.net/dc/text8.zip をダウンロードし、 data/text8 におく。

(base) $ python3 word2vec_gensim.py
FileNotFoundError: [Errno 2] No such file or directory: 'data/text8'

この章の requirements.txt として示されている環境は次の通り。

keras==2.1.6
tensorflow==1.8.0
h5py==2.7.1
matplotlib==2.1.1
gensim==3.2.0
nltk==3.2.5
scikit-learn==0.19.1

私の base 環境は次の通り。

keras=2.4.3, tensorflow=2.2.0, h5py=2.10.0, matplotlib, gensim, nltk, scikit-learn

ではどうだろうか。

(base) $ python3 word2vec_gensim.py
(中略)
2021-02-27 11:01:31,839 : INFO : training on a 85026035 raw words (59642685 effective words) took 310.3s, 192187 effective words/s
model.most_similar('woman')
word2vec_gensim.py:18: DeprecationWarning: Call to deprecated `most_similar` (Method will be removed in 4.0.0, use self.wv.most_similar() instead).
  print(model.most_similar("woman"))
2021-02-27 11:01:31,850 : INFO : precomputing L2-norms of word weight vectors
[('child', 0.7302803993225098), →
 ('girl', 0.7119700908660889), →
 ('prostitute', 0.6762566566467285), →
 ('man', 0.6573313474655151), →('lady', 0.63153076171875), →
 ('baby', 0.6275932788848877), →
 ('mother', 0.6238293647766113), →
 ('herself', 0.6229268908500671), →
 ('person', 0.6131588220596313), →
 ('lover', 0.610485315322876)]
model.most_similar(positive=['woman', 'king'], negative=['man'], topn=10)
word2vec_gensim.py:22: DeprecationWarning: Call to deprecated `most_similar` (Method will be removed in 4.0.0, use self.wv.most_similar() instead).
  print(model.most_similar(positive=["woman", "king"],
[('queen', 0.6185044050216675), →
 ('empress', 0.5706058144569397), →
 ('throne', 0.5563645362854004), →
 ('prince', 0.5521005392074585), →
 ('emperor', 0.5419045090675354), →
 ('elizabeth', 0.5344190001487732), →
 ('princess', 0.5276419520378113), →
 ('daughter', 0.5217649936676025), →
 ('son', 0.5124473571777344), →
 ('consort', 0.5110341310501099)]
model.similarity('girl', 'woman')
word2vec_gensim.py:27: DeprecationWarning: Call to deprecated `similarity` (Method will be removed in 4.0.0, use self.wv.similarity() instead).
  print(model.similarity("girl", "woman"))
0.7119701
model.similarity('girl', 'man')
word2vec_gensim.py:29: DeprecationWarning: Call to deprecated `similarity` (Method will be removed in 4.0.0, use self.wv.similarity() instead).
  print(model.similarity("girl", "man"))
0.57375926
model.similarity('girl', 'car')
word2vec_gensim.py:31: DeprecationWarning: Call to deprecated `similarity` (Method will be removed in 4.0.0, use self.wv.similarity() instead).
  print(model.similarity("girl", "car"))
0.29582304
model.similarity('bus', 'car')
word2vec_gensim.py:33: DeprecationWarning: Call to deprecated `similarity` (Method will be removed in 4.0.0, use self.wv.similarity() instead).
  print(model.similarity("bus", "car"))
0.4992041

いくつか非推奨の警告が出ているが、うまく値が出ているようだ。

第6章 リカレントネットワーク

特に新たな仮想環境を作らずとも、ALice in Wonderland の学習はうまくいっているようだ。 最初のあたりで、

Iteration #: 3
2563/2563 [==============================] - 58s 22ms/step - loss: 1.7035
Generating from seed:  there. “t
 there. “they were the more the mouse the mouse the mouse the mouse the mouse the mouse the mouse the mouse th

こんな出力を見ると、三遊亭圓歌の「授業中」を思い出す。なお、その後のエポックが進むとより複雑な文が生成されたが、 最後のエポックになって、seed が悪かったのだろう、推測した文は the mouse the mouse ... の繰り返しだった。


7章 さまざまなディープラーニングのモデル

7.2.1 の回帰モデルの実装を試してみた。base の環境で特に問題はなく、本書の図と同じような結果が得られた。

8章

ここは時間切れのため、試していない。

誤植

オライリーの日本語ページには誤植に関する情報がない。私がみつけた、些細な誤植を示す。

p.156 上から9行目、「NLTK がすでにインストールされてる可能性は高いでしょう」とあるが、 書籍の文章であることを考慮するとイ抜きことばは避けて「NLTK がすでにインストールされている可能性は高いでしょう」 とすべきだ。

p.261 下から2行目、「実際に Kears を用い」とあるが、正しくは「実際に Keras を用い」だ。

書誌情報

書 名直感 Deep Learning
著 者Antonio Gulli, Sujit Pal
発行日2018 年 8 月 8 日(初版第1刷)
発行所オライリー・ジャパン
発売元オーム社
定 価3400 円
サイズA5 判
ISBN978-4-87311-826-0
その他越谷市立図書館で借りて読む

まりんきょ学問所コンピュータの部屋コンピュータの本ニューロコンピューティング・人工知能 > Antonio Gulli, Sujit Pal:直感 Deep Learning


MARUYAMA Satosi