0

下のコードはtensor flowの、 リストに含まれている数字を計算グラフの演算に供給しその出力を書き出すコードなんですが
最後のfeed_dict={x_data: x_val}はどういう意味でしょうか?

import tensorflow as tf
sess = tf.Session()
#テンソルとプレースホルダを設定する。ここでは演算に供給するためのNumpy配列を作成する
import numpy as np

x_vals = np.array([1., 3., 5., 7., 9.])
x_data = tf.placeholder(tf.float32)
m_const = tf.constant(3.)
#演算を定義する
my_product = tf.multiply(x_data, m_const)
#入力値をループで処理し、入力値ごとに除算の結果を出力する。
for x_val in x_vals:
    print(sess.run(my_product, feed_dict={x_data: x_val}))
2
  • 1
    Tensorflow の API ドキュメントにある tf.Session.run の説明はご覧になりましたか?
    – nekketsuuu
    2017年8月17日 2:55
  • すいません恥ずかしながら英語が苦手で調べながらでもわかりませんでした。お手数ですが教えてもらえるとありがたいです
    – user23690
    2017年8月18日 22:20

1 件の回答 1

0

TensorFlow Python API r1.3 によると、tf.Session クラスの run メソッドにはオプション引数として feed_dict を持っています。これは辞書型の引数で、その役割は下のように説明されています。

The optional feed_dict argument allows the caller to override the value of tensors in the graph. Each key in feed_dict can be one of the following types:

  • If the key is a tf.Tensor, the value may be a Python scalar, string, list, or numpy ndarray that can be converted to the same dtype as that tensor. Additionally, if the key is a tf.placeholder, the shape of the value will be checked for compatibility with the placeholder.
  • If the key is a tf.SparseTensor, the value should be a tf.SparseTensorValue.
  • If the key is a nested tuple of Tensors or SparseTensors, the value should be a nested tuple with the same structure that maps to their corresponding values as above.

これを和訳してみました。

オプション引数 feed_dict を使うと、グラフ中のテンソルの値を上書きすることができます。feed_dict 中のキーと値の型は、以下のいずれかにすることができます。

  • キーが tf.Tensor のとき、値は Python のスカラー、string、list、あるいは numpy ndarray であって、テンソルと同じ dtype に変換可能なものであれば良いです。更に、もしキーが tf.placeholder であるなら、値の shape が placeholder と合うかどうかチェックされます。
  • キーが tf.SparseTensor のとき、値は tf.SparseTensorValue であるべきです。
  • キーが TensorSparseTensor たちのネストしたタプルのとき、値はそれと同じ形をしたタプルで、それぞれのテンソルを上に書いてあるような値にうつすようなものであるべきです。

さて、今計算しようとしているのは以下の式でした。

x_data = tf.placeholder(tf.float32)
m_const = tf.constant(3.)
my_product = tf.multiply(x_data, m_const)

これはつまり、<float32型の何か> × 3.0 を計算しようとしているわけです。

今回のプログラムにおける feed_dict は、式の中に空いた穴(プレイスホルダー)であるところの <float32型の何か> を何にするかということを設定しています。

プログラム中の for ループは、プレイスホルダーに入れる値を変えながら上の式を計算しています。たとえば1回目のループでは x_val1.0 になるので、

run(my_product, feed_dict={x_data: 1.0})

が実行され、1.0 × 3.0 が計算されることになります。

なお、これはマニュアルに書いてある1つ目の場合、つまり、キーが tf.placeholder というテンソル、値が Python スカラーの場合にあたります。

1
  • ありがとうございます。
    – user23690
    2017年8月22日 23:51

この質問に回答するには、ログインする必要があります。

求めていた回答ではありませんか? のタグが付いた他の質問を参照する。