Session 在Tensorflow 2中以延迟模式计算张量

Session 在Tensorflow 2中以延迟模式计算张量,session,tensorflow2.0,Session,Tensorflow2.0,我想计算张量的平方。 常数=tf.常数([1,2,3]) tft=常数*常数 #https://www.tensorflow.org/api_docs/python/tf/compat/v1/Session sess = tf.compat.v1.Session() with sess.as_default(): print(tft.eval()) 但是,它返回以下错误: NotImplementedError:当执行时不支持eval 已启用,.numpy()是您要查找的吗 我知道我可以让

我想计算张量的平方。 常数=tf.常数([1,2,3]) tft=常数*常数

#https://www.tensorflow.org/api_docs/python/tf/compat/v1/Session
sess = tf.compat.v1.Session()
with sess.as_default():
  print(tft.eval())
但是,它返回以下错误:

NotImplementedError:当执行时不支持eval 已启用,.numpy()是您要查找的吗

我知道我可以让渴望的惩罚无效

导入tensorflow作为tf

tf.compat.v1.disable_eager_execution()
constant = tf.constant([1, 2, 3])
tft = constant*constant
print(tft)
但是,这将返回张量(“mul_4:0”,shape=(3,),dtype=int32),而不是实际值。请问我如何评价它


非常感谢您的帮助。

在TF2.x中,您可以在会话中使用评估张量,如下所示

import tensorflow as tf
print(tf.__version__)

with tf.compat.v1.Session() as sess:
  constant = tf.constant([1, 2, 3])
  tft = constant*constant
  print(tft.eval())
输出:

2.2.0
[1 4 9]
2.2.0
tf.Tensor([1 4 9], shape=(3,), dtype=int32)
[1 4 9]
还有一种没有会话的方法,通过将
tensor
转换为
numpy
以查看实际值来实现

import tensorflow as tf
import numpy as np
print(tf.__version__)

def tensor_to_array(array_value):
    return array_value.numpy()

constant = tf.constant([1, 2, 3])
tft = constant*constant

print(tft)
print(tensor_to_array(tft))
输出:

2.2.0
[1 4 9]
2.2.0
tf.Tensor([1 4 9], shape=(3,), dtype=int32)
[1 4 9]

在TF2.x中,您可以在会话中使用计算张量,如下所示

import tensorflow as tf
print(tf.__version__)

with tf.compat.v1.Session() as sess:
  constant = tf.constant([1, 2, 3])
  tft = constant*constant
  print(tft.eval())
输出:

2.2.0
[1 4 9]
2.2.0
tf.Tensor([1 4 9], shape=(3,), dtype=int32)
[1 4 9]
还有一种没有会话的方法,通过将
tensor
转换为
numpy
以查看实际值来实现

import tensorflow as tf
import numpy as np
print(tf.__version__)

def tensor_to_array(array_value):
    return array_value.numpy()

constant = tf.constant([1, 2, 3])
tft = constant*constant

print(tft)
print(tensor_to_array(tft))
输出:

2.2.0
[1 4 9]
2.2.0
tf.Tensor([1 4 9], shape=(3,), dtype=int32)
[1 4 9]