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

2024-09-28 05:22:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在学习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)??在

如果“是”我必须运行,那么我可以一起运行所有这些操作吗?我试过了,但我出错了:

首先我试了一下:

^{pr2}$

我有个错误:

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

所以我从run中删除了一个参数(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])??在


Tags: runimportabostfasnprr
1条回答
网友
1楼 · 发布于 2024-09-28 05:22:30

要回答第一个问题,是的,一切都在一个会话中运行。你定义了一个图,然后会话是当图形被编译,加载到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)

输出是

^{pr2}$

你的矩阵乘法是行不通的,因为内部尺寸必须匹配。这个回答了你的问题,还是你想做别的什么?在

相关问题 更多 >

    热门问题