TensorFlow learning process record (2) -- basic use (2) -- interactive use

2. Interactive use

In the previous example we used the Session to start the graph and called the Session.run method to execute the op.
To facilitate the use of a Python interactive environment such as IPython, the InteractiveSession can be used instead of the Session class, and the Tensor.eval() and Operation.run() methods can be used instead of Session.run(). This avoids using a variable to hold the session.

# coding=utf-8

# 进入一个交互式 TensorFlow 会话.
import tensorflow as tf
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'

sess = tf.InteractiveSession()

x = tf.Variable([1.0, 2.0])
a = tf.constant([3.0, 3.0])

# 使用初始化器 initializer op 的 run() 方法初始化 'x'
x.initializer.run()

# 增加一个加法 add op, 从 'x' 加上 'a'. 运行加法 op, 输出结果
# sub = tf.sub(x, a)
add = tf.add(x, a)
print(add.eval())
# ==> [4. 5.]

The document gives the subtraction sub = tf.sub(x, a), but running the subtraction will report an error:
write picture description here
after viewing the original code, it is found that sub() is changed to subtract()
write picture description here
to get the result:
write picture description here

 …
this is a small episode ha, the topic of this section is "interactive use", not code issues. .

The InteractiveSession class is a user interactive context for TensorFlow Session. Like a shell. Unlike regular sessions, InteractiveSession installs itself as the default session in the constructor. The @{tf.Tensor.eval} and @{tf.Operation.run} methods will use this session to run ops.
This is handy in interactive shells and [IPython notebooks], as it avoids having to run ops through an explicit "session" object.
for example:

  sess = tf.InteractiveSession()
  a = tf.constant(5.0)
  b = tf.constant(6.0)
  c = a * b
  # 我们可以使用'c.eval()' 而不用 'sess'
  print(c.eval())
  sess.close()

Note that the regular session itself is used as the default session when created in the "with" statement.
A common approach in non-interactive programs is to follow this pattern:

  a = tf.constant(5.0)
  b = tf.constant(6.0)
  c = a * b
  with tf.Session():
    # 这里也能使用 'c.eval()'
    print(c.eval())

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325764114&siteId=291194637