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?
a NumPy array is created by using the np. array() method. The NumPy array is converted to tensor by using tf. convert_to_tensor() method.
How to convert a numpy array to tensor? To achieve this we have a function in tensorflow called "convert_to_tensor", this will convert the given value into a tensor. The value can be a numpy array, python list and python scalars, for the following the function will return a tensor.
To convert a Python list to a tensor, we are going to use the tf. convert_to_tensor() function and this function will help the user to convert the given object into a tensor. In this example, the object can be a Python list and by using the function will return a tensor.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With