15
votes

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?

2
Did you try this? - Sheldore
Thank you, Bazingaa. I am using Keras. Is there a way for keras tensor? - user10282036
Ok, I was just trying to Google on your behalf for this problem. Perhaps try this using .variable - Sheldore
Thank you, Bazingaa. It does not work. - user10282036
hi, can you provide a little more context? here you can find some good suggestions to help us help you - fr_andres

2 Answers

17
votes

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.

0
votes

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