Tensorflow2.0 - How to convert Tensor to numpy() array

Written by - Aionlinecourse1459 times views

You can use the .numpy() method of a Tensor to convert it to a NumPy array. Here's an example:


import tensorflow as tf

# Create a Tensor
tensor = tf.constant([[1, 2], [3, 4]])

# Convert the Tensor to a NumPy array
array = tensor.numpy()

print(array)  # prints [[1 2] [3 4]]

Keep in mind that this method returns a NumPy array with a copy of the data in the Tensor. If you want to avoid the overhead of copying the data, you can use the tf.Tensor.experimental_memory_efficient_forwarding property, which returns a view of the Tensor as a NumPy array without copying the data. Here's an example:

import tensorflow as tf

# Create a Tensor
tensor = tf.constant([[1, 2], [3, 4]])

# Get a view of the Tensor as a NumPy array without copying the data
array = tensor.experimental_memory_efficient_forwarding

print(array)  # prints [[1 2] [3 4]]

Note that this property is experimental and may not always be available.

Recommended Projects

Deep Learning Interview Guide

Topic modeling using K-means clustering to group customer reviews

Have you ever thought about the ways one can analyze a review to extract all the misleading or useful information?...

Natural Language Processing
Deep Learning Interview Guide

Medical Image Segmentation With UNET

Have you ever thought about how doctors are so precise in diagnosing any conditions based on medical images? Quite simply,...

Computer Vision
Deep Learning Interview Guide

Build A Book Recommender System With TF-IDF And Clustering(Python)

Have you ever thought about the reasons behind the segregation and recommendation of books with similarities? This project is aimed...

Machine LearningDeep LearningNatural Language Processing
Deep Learning Interview Guide

Automatic Eye Cataract Detection Using YOLOv8

Cataracts are a leading cause of vision impairment worldwide, affecting millions of people every year. Early detection and timely intervention...

Computer Vision
Deep Learning Interview Guide

Crop Disease Detection Using YOLOv8

In this project, we are utilizing AI for a noble objective, which is crop disease detection. Well, you're here if...

Computer Vision
Deep Learning Interview Guide

Vegetable classification with Parallel CNN model

The Vegetable Classification project shows how CNNs can sort vegetables efficiently. As industries like agriculture and food retail grow, automating...

Machine LearningDeep Learning
Deep Learning Interview Guide

Banana Leaf Disease Detection using Vision Transformer model

Banana cultivation is a significant agricultural activity in many tropical and subtropical regions, providing a vital source of income and...

Deep LearningComputer Vision