ytooyamaのブログ

サーバ構築とか、仕事で発見したこととか、趣味のこととかを書いています。

Python 3.7でTensorflow 2.xを動かす

この記事はQiitaからの移行記事です。内容が古い場合があります。

前書き

macOSにPython3.7.xをインストールして pip3 install tensorflow したら 2.1系が入りました。ネットで見つけたコードが動かなくて困りました。

Python 3.6.xとTensorflow 1.xのセットアップを行えば元のソースのまま実行できるようですが、せっかくなのでTensorflow 2.xを使ってみたいと思います。

この構成でHello Tensorflowするには?

何も考えずHello Tensorflowしてみる

そして、よくあるコードを tf-hello.py みたいな名前をつけて保存し、実行してみます。

import tensorflow as tf
  
hello = tf.constant('Hello, Hello World!')

sess = tf.Session()
print(sess.run(hello)) 

すると、次のように表示されるはずです。

$ python3 tf-hello.py
...
Traceback (most recent call last):
  File "tf-hello.py", line 6, in <module>
    sess = tf.Session()
AttributeError: module 'tensorflow' has no attribute 'Session'

Tensorflow 2.xでは、tf.Sessionやtf.placeholderは使わなくなったようです(Migrate your TensorFlow 1 code to TensorFlow 2を参照)。

対策1

次のようにコード修正する方法があります。 ただ出力するなら tf.print が使えるようです。

import tensorflow as tf
  
hello = tf.constant('Hello, Hello World!')

#sess = tf.Session()
#print(sess.run(hello))

tf.print(hello) 

対策2

次のようにimport行を修正する方法があります。こちらの方法でも動作しますが、いずれ動かなくなるので、対策1の方法の方が良さそうです。

#import tensorflow as tf
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
 
hello = tf.constant('Hello, Hello World!')

sess = tf.Session()
print(sess.run(hello)) 

ちなみに

数値も同様に代入したものを出力できます。

$ cat calc.py

import tensorflow as tf

a = tf.constant(1234)
b = tf.constant(5000)
total = a + b
tf.print(total)              

$ python3.7 calc.py
...
2020-02-13 00:34:45.897058: I tensorflow/compiler/xla/service/service.cc:168] XLA service 0x7f9b08d70740 initialized for platform Host (this does not guarantee that XLA will be used). Devices:
2020-02-13 00:34:45.897083: I tensorflow/compiler/xla/service/service.cc:176]   StreamExecutor device (0): Host, Default Version
6234

以上です。

参考

このブログサイトはJavaScriptを使っていますが、読み込んでいるJavaScriptは全てはてなが提供しているものであり、筆者が設置しているものではありません。