20

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?

Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
user10282036
  • 321
  • 2
  • 5
  • 13

2 Answers2

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.

Matias Haeussler
  • 1,061
  • 2
  • 12
  • 25
  • 1
    A variable isn't the same as a tensor according to Keras's documentation. >>> keras_var = K.variable(np_var)`
    >>> K.is_keras_tensor(keras_var) # A variable is not a Tensor.
    False
    >>> keras_placeholder = K.placeholder(shape=(2, 4, 5))
    >>> K.is_keras_tensor(keras_placeholder) # A placeholder is a Tensor.
    True
    – KareemJ Oct 09 '19 at 15:28
  • 1
    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 – Matias Haeussler Oct 09 '19 at 21:31
  • This is just perfect! Thank you – Ashwin Balani Apr 27 '20 at 15:29
4

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