pythonによるtensorflow〜インストール、サンプルの実行〜

今回は、いま注目されている「tensorflow」についてご紹介します。

目次

1. tensorflowとは

以下のページを参考にしました。
「TensorFlow™ is an open source software library for numerical computation using data flow graphs. Nodes in the graph represent mathematical operations, while the graph edges represent the multidimensional data arrays (tensors) communicated between them. The flexible architecture allows you to deploy computation to one or more CPUs or GPUs in a desktop, server, or mobile device with a single API. TensorFlow was originally developed by researchers and engineers working on the Google Brain Team within Google's Machine Intelligence research organization for the purposes of conducting machine learning and deep neural networks research, but the system is general enough to be applicable in a wide variety of other domains as well.」
tensorflowとはdata flow graphsというものを用いて、数値計算を行うライブラリなようです。Google Brain チームにより開発され、機械学習やニューラルネットワークを行うために主に開発されたようです。

機械学習を実装してみようと思う方にとって、必要となるはずなので、今回記事でそれのインストール、サンプルの実行について書きます。

2. tensorflowの利点

データフローグラフ

以下の内容はこのページを参考にしました。
TensorFlowの特徴としては、データフローグラフによる柔軟性、ローレベルオペレータも手書きできる汎用性、高いパフォーマンス、スケーラビリティ、研究レベルから実プロダクトまで扱える効率性などがあります。

利用方法例として、画像に写っているものを認識して文章化するアルゴリズム、各種数値計算、自然言語処理(翻訳)、など多岐におよび、新しい応用分野が広がり続けています。

コア部分はC++で実装されていて、ユーザ向けにPythonのインターフェースが用意されています。

今回の例では、簡単に扱いやすい、pythonでの実装を考えています。

3. tensorflow のインストール


以下の環境はMac(Yosemite 10.10.5)でおこなっています。インストールの仕方はopencvなどのライブラリとよく似ています。

opencvのインストールについては下記をごらんください。

OpenCVのインストール(LP-tech)


tensorflowのインストールで注意すべきことは、

  • GPUがあるかないか
  • pythonのversion
  • WindowsかMacか

です。それに応じて、適切なバージョンをインストールする必要があります。

下の例ではtensorflow version0.9.0をインストールするコードです。

$ export TF_BINARY_URL=https://storage.googleapis.com/tensorflow/mac/tensorflow-0.9.0-py2-none-any.whl
$pip install --upgrade $TF_BINARY_URL
tensorflow install
インストールできたら、早速実行してみましょう。

ターミナルを開いてもらってpythonと入力し以下のように順番ごとに入力すると、"Hello, TensorFlow!"と出力されます。
>>> import tensor flow as tf
>>> hello = tf.constant("Hello, TensorFlow.")
>>> sess = tf.Session()
>>> print(less.run(hello))
Hello, TensorFlow.
sample_tensorflow.py
これでTensorflowが使えるようになりました。

(補足)

3行目を入力した際に
>>> sess = tf.Session()

can't determine number of CPU cores: assuming 4
error.py
と出る場合があります。これはOSXバイナリを使っている場合に発生してしまうエラーなようで、
<span class="go">NUM_CORES = <コア数>;</span>
編集内容
と入力すると解決するそうです。


いかがでしたか?

現在のでは、tensorflowの他に、chainerやKerasと呼ばれるパッケージもあります!

興味のある方は是非調べてみてください。