简体   繁体   中英

How to convert tensor to ndarray

I'm beginner of tensorflow. The yolo_model.predict returns tensor.But when i use cpu_nms, i need to convert pred_boxes and pred_scores to ndarray. I have tried using .eval () but I get some FailedPreconditionError.

'''

img = np.asarray(img, np.float32)
img = img[np.newaxis, :] / 255.

with tf.Session() as sess:

    input_data = tf.placeholder(tf.float32, [1, args.new_size[1], args.new_size[0], 3], name='input_data')
    yolo_model = yolov3(args.num_class, args.anchors)
    with tf.variable_scope('yolov3'):
        pred_feature_maps = yolo_model.forward(input_data, False)

    pred_boxes, pred_confs, pred_probs = yolo_model.predict(pred_feature_maps)

    pred_scores = pred_confs * pred_probs
    # pred_boxes = pred_boxes.eval()
    # pred_scores = pred_scores.eval()

    boxes, scores, labels = cpu_nms(pred_boxes, pred_scores, args.num_class, max_boxes=200, score_thresh=0.3, iou_thresh=0.45)

    saver = tf.train.Saver()
    saver.restore(sess, args.restore_path)

    boxes_, scores_, labels_ = sess.run([boxes, scores, labels], feed_dict={input_data: img})

''' Thanks!

If you are extracting variable tensor and then to an array, then below are the example for different versions of tensorflow.

If you would like to extract the value in tensorflow version 1.14 OR other versions that support session , then below is an example -

#!pip install tensorflow==1.14

import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np
import time

print("tensorflow version:",tf.__version__)

def make_discriminator_model():
    model = tf.keras.Sequential()
    model.add(tf.keras.layers.Conv2D(7,(3,3) , padding = "same" , input_shape = (28,28,1)))
    model.add(tf.keras.layers.Flatten())
    model.add(tf.keras.layers.LeakyReLU())
    model.add(tf.keras.layers.Dense(50,activation = 'relu'))
    model.add(tf.keras.layers.Dense(1))
    return model 

model_discriminator = make_discriminator_model()
output = model_discriminator(np.random.rand(1,28,28,1).astype("float32"))

#initialize the variable
init_op = tf.initialize_all_variables()

#run the graph
with tf.Session() as sess:
    sess.run(init_op) #execute init_op
    print("Output as a Tensor:",output)
    out = np.array(sess.run(output))
    print("Output as an Array:",out)
    print("Type of the Array:",type(out))

Output will be -

tensorflow version: 1.14.0
Output as a Tensor: Tensor("sequential_7/dense_15/BiasAdd:0", shape=(1, 1), dtype=float32)
Output as an Array: [[-0.29746282]]
Type of the Array: <class 'numpy.ndarray'>

If you would like to extract the value in tensorflow version 2.1 OR other versions that supports tensor print , then below is an example -

#!pip install tensorflow==2.1

import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np

print("tensorflow version:",tf.__version__)

def make_discriminator_model():
    model = tf.keras.Sequential()
    model.add(tf.keras.layers.Conv2D(7,(3,3) , padding = "same" , input_shape = (28,28,1)))
    model.add(tf.keras.layers.Flatten())
    model.add(tf.keras.layers.LeakyReLU())
    model.add(tf.keras.layers.Dense(50,activation = 'relu'))
    model.add(tf.keras.layers.Dense(1))
    return model 

model_discriminator = make_discriminator_model()
output = model_discriminator(np.random.rand(1,28,28,1).astype("float32"))
print("Output as a Tensor:",output)

out = np.array(output)
print("Output as an Array:",out)
print("Type of the Array:",type(out))

Output will be -

tensorflow version: 2.1.0
Output as a Tensor: tf.Tensor([[0.32392436]], shape=(1, 1), dtype=float32)
Output as an Array: [[0.32392436]]
Type of the Array: <class 'numpy.ndarray'>

NOTE: There are symbolic and variable tensor, you can understand the difference between them here - Symbolic Tensor Vs Variable Tensor

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM