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?
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?
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
.
>>> 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
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