21

When using the keras model to do predict, I got the error below

AttributeError: 'Tensor' object has no attribute 'ndim'

The reason is that the weights is numpy array, not tensor.
So how to convert numpy array to keras tensor?

6
  • Did you try this? Commented Oct 15, 2018 at 12:50
  • Thank you, Bazingaa. I am using Keras. Is there a way for keras tensor? Commented Oct 15, 2018 at 13:28
  • Ok, I was just trying to Google on your behalf for this problem. Perhaps try this using .variable Commented Oct 15, 2018 at 13:54
  • Thank you, Bazingaa. It does not work. Commented Oct 15, 2018 at 14:35
  • hi, can you provide a little more context? here you can find some good suggestions to help us help you Commented Nov 8, 2018 at 3:37

2 Answers 2

19

In Tensorflow it can be done the following way:

import tensorflow.keras.backend as K
import numpy as np

a = np.array([1,2,3])
b = K.constant(a)
print(b)

# <tf.Tensor 'Const_1:0' shape=(3,) dtype=float32>

print(K.eval(b))

# array([1., 2., 3.], dtype=float32)

In raw keras it should be done replacing import tensorflow.keras.backend as K with from keras import backend as K.

Sign up to request clarification or add additional context in comments.

2 Comments

A variable isn't the same as a tensor according to Keras's documentation. <code> >>> keras_var = K.variable(np_var)` <br> >>> K.is_keras_tensor(keras_var) # A variable is not a Tensor.<br> False<br> >>> keras_placeholder = K.placeholder(shape=(2, 4, 5))<br> >>> K.is_keras_tensor(keras_placeholder) # A placeholder is a Tensor.<br> True<br> </code>
You are right, I have just updated my answer to use K.constant() instead of K.variable(), it returns a tensor instead of a variable as print() says
6

To convert numpy array to tensor,

import tensor as tf
#Considering y variable holds numpy array
y_tensor = tf.convert_to_tensor(y, dtype=tf.int64) 

#You can use any of the available datatypes that suits best - https://www.tensorflow.org/api_docs/python/tf/dtypes/DType

1 Comment

also you can use import tensorflow as tf

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.