Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 361
user10282036 Avatar asked Oct 15 '18 12:10

user10282036


People also ask

How do I turn a NumPy array into a 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.

Which of the following will be used to convert NumPy array to TensorFlow tensor?

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.

How do you convert a list into 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.


1 Answers

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.

like image 144
Matias Haeussler Avatar answered Sep 23 '22 01:09

Matias Haeussler