[python] TensorFlow에서 텐서를 numpy 배열로 변환하는 방법은 무엇입니까?

Python 바인딩과 함께 Tensorflow를 사용할 때 텐서를 numpy 배열로 변환하는 방법은 무엇입니까?



답변

텐서 는 NumPy 배열에 의해 반환 Session.run되거나 반환됩니다 eval.

>>> print(type(tf.Session().run(tf.constant([1,2,3]))))
<class 'numpy.ndarray'>

또는:

>>> sess = tf.InteractiveSession()
>>> print(type(tf.constant([1,2,3]).eval()))
<class 'numpy.ndarray'>

또는 동등하게 :

>>> sess = tf.Session()
>>> with sess.as_default():
>>>    print(type(tf.constant([1,2,3]).eval()))
<class 'numpy.ndarray'>

편집 : 어떤 텐서가 반환 하지 Session.run않거나 eval()NumPy 배열입니다. 예를 들어 스파 스 텐서는 SparseTensorValue로 반환됩니다.

>>> print(type(tf.Session().run(tf.SparseTensor([[0, 0]],[1],[1,2]))))
<class 'tensorflow.python.framework.sparse_tensor.SparseTensorValue'>


답변

텐서에서 numpy 배열로 다시 변환하려면 변환 된 텐서를 실행 .eval()하면됩니다.


답변

텐서 플로우 2.x

Eager Execution 은 기본적으로 활성화되어 있으므로 .numpy()Tensor 객체를 호출 하십시오.

import tensorflow as tf

a = tf.constant([[1, 2], [3, 4]])
b = tf.add(a, 1)

a.numpy()
# array([[1, 2],
#        [3, 4]], dtype=int32)

b.numpy()
# array([[2, 3],
#        [4, 5]], dtype=int32)

tf.multiply(a, b).numpy()
# array([[ 2,  6],
#        [12, 20]], dtype=int32)

(문서에서) 주목할 가치가 있습니다.

Numpy array는 Tensor 객체와 메모리를 공유 할 수 있습니다. 하나의 변경 사항은 다른 하나에 반영 될 수 있습니다.

대담한 강조 광산. 사본이 반환되거나 반환되지 않을 수 있으며 이는 구현 세부 사항입니다.


Eager Execution이 비활성화 된 경우 그래프를 작성한 후 다음을 통해 실행할 수 있습니다 tf.compat.v1.Session.

a = tf.constant([[1, 2], [3, 4]])
b = tf.add(a, 1)
out = tf.multiply(a, b)

out.eval(session=tf.compat.v1.Session())
# array([[ 2,  6],
#        [12, 20]], dtype=int32)

또한보십시오 이전 API와 새 API의 맵핑에 대해서는 TF 2.0 기호 맵 을 .


답변

다음을 수행해야합니다.

  1. 이미지 텐서를 일부 형식 (jpeg, png)으로 이진 텐서로 인코딩
  2. 세션에서 이진 텐서를 평가 (실행)
  3. 바이너리를 스트림으로 바꾼다
  4. PIL 이미지로 피드
  5. (선택 사항) 이미지를 matplotlib로 표시

암호:

import tensorflow as tf
import matplotlib.pyplot as plt
import PIL

...

image_tensor = <your decoded image tensor>
jpeg_bin_tensor = tf.image.encode_jpeg(image_tensor)

with tf.Session() as sess:
    # display encoded back to image data
    jpeg_bin = sess.run(jpeg_bin_tensor)
    jpeg_str = StringIO.StringIO(jpeg_bin)
    jpeg_image = PIL.Image.open(jpeg_str)
    plt.imshow(jpeg_image)

이것은 나를 위해 일했습니다. ipython 노트북에서 사용해 볼 수 있습니다. 다음 줄을 추가하는 것을 잊지 마십시오.

%matplotlib inline


답변

이 방법을 시도해 볼 수 있습니다.

import tensorflow as tf
W1 = tf.Variable(tf.random_uniform([1], -1.0, 1.0))
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)
array = W1.eval(sess)
print (array)


답변

나는 영리한 도서관 / 튜토리얼로 얻은 (적대적인) 이미지를 나타내는 텐서의 특정 사례에서 텐서- > ndarray 변환에 직면하고 해결했습니다 .

내 질문 / 답변 ( here )이 다른 경우에도 유용한 예 라고 생각합니다 .

저는 TensorFlow를 처음 사용합니다. 경험적 결론입니다.

성공하기 위해서는 입력 자리 표시 자 값도 tensor.eval () 메서드가 필요할 수 있습니다 . 텐서는 feed_dict출력 값을 반환하기 위해 입력 값이 필요한 함수처럼 작동 할 수 있습니다.

array_out = tensor.eval(session=sess, feed_dict={x: x_input})

필자의 경우 자리 표시 자 이름은 x 이지만 입력 자리 표시 자의 올바른 이름을 찾아야한다고 가정합니다 .
x_input입력 데이터를 포함하는 스칼라 값 또는 배열입니다.

제 경우에는 또한 제공 sess이 필수적이었습니다.

내 예제는 matplotlib 이미지 시각화 부분 도 다루지 만 OT입니다.


답변

간단한 예는 다음과 같습니다.

    import tensorflow as tf
    import numpy as np
    a=tf.random_normal([2,3],0.0,1.0,dtype=tf.float32)  #sampling from a std normal
    print(type(a))
    #<class 'tensorflow.python.framework.ops.Tensor'>
    tf.InteractiveSession()  # run an interactive session in Tf.

이 텐서 a를 numpy 배열로 변환하려면 n

    a_np=a.eval()
    print(type(a_np))
    #<class 'numpy.ndarray'>

저것과 같이 쉬운!