Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Convert Tensor to numpy array #40

Closed
nthakor opened this issue Jun 10, 2016 · 23 comments
Closed

Convert Tensor to numpy array #40

nthakor opened this issue Jun 10, 2016 · 23 comments

Comments

@nthakor
Copy link

nthakor commented Jun 10, 2016

I am trying to calculate ruc score after every epoch. For than the tensor object need to be converted to numpy array.
Following is the code I am trying.


# Launch the graph
with tf.Session() as sess:
    sess.run(init)

    # Training cycle
    for epoch in range(training_epochs):
        avg_cost = 0.
        total_batch = int(len(trX)/batch_size)
        # Loop over all batches
        for i in range(total_batch):
            batch_x, batch_y = trX[batch_size*i:batch_size*(i+1)],trY[batch_size*i:batch_size*(i+1)]
            # Run optimization op (backprop) and cost op (to get loss value)
            _, c = sess.run([optimizer, cost], feed_dict={x: batch_x,
                                                          y: batch_y})
            # Compute average loss
            avg_cost += c / total_batch
        # Display logs per epoch step
        if epoch % display_step == 0:
            print "Epoch:", '%04d' % (epoch+1), "cost=", \
                "{:.9f}".format(avg_cost)
            print roc_auc_score(teY,pred)

    print "Optimization Finished!"
    # Test model
    correct_prediction = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))
    # Calculate accuracy
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
    print "Accuracy:", accuracy.eval({x: teX, y: teY})

It is giving following error:

TypeError: Expected sequence or array-like, got <class 'tensorflow.python.framework.ops.Tensor'>

Can you please tell how to convert tensor to numpy array.
I tried pred.eval() but it is showing error also.

@aymericdamien
Copy link
Owner

To convert a tensor to numpy array, you have to run:

array = your_tensor.eval(session=your_session)

@nthakor
Copy link
Author

nthakor commented Jun 14, 2016

Resolved Thanks.

@nthakor nthakor closed this as completed Jun 14, 2016
@fmigas
Copy link

fmigas commented Dec 9, 2017

Hello,
I have the same problem, but I need to convert a tensor to a numpy arran in keras (without a tensorflow session). Can you help?

@b18arundhati
Copy link

Hi!
I have the same problem. @fmigas did you find any solution?

@fmigas
Copy link

fmigas commented Dec 27, 2017 via email

@b18arundhati
Copy link

b18arundhati commented Dec 27, 2017 via email

@samensah
Copy link

@fmigas @b18arundhati Hi!, did you guys manage to find a solution on the conversion from the tensor to numpy array in Keras? I'm having the same problem.

@b18arundhati
Copy link

b18arundhati commented Jan 14, 2018 via email

@eavidan
Copy link

eavidan commented Feb 11, 2018

we are using Tensorflow Serving and I have written the following function to convert the PredictResponse (tensor) back to numpy array if it helps

def predictResponse_into_nparray(response, output_tensor_name):
    dims = response.outputs[output_tensor_name].tensor_shape.dim
    shape = tuple(d.size for d in dims)
    print(shape)
    return np.reshape(response.outputs[output_tensor_name].float_val, shape)

@jonathand94
Copy link

for evaluating a tensor in Keras use Keras backend function "eval()" --> K.eval(my_tensor)
Check for documentation: https://keras.io/backend/

@ParekhVivek09
Copy link

Hi,@b18arundhati did you find any solution regarding this. I have the same environment in Keras.

@bfonta
Copy link

bfonta commented Jul 18, 2018

Try the following:

import tensorflow as tf
from tensorflow.python.keras import backend as K
sess = K.get_session()
array = sess.run(your_tensor)

@emnajaoua
Copy link

emnajaoua commented Sep 5, 2018

@b18arundhati can you please tell us what is your workaround. I am using tensor objects under keras, I want to convert them to arrays or lists so I can use them as input for another function. the output of that other function is so necessary since I am using it to calculate the loss.
I tried the solutions of @b-fontana @jonathand94 but still I get this error:
InvalidArgumentError: You must feed a value for placeholder tensor 'Placeholder' with dtype float and shape [?,36]
[[Node: Placeholder = Placeholderdtype=DT_FLOAT, shape=[?,36], _device="/job:localhost/replica:0/task:0/device:CPU:0"]]

Any suggestions please ?

@bfonta
Copy link

bfonta commented Sep 5, 2018

Can you post a minimal working example, showing the tensor you want to evaluate?
Anyways, depending on how you defined the tensor "your_tensor", you might have to provide additional values for some placeholders. You are probably trying to evaluate a tensor that is not completely defined when you do 'sess.run()'.

@emnajaoua
Copy link

@b-fontana Thank you for your respond. In fact, my case is a bit complicated. I am defining a function that represent a custom loss. This function is using as inputs numpy arrays. So I was trying to evaluate my tensors to be numpy arrays so I can process this function but that was not possible. Because I have to fed an actual value to my tensors for that. a better explanation is in this link keras-team/keras#4075.
Anyway, now I am working on rewriting my custom loss function with keras symbols or operations.

@ShantanuShinde
Copy link

To convert a tensor to numpy array, you have to run:

array = your_tensor.eval(session=your_session)

I used this. but the program hangs at the eval(). what is the problem?

@bfonta
Copy link

bfonta commented Oct 19, 2018

@Gameatro:

Try the following:

for evaluating a tensor in Keras use Keras backend function "eval()" --> K.eval(my_tensor)
Check for documentation: https://keras.io/backend/

