ぱたへね

はてなダイアリーはrustの色分けができないのでこっちに来た

機械学習の説明

今日来たPiqcyから Attention is not Explanation の紹介に反応。 https://arxiv.org/abs/1902.10186

「自然言語処理においてAttentionはよくモデルの判断根拠として用いられるが、本当に説明になっているのかを検証した研究。結果として、GradientベースのスコアとAttentionは乖離があり、またAttentionの分布が異なるよう変更しても予測結果を維持することができることを確認」

意味づけとか解釈の話は、それで一つの研究ジャンルって所まで分かってきた。GRAD-CAMはいろんなアルゴリズムの中でも、意味づけするための仕組みが不要、計算量が少ない事がメリットで、正確さ(これもいろいろ方向がある)はそれなりのアルゴリズムっぽい。

この本が分かりやすく勉強中。 https://christophm.github.io/interpretable-ml-book/

TPUがサポートしていないOPをTensorboardで調べる

TPUを使うと良く謎のエラーに悩まされます。

RuntimeError: Compilation failed: Compilation failure: Detected unsupported operations when trying to compile graph cluster_666512355060360340[] on XLA_TPU_JIT: Placeholder

どのoperationをTPUがサポートしていて、そうでないのかが良く分からず悩んでました。 Tensorboardを使うと、どのoperationがTPUをサポートしているのかを教えてくれます。

やり方は簡単で、tensorboardのgraphを表示させた状態で、TPU compatibilityをクリックするだけです。

f:id:natsutan:20190119100635p:plain

この例ですと6のoperationがサポート対象外です。サポート対象外であってもCPUで動かせる時もあるので全部TPU compatibilityにする必要は無いのですが、エラーの解決やパフォーマンス向上には役に立ちますね。

GCP, TPU, Tensorflow, Tensorboard

ローカルで動いたTensorflow環境をTPUに持って行くとすんなり動かない。動いた物を集めながら、差分を少しずつでも調べていかないと前に進まない感じがする。少しずつ環境をつくっています。やりたいことがいっぱいあるがもどかしい。

TPUを使う

Kerasを使わずにTPUを使ったサンプル。これはあっさりと動きました。

import os
import tensorflow as tf
from tensorflow.contrib import tpu
from tensorflow.examples.tutorials.mnist import input_data

MAX_EPOCH = 50

mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
num_input = 28 * 28 * 1
num_classes = 10

x_ = tf.placeholder("float", shape=[None, num_input], name='X')
y_ = tf.placeholder("float", shape=[None, num_classes], name='Y')

is_training = tf.placeholder(tf.bool)
x_image = tf.reshape(x_, [-1, 28, 28, 1])

conv1 = tf.layers.conv2d(inputs=x_image, filters=32, kernel_size=(5, 5), padding='same', activation=tf.nn.relu)
pool1 = tf.layers.max_pooling2d(inputs=conv1, pool_size=(2, 2), strides=2)
conv2 = tf.layers.conv2d(inputs=pool1, filters=64, kernel_size=(5, 5), padding='same', activation=tf.nn.relu)
pool2 = tf.layers.max_pooling2d(inputs=conv2, pool_size=(2, 2), strides=2)

pool2_flat = tf.reshape(pool2, shape=[-1, 7 * 7 * 64])
dense = tf.layers.dense(inputs=pool2_flat, units=1024, activation=tf.nn.relu)
dropout = tf.layers.dropout(inputs=dense, rate=0.4, training=is_training)
logits = tf.layers.dense(inputs=dropout, units=10)

# 誤差関数
cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits=logits, labels=y_))
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)


