いっきのblog

技術とか色々

TensorFlow2.0とTensorFlowHubを使ってみる

TensorFlow2.0betaが出てたので、試してみる。

TensorFlowとは?

TensorFlow(テンソルフロー)とは、Googleが開発しているOSS機械学習のライブラリ。Googleはもちろんアルファ碁で有名になったDeepMindでも使われている。
対応言語は、Python, C, C++, Java, Goなどがある。
今回は使わないが、Mobileにも入れることができたりする。

TensorFlow - Wikipedia

また、Tensor(テンソル)については、以下の記事が参考になった。

mathcommunication.hatenablog.com

とはいっても難しくてあまり理解できなかったので、以下の記事がFlow(フロー)部分も含めて、ざっくりの理解ができた。

www.codexa.net

ようは、テンソルとは多次元配列のこといっているとの理解で一旦とどめて置く。

TensorFlow1.0と2.0の違い

以下の記事がいいまとめすぎて、理解しやすかった。

qiita.com

PyTrouchをだいぶ意識したバージョンアップみたい

TensorFlow2.0のインストール方法

pip install tensorflow==2.0.0-beta0

さっそくエラー

ERROR: Cannot uninstall 'wrapt'. It is a distutils installed project and thus we cannot accurately determine which files belong to it which would lead to only a partial uninstall

wrapt周りが怪しいので、uninstallすると無事インストールできた。

pip install -U --ignore-installed wrapt enum34 simplejson netaddr

ニューラルネットワークチュートリアル

以下の記事を行なった。エラーなしで動くので、ここでは特に何もしない。

www.tensorflow.org

ただ、とりあえず具動かせるが、理解が足りてない部分を以下を参考とした。

www.sbbit.jp

ついでに、CNNも

lp-tech.net

softmax

qiita.com

TensorFlowHubのインストール

公式のチュートリアルを参考に動かしてみる

www.tensorflow.org

!pip install "tensorflow_hub==0.4.0"
!pip install "tf-nightly"

つづいて、

import tensorflow as tf
import tensorflow_hub as hub

tf.enable_eager_execution()

module_url = "https://tfhub.dev/google/tf2-preview/nnlm-en-dim128/1"
embed = hub.KerasLayer(module_url)
embeddings = embed(["A long sentence.", "single-word",
                    "http://example.com"])
print(embeddings.shape)  #(3,128)

ここでエラー

AttributeError: module 'tensorflow' has no attribute 'enable_eager_execution'

TF2.0だとeager-modeがデフォルトtrueなので、コメントアウト

www.tensorflow.org

// tf.enable_eager_execution()

1.x => 2.x のマイグレーション

エラーの一つを紹介すると

AttributeError: module 'tensorflow' has no attribute 'logging'

TF2系なのでloggingがないっぽいので、
tf.logging => tf.compat.v1.loggingに変更で動く
tf.gfile => tf.io.gfileなど

www.tensorflow.org

基本はcompat.v1つければよさそう

終わりに

ざっくりと駆け足でTensorFlow2.xを使って見た。
2系らしい動きはまだできてないので、次は深掘りする。