If this does not work, please paste a minimum working example so that we can reproduce your error.

@chhetrycse
Copy link

def dis(bin_image):

res=distance_transform_cdt(bin_image)

return res

out = Conv2D(1, (1, 1), activation='sigmoid') (c9)

print(out.shape)

#outputs = resize_layer(scale=2)(out, method="dis")

outputs=Lambda(dis)(out)

(?, 256, 256, 1)

ValueError Traceback (most recent call last)
in ()
----> 1 get_net = base_model()

in base_model(IMG_WIDTH, IMG_HEIGHT, IMG_CHANNELS)
52 print(out.shape)
53 #outputs = resize_layer(scale=2)(out, method="dis")
---> 54 outputs=Lambda(dis)(out)
55
56 model = Model(inputs=[inputs], outputs=[outputs])

/usr/local/lib/python3.6/dist-packages/keras/engine/base_layer.py in call(self, inputs, **kwargs)
455 # Actually call the layer,
456 # collecting output(s), mask(s), and shape(s).
--> 457 output = self.call(inputs, **kwargs)
458 output_mask = self.compute_mask(inputs, previous_mask)
459

/usr/local/lib/python3.6/dist-packages/keras/layers/core.py in call(self, inputs, mask)
685 if has_arg(self.function, 'mask'):
686 arguments['mask'] = mask
--> 687 return self.function(inputs, **arguments)
688
689 def compute_mask(self, inputs, mask=None):

in dis(bin_image)
2 def dis(bin_image):
3
----> 4 res=distance_transform_cdt(bin_image)
5 return res

/usr/local/lib/python3.6/dist-packages/scipy/ndimage/morphology.py in distance_transform_cdt(input, metric, return_distances, return_indices, distances, indices)
2009 dt[...] = numpy.where(input, -1, 0).astype(numpy.int32)
2010 else:
-> 2011 dt = numpy.where(input, -1, 0).astype(numpy.int32)
2012
2013 rank = dt.ndim

ValueError: setting an array element with a sequence.

@jsl303
Copy link

jsl303 commented Apr 16, 2019

Hi Everyone,
I'm trying to implement a custom metric in Keras, and I'm also having the problem to convert Tensor to Numpy.
All of the options below throws the error: "You must feed a value for placeholder tensor 'dense_3_target' with dtype float and shape [?,?]"
Did anyone find a solution yet?

from tensorflow.keras import backend as K
def custom_accuracy(y_true, y_pred):
sess = K.get_session()
y_true_np = sess.run(y_true) #1
y_true_np = y_true.eval(session=sess) #2
y_true_np = K.eval(y_true) #3
y_true_np = K.get_value(y_true) #4

@ahmedhosny
Copy link

The loss function is part of the graph - I believe everything needs to be implemented using keras backend or tf functions i.e. operate on tensors not numpy arrays.

@huangjiancong1
Copy link

To convert a tensor to numpy array, you have to run:

array = your_tensor.eval(session=your_session)

I think array = your_tensor.eval(session=your_session) can not work if there have different placeholder defined,

there should be define feed_dict={} in some way?

@agarwala95
Copy link

@b18arundhati can you please tell us what is your workaround. I am using tensor objects under keras, I want to convert them to arrays or lists so I can use them as input for another function. the output of that other function is so necessary since I am using it to calculate the loss.
I tried the solutions of @b-fontana @jonathand94 but still I get this error:
InvalidArgumentError: You must feed a value for placeholder tensor 'Placeholder' with dtype float and shape [?,36]
[[Node: Placeholder = Placeholderdtype=DT_FLOAT, shape=[?,36], _device="/job:localhost/replica:0/task:0/device:CPU:0"]]

Any suggestions please ?

Did you solve this? I have the same problem

@ghost
Copy link

ghost commented Apr 21, 2020

I have the same problem, but no possible to debug it. I tried to use Keras backend as suggested, but it didn't work.

Here is a MWE:


import numpy  as np 
import tensorflow as tf
import scipy.optimize 


# fixed parameters
kon = 0.01
mu  = 1.5
fi  = 0.5 
kappa = 22
w = 0.63

# varying parameters 
n=10000
x0 = tf.random.normal(shape=(n,), stddev=0.2)
x0 =np.exp(x0)
eps = tf.random.normal(shape=(n,), stddev=0.17)
z = tf.sigmoid(tf.random.normal(shape=(n,), stddev=0.22))

@tf.function 
def get_leisure(z, eps, x0):
    e_eps = tf.exp(eps)
    e_x0 = x0
    c_1=mu/fi * np.ones(n)
    c_2=(1-mu)*kappa * np.ones(n)
    c_3= 1 + (1/fi)
    c_4=mu*np.log(w*e_eps*e_x0/kon)+np.log(z)
    def fun(x):
        return c_1[0] * np.log(x) - c_2[0] * ((x) ** c_3)-c_4
    hvec = scipy.optimize.newton_krylov(fun, 0.5 * np.ones(n))
    return hvec
   
get_leisure(z,eps,x0) 

NotImplementedError: in converted code:

    <ipython-input-65-5bb23bbd74cf>:8 get_leisure  *
        c_4=mu*np.log(w*e_eps*e_x0/kon)+np.log(z)
    /Users/usr/opt/anaconda3/envs/spyder/lib/python3.7/site-packages/tensorflow_core/python/framework/ops.py:728 __array__
        " array.".format(self.name))

    NotImplementedError: Cannot convert a symbolic Tensor (truediv:0) to a numpy array.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests