programing tip

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

itbloger 2020. 6. 25. 21:26
반응형

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.0

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

import tensorflow as tf

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

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)

I have faced and solved the tensor->ndarray conversion in the specific case of tensors representing (adversarial) images, obtained with cleverhans library/tutorials.

I think that my question/answer (here) may be an helpful example also for other cases.

I'm new with TensorFlow, mine is an empirical conclusion:

It seems that tensor.eval() method may need, in order to succeed, also the value for input placeholders. Tensor may work like a function that needs its input values (provided into feed_dict) in order to return an output value, e.g.

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

Please note that the placeholder name is x in my case, but I suppose you should find out the right name for the input placeholder. x_input is a scalar value or array containing input data.

In my case also providing sess was mandatory.

My example also covers the matplotlib image visualization part, but this is OT.


A simple example could be,

    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.

n now if we want this tensor a to be converted into a numpy array

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

As simple as that!

참고URL : https://stackoverflow.com/questions/34097281/how-can-i-convert-a-tensor-into-a-numpy-array-in-tensorflow

반응형