correct_prediction = tf.equal(tf.argmax(logits, 1), tf.argmax(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

# TPU
tpu_grpc_url = tf.contrib.cluster_resolver.TPUClusterResolver(tpu=[os.environ['TPU_NAME']])

strategy = tf.contrib.tpu.TPUDistributionStrategy(tpu_grpc_url)

init = tf.global_variables_initializer()

tf.summary.scalar('softmax_cross_entropy', cross_entropy)
tf.summary.scalar('accuracy', accuracy)

merged = tf.summary.merge_all()

with tf.Session() as sess:
    with tf.name_scope('summary'):
        writer = tf.summary.FileWriter('./logs_tpu', sess.graph)

        sess.run(init)

        for i in range(MAX_EPOCH):
            batch = mnist.train.next_batch(50)

            train_accuracy = accuracy.eval(session=sess, feed_dict={x_: batch[0], y_: batch[1], is_training: True})
            print("step = %d, training accuracy = %g" % (i, train_accuracy))

            s = sess.run(merged,  feed_dict={x_: batch[0], y_: batch[1], is_training: False})
            writer.add_summary(s, i)

            train_step.run(session=sess, feed_dict={x_: batch[0], y_: batch[1], is_training: False})
            print("Test Accuracy:", sess.run(accuracy, feed_dict={x_: mnist.test.images, y_: mnist.test.labels, is_training: False}))


tpu.shutdown_system()

Tensorboardを使う

ここを参考に6006のfirewall ruleを追加することで、GCPでの学習結果をtensorboardで確認できます。 https://qiita.com/tk_01/items/307716a680460f8dbe17

f:id:natsutan:20190118205846p:plain f:id:natsutan:20190118205849p:plain

どうやら上手く学習できているようです。

PythonとKerasによるディープラーニング

PythonとKerasによるディープラーニング

PythonとKerasによるディープラーニングを読みました。Kerasの作者が書いた本だけあって、非常に分かりやすく書かれています。Kerasの楽できる関数群をフルに使って、短い記述で定番のニューラルネットワークを動かすことができます。単にニューラルネットワークの説明だけでなく、データの内容を確認したり、学習結果をグラフにプロットしたり、もう半歩先まではコード付きで解説があります。

本のレベルとしては、最初の一歩の次に進める本です。CNNを使った識別や、LSTMを使った未来予測など、やりたいことがはっきりしているのであれば、ショートカットとしてとても役に立ちます。Pythonこれからという人には、ちょっと厳しいと思います。

この本を読んで手を動かしていけば、例えばニューラルネットワークがどこを見て猫と判断しているのかをわかりやすくするヒートマップも、Kerasを使って簡単にできるようになります。

f:id:natsutan:20190105225346j:plain
heatmap

こんな感じですね。識別の部分も含めて、これくらいのコードで実装できます。

model = VGG16(weights='imagenet')

preds = model.predict(x)
print('Predicted:', decode_predictions(preds, top=3))

last_conv_layer = model.get_layer('block5_conv3')
cat_output = model.output[:,386]
grads = K.gradients(cat_output, last_conv_layer.output)[0]

pooled_grads = K.mean(grads, axis=(0,1,2))
grads = K.function([model.input], [pooled_grads, last_conv_layer.output[0]])

iterate = K.function([model.input], [pooled_grads, last_conv_layer.output[0]])

pooled_grads_value, conv_layer_value = iterate([x])

for i in range(512):
    conv_layer_value[:, :, 1] *= pooled_grads_value[i]

heatmap = np.mean(conv_layer_value, axis=-1)
heetmap = np.maximum(heatmap, 0)
heatmap /= np.max(heatmap)

一方、Kerasの弱点として、型から外れると使いにくいというのもあり、ちょっと難しいことをするとこの一冊だけではきついです。

ちょうど昨年末にQiitaに闇のkerasに対する防衛術という記事が上がってました。Kerasが想定していることと違う事をしようとすると、まだまだ情報が足りなかったり、見つけた情報も更新が速すぎて古かったりします。何か新しいことをするというレベルではなく、まず手持ちのデータで識別から始めたいという人におすすめします。

TensorFlowのAPI Level

TensorFlowが良くわからないので勉強しています。 Hands-On Convolutional Neural Networks with TensorFlow を読んでいたら、TensorFlow API levelsというセクションで、High-Level TensorFlow API、Mid-level TensorFlow API, Low-Level TensorFlow APIという表現が出てきました。気になったので、公式ドキュメントを調べてみました。

TensorFlow GuideにAPIの説明がありました。

High Level APIs

これは明確に記載があります。

  • Keras
  • Eager Execution
  • Importting Data
  • Estimators

の4系統です。

Low Level APIs

TensorFlowで使う VariableとかSessionとかがこの辺ですね。

それ以外

High-Level API以外は全部Low-Level APIかとも思ったのですが、TensorBoardはどちらでもなさそうです。また、Mid Level APIは、この本の作者の用語っぽいですね。あと、tf.contribなんかもどちらでもないです。

2018年の思い出

2018年を振り返ってみた。

Coursera

有名どころのCourseraのマシンラーニングコースを終えた。 https://www.coursera.org/learn/machine-learning

人生を少し変えたコースです。このコースの知識でなんとかデータサイエンティストとしての一歩を踏み出しました。今年の方向性も左右しそうです。Deep Learningのオンラインコースは他にもいっぱいありますが、機械学習全般という観点からはこれが最初の一歩として一番良いと自信も持って言えます。

他にもいろんなコースを受けて、それぞれとても勉強になりました。Coursera一本という訳にはいかないですが、本を読みつつがっつり勉強したいときはCourseraでコースを探すという習慣はついたかなと思います。勉強する時間が欲しい。

プリキュア

改めてプリキュアが好きだなと認識した一年でした。特に元気のプリキュア キュアエールには毎週元気をもらってました。 映画も最高でした。初代の二人も良いですね。そろそろHUGっとプリキュアも終わりなのですでにさみしくなってます。プリキュアをゆっくり見る時間が欲しい。ハピネスチャージと魔法つかいプリキュアを最初から全部見たい。

読書

老眼が入ってきて読書量は激減しました。その中からいくつか面白かった本を紹介

君と時計と嘘の塔シリーズ

一年振り返って面白かった本を強いて一冊上げるとすると君と時計と嘘の塔シリーズです。 https://www.amazon.co.jp/dp/B017XHTJTK/ref=dp-kindle-redirect?_encoding=UTF8&btkr=1 謎解き物なのでストーリーなどの解説は無し。ネタバレ無しでどうぞ。

ソード・ワールド2.5ショートストーリーズ 呪いと祝福の大地

https://www.amazon.co.jp/dp/B07JGR1HBZ/ref=dp-kindle-redirect?_encoding=UTF8&btkr=1 この本も良かったです。ソードワールド2.5の新しい世界観を説明するような短編集です。読んでいると冒険したくなってきました。

ラブクラフトの「宇宙からの色」

https://www.amazon.co.jp/dp/4488523048 学生の頃読んだときは具体的な怪物とか出てこなかったり、秘境に行くわけでもなく、正直面白く無かった。今読むと、めちゃ怖くて面白かったです。結婚して子供が大きくなって、「日常」というものが大事に感じているからだと思う。

ゲームブック

ゲームブックを大量に集め始めたが、これまたやる時間がない。出張先に持って行ってやりたい。

2019年にむけて

やりたいことはいっぱいあるので、今年も楽しい一年になりそうです。 皆さんよろしくお願いします。

GCPでTPUを動かしたメモ

GCPでTPU動いたのでメモ

準備

ここ読みながらTPUを起動する。ctpu upの前に、ブラウザのコンソールからSTARTさせないと動かなかった。(TPUにチェックを入れて緑色になっただけだと動いていなかった。)

https://cloud.google.com/tpu/docs/quickstart?hl=ja

途中でshellが変わって補完が効かなくなったのがつらい。まだよくわからない仕組みで動いている。

ちなみに、TPU使うだけならGPUインスタンスの契約は不要。GPU無しのVMとTPUだけ契約すればOK。TPUをプリエンプティブにするとそんなにお金はかからない。12月中はそこそこ遊んだけど、まだ10ドルもかかってないです。

ソース

TensorFlowが良くわからないのでKerasで。

import os
import tensorflow as tf
from tensorflow.contrib import tpu
from tensorflow.keras.datasets import mnist
from tensorflow.keras import layers
from tensorflow.keras import models
from tensorflow.keras.utils import to_categorical

(train_images, train_labels), (test_images, test_labels) = mnist.load_data()

# (60000, 28, 28)
#print(train_images.shape)

# (10000, 28, 28)
#print(test_images.shape)

network = models.Sequential()
network.add(layers.Dense(512, activation='relu', input_shape=(28*28,)))
network.add(layers.Dense(10, activation='softmax'))

# loss function
# optimizer
# metrics

network.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'])

# normalization
train_images = train_images.reshape((60000, 28*28))
train_images = train_images.astype('float32') / 255
test_images = test_images.reshape((10000, 28*28))
test_images = test_images.astype('float32') / 255

# one hot encoding
train_labels = to_categorical(train_labels)
test_labels = to_categorical(test_labels)

tpu_grpc_url = tf.contrib.cluster_resolver.TPUClusterResolver(tpu=[os.environ['TPU_NAME']])

strategy = tf.contrib.tpu.TPUDistributionStrategy(tpu_grpc_url)

tpu_model = tf.contrib.tpu.keras_to_tpu_model(
    network,
    strategy=strategy
)

tpu_model.fit(train_images, train_labels, epochs=5, batch_size=128)
test_loss, test_acc = tpu_model.evaluate(test_images, test_labels)

tpu.shutdown_system()


# test_acc: , 0.9786
print("test_acc: ,", test_acc)

結果

natsutan0@emiru:~/myproj/keras_book/chap2$ python3 mnist_tpu.py
WARNING:tensorflow:From /home/natsutan0/.local/lib/python3.5/site-packages/tensorflow/python/ops/resource_variable_ops.py:434: colocate_with (from tensorflow.python.framework.ops) is deprecated and will be rem\
oved in a future version.
Instructions for updating:
Colocations handled automatically by placer.
2018-12-25 02:02:07.817964: W tensorflow/core/distributed_runtime/rpc/grpc_session.cc:354] GrpcSession::ListDevices will initialize the session with an empty graph and other defaults because the session has no\
t yet been created.
WARNING:tensorflow:tpu_model (from tensorflow.contrib.tpu.python.tpu.keras_support) is experimental and may change or be removed at any time, and without warning.
2018-12-25 02:02:07.834462: I tensorflow/core/platform/profile_utils/cpu_utils.cc:94] CPU Frequency: 2500000000 Hz
2018-12-25 02:02:07.834760: I tensorflow/compiler/xla/service/service.cc:150] XLA service 0x55f1d962b4d0 executing computations on platform Host. Devices:
2018-12-25 02:02:07.834798: I tensorflow/compiler/xla/service/service.cc:158]   StreamExecutor device (0): <undefined>, <undefined>
Epoch 1/5
WARNING:tensorflow:From /home/natsutan0/.local/lib/python3.5/site-packages/tensorflow/contrib/tpu/python/tpu/keras_support.py:302: to_float (from tensorflow.python.ops.math_ops) is deprecated and will be remov\
ed in a future version.
Instructions for updating:
Use tf.cast instead.
WARNING:tensorflow:From /home/natsutan0/.local/lib/python3.5/site-packages/tensorflow/python/ops/math_ops.py:3064: to_int32 (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future v\
ersion.
Instructions for updating:
Use tf.cast instead.
WARNING:tensorflow:Cannot update non-variable config: epsilon
60000/60000 [==============================] - 8s 140us/sample - loss: 0.2546 - acc: 0.9275
Epoch 2/5
60000/60000 [==============================] - 4s 69us/sample - loss: 0.1038 - acc: 0.9697
Epoch 3/5
60000/60000 [==============================] - 4s 71us/sample - loss: 0.0680 - acc: 0.9797
Epoch 4/5
60000/60000 [==============================] - 4s 71us/sample - loss: 0.0486 - acc: 0.9853
Epoch 5/5
60000/60000 [==============================] - 4s 71us/sample - loss: 0.0365 - acc: 0.9890
10000/10000 [==============================] - 4s 355us/sample - loss: 0.0795 - acc: 0.9751
test_acc: , 0.9751
natsutan0@emiru:~/myproj/keras_book/chap2$

TPUが起動していない時はTPU無いで~って怒られる。それがでなくなったのでなんか動いてると思う。 さすがにこの規模だとCPUに比べて気持ち速いレベルです。もうちょっと大きなモデルでやってみたい。