Search code examples
kerasconv-neural-network

ValueError: Failed to convert a NumPy array to a Tensor


I used `

x_train = np.array([np.array(val) for val in x_train])
y_train = np.array([np.array(val) for val in y_train])

` but I failed to convert numpy to tensor

My code is `

x_train = np.array([np.array(val) for val in x_train])
y_train = np.array([np.array(val) for val in y_train])
model.fit(x_train,y_train,epochs =5,batch_size = 128,validation_split = 0.2,shuffle =True)
test_loss,test_acc = model.evaluate(x_test,y_test)
print('Test loss',test_loss)
print('Accuracy',test_acc)

` Error:

ValueError                                Traceback (most recent call last)
<ipython-input-39-43fd775bb14b> in <module>
      1 x_train = np.array([np.array(val) for val in x_train])
      2 y_train = np.array([np.array(val) for val in y_train])
----> 3 model.fit(x_train,y_train,epochs =5,batch_size = 128,validation_split = 0.2,shuffle =True)
      4 test_loss,test_acc = model.evaluate(x_test,y_test)
      5 print('Test loss',test_loss)

1 frames
/usr/local/lib/python3.7/dist-packages/tensorflow/python/framework/constant_op.py in convert_to_eager_tensor(value, ctx, dtype)
    100       dtype = dtypes.as_dtype(dtype).as_datatype_enum
    101   ctx.ensure_initialized()
--> 102   return ops.EagerTensor(value, ctx.device_name, dtype)
    103 
    104 

ValueError: Failed to convert a NumPy array to a Tensor (Unsupported object type numpy.ndarray).

My model: `

model = tf.keras.Sequential([
    tf.keras.layers.Embedding(words,embed_size,input_shape =(x_train.shape[0],)),
    tf.keras.layers.Conv1D(128,3,activation = 'relu'),
    tf.keras.layers.MaxPooling1D(),
    tf.keras.layers.LSTM(128,activation = 'tanh'),
    tf.keras.layers.Dense(10,activation='relu',input_dim=300),
    tf.keras.layers.Dense(1,activation='sigmoid',input_dim=300) ])

model.summary()

`


Solution

  • The error you are getting is because of the data type of an array, as Tensorflow models do not support Object data type, So, try to cast these tensors. I am casting it to float32.

    x_train = np.array([np.array(val) for val in x_train])
    y_train = np.array([np.array(val) for val in y_train])
    
    x_train = tf.cast(x_train , dtype=tf.float32)
    y_train = tf.cast(y_train , dtype=tf.float32)