Tensorflow: EagerTensor を numpy 配列に変換するにはどうすればいいですか? 質問する

Tensorflow: EagerTensor を numpy 配列に変換するにはどうすればいいですか? 質問する

標準の Tensorflow の場合:

import tensorflow as tf

x = tf.convert_to_tensor([0,1,2,3,4], dtype=tf.int64)
y = x + 10

sess = tf.InteractiveSession()
sess.run([
    tf.local_variables_initializer(),
    tf.global_variables_initializer(),
])
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(coord=coord)

z = y.eval(feed_dict={x:[0,1,2,3,4]})
print(z)          # [10 11 12 13 14]
print(type(z))    # <class 'numpy.ndarray'>

coord.request_stop()
coord.join(threads)
sess.close()

熱心な実行により:

import tensorflow as tf

tf.enable_eager_execution() # requires r1.7

x = tf.convert_to_tensor([0,1,2,3,4], dtype=tf.int64)
y = x + 10

print(y)        # tf.Tensor([10 11 12 13 14], shape=(5,), dtype=int64)
print(type(y))  # <class 'EagerTensor'>

を試してみるとy.eval()、 になりますNotImplementedError: eval not supported for Eager Tensors。これを変換する方法はないのでしょうか? これにより、Eager Tensorflow はまったく役に立たなくなります。

tf.make_ndarrayテンソルを NumPy 配列に変換する関数がありますが、その結果、次の問題が発生しますAttributeError: 'EagerTensor' object has no attribute 'tensor_shape'

ベストアンサー1

.numpy()使用できる関数がありますが、代わりに を実行することもできますnumpy.array(y)。例:

import tensorflow as tf
import numpy as np

tf.enable_eager_execution()

x = tf.constant([1., 2.])
print(type(x))            # <type 'EagerTensor'>
print(type(x.numpy()))    # <type 'numpy.ndarray'>
print(type(np.array(x)))  # <type 'numpy.ndarray'>

見る熱心な実行ガイドのセクション

おすすめ記事