运行 如何在张量会话中在一行中同时进行多项操作?

How run multiple operation together in one line in tensor session?

我正在学习 tensorflow,首先我有两个问题,是否有必要 运行 会话中的每个操作?就像我创建一个简单的程序,其中有三个操作加法和减法以及矩阵乘法那么是否有必要 运行 在会话中进行所有这些操作?

import tensorflow as tf
import numpy as np
import os
os.environ["TF_CPP_MIN_LOG_LEVEL"]="3"
a=np.array([[1,2,3],[4,5,6],[5,6,7]],dtype="float32")
b=np.array([[7,8,9],[9,6,5],[6,7,8]],dtype="float32")
ab=tf.Variable(a)
bb=tf.constant(b)
inn=tf.global_variables_initializer()
add=ab+bb
sub=(ab-bb)

mul=tf.matmul(a,b)
with tf.Session() as rr:
    rr.run(inn)
    rr.run(ab)
    res=rr.run(mul)
    print(res)

所以现在我必须 运行 会话中的每个操作(add、sub 和 matmul)??

如果 "yes" 我必须 运行 那么我可以 运行 所有这些操作一起进行吗?我试过了,但出现错误:

首先我尝试了这个:

import tensorflow as tf
import numpy as np
import os
os.environ["TF_CPP_MIN_LOG_LEVEL"]="3"
a=np.array([[1,2,3],[4,5,6],[5,6,7]],dtype="float32")
b=np.array([[7,8,9],[9,6,5],[6,7,8]],dtype="float32")
ab=tf.Variable(a)
bb=tf.constant(b)
inn=tf.global_variables_initializer()
add=ab+bb
sub=(ab-bb)

mul=tf.matmul(a,b)
with tf.Session() as rr:
    rr.run(inn,ab,add,sub,mul)
    rr.run(ab)
    res=rr.run(mul)
    print(res)

我收到这个错误:

TypeError: run() takes from 2 to 5 positional arguments but 6 were given

所以我从 运行 中删除了一个参数 (mul) 然后我得到了这个错误:

 raise TypeError("Using a `tf.Tensor` as a Python `bool` is not allowed. "
    TypeError: Using a `tf.Tensor` as a Python `bool` is not allowed. Use `if t is not None:` instead of `if t:` to test if a tensor is defined, and use TensorFlow ops such as tf.cond to execute subgraphs conditioned on the value of a tensor.

我如何才能 运行 所有操作一次,或者我必须 运行 每个单独操作?

在编写此代码的第二个过程中,我尝试将两个矩阵与形状 [2,3] 相乘,我的程序是:

import tensorflow as tf
import numpy as np
import os
os.environ["TF_CPP_MIN_LOG_LEVEL"]="3"
a=np.array([[1,2,3],[4,5,6]],dtype="float32")
b=np.array([[7,8,9],[9,6,5]],dtype="float32")
ab=tf.Variable(a)
bb=tf.constant(b)
inn=tf.global_variables_initializer()
add=ab+bb
sub=(ab-bb)

mul=tf.matmul(a,b)
with tf.Session() as rr:
    rr.run(inn)
    rr.run(ab)
    res=rr.run(mul)
    print(res)

我收到这个错误:

ValueError: Dimensions must be equal, but are 3 and 2 for 'MatMul' (op: 'MatMul') with input shapes: [2,3], [2,3].

如何乘 a=([1,2,3],[4,5,6]) b= ([9,8,7],[6,4,3]) ??

回答第一个问题,是的,所有内容 运行 都在一个会话中。您定义一个图形,然后会话是在图形被编译、加载到 tensorflow 内部并执行时,只要会话打开,所有变量的状态就会保持不变。

不过你的代码有点奇怪。您将其中一个输入定义为常量,而将另一个输入定义为变量,但变量永远不会改变。但在最基本的层面上,您可以 运行 通过将多个操作作为列表传递来在一个会话中进行多个操作。方法如下:

a=np.array([[1,2,3],[4,5,6]],dtype="float32")
b=np.array([[7,8,9],[9,6,5]],dtype="float32")
tfa = tf.constant(a)
tfb = tf.constant(b)
add = tfa + tfb
sub = tfa - tfb
with tf.Session() as s:
    res_add, res_sub = s.run([add, sub])
print(res_add)
print(res_sub)

输出为

[[  8.  10.  12.]
 [ 13.  11.  11.]]
[[-6. -6. -6.]
 [-5. -1.  1.]]

您的矩阵乘法将不起作用,因为内部维度必须匹配。这是否回答了您的问题,或者您是否在尝试做其他事情?