Recommended comparison reading:

  1. · Understanding Numpy, Tensor and Variable in PyTorch
  2. “Take you to AI” takes you to AI and TensorFlow2 combat introduction: How to fast deep Learning development

Since TensorFlow is currently in the process of updating version 2.0, bloggers have also added a dynamic attitude conversion method for their blogs for version 2.0, updated at 2019/09 //29

Figure 1 numpy Figure 2 tensorflow

– Problem Description

When we use TensorFlow for deep learning training, most of the time we are greeted with Numpy data, such as CSV or photo data. But we all know that TensorFlow training uses Tensor to store variables, and that the net output is also Tensor.

Normally we don’t know the difference between Numpy and Tensor, because TensorFlow automatically translates Numpy data into Tensor. But when you output the network, you still have a Tensor output, and when you use that output to do things that can only be done with Numpy data you get some weird errors.

For example, I get an error when I try to use Matplotlib to display the output of the autoencoder and decoder

TypeError: Image data cannot be converted to float
Copy the code

The solution

TF 1. X version

Sometimes the solution is simple, but errors are hard to find, so I recommend explicitly converting the data.

  • Numpy2Tensor

TensorFlow will automatically translate Numpy data into Tensor, but we can also translate it explicitly:

data_tensor= tf.convert_to_tensor(data_numpy)
Copy the code
  • Tensor2Numpy

The net output is still at Tensor, and when we use it to perform operations that can only be done with Numpy data we get some weird errors. Solutions:

with tf.Session() as sess:
    data_numpy = data_tensor.eval()
Copy the code

TF 2.x version (Updated at 2019//09//29)

  • Numpy2Tensor (same as 1.x version)

TensorFlow will automatically translate Numpy data into Tensor, but we can also translate it explicitly:

data_tensor= tf.convert_to_tensor(data_numpy)
Copy the code
  • Tensor2Numpy

The net output is still at Tensor, and when we use it to perform operations that can only be done with Numpy data we get some weird errors. The tensor will have to translate.numpy() into a tensor:

data_numpy = data_tensor.numpy()
Copy the code

At the same time, we recommend you to follow the author’s public account “Minimalist AI” (ID: BriefAI) to discuss the theory and application development technology of learning deep learning.

Welcome to xiao Song’s official account ** “Minimalist AI” ** Take you to learn deep learning:

Based on the sharing of theoretical learning and application development technology of deep learning, the author will often share the dry contents of deep learning. When learning or applying deep learning, you can also communicate with me on this page if you have any questions.

From CSDN blog expert & Zhihu deep learning columnist @Xiaosong yes