11

I know this problem has been answered previously in the link below,but it does not apply to my situation.(Tensorflow - ValueError: Failed to convert a NumPy array to a Tensor (Unsupported object type float))

Both my predictor (X) and target variables (y) are <class 'numpy.ndarray'> and their shapes are X: (8981, 25) y: (8981, 1)

Yet, I am still getting the error message. ValueError: Failed to convert a NumPy array to a Tensor (Unsupported object type float).

Please refer to the following code:

import tensorflow as tf
ndim = X.shape[1]
model = tf.keras.models.Sequential()
# model.add(tf.keras.layers.Flatten())
model.add(tf.keras.layers.Dense(36, activation = tf.nn.relu, input_dim=ndim))
model.add(tf.keras.layers.Dense(36, activation = tf.nn.relu))
model.add(tf.keras.layers.Dense(2, activation = tf.nn.softmax))
model.compile(optimizer = 'adam',
              loss = 'sparse_categorical_crossentropy',
              metrics = ['accuracy'])
model.fit(X.values, y, epochs = 5)
y_pred = model.predict([X_2019])

Any help will be really appreciated! Thanks!!!

Pavel Fedotov
  • 301
  • 3
  • 15
RonSg83
  • 111
  • 1
  • 1
  • 3

3 Answers3

16

Try inserting dtype=np.float when creating the np array:

np.array(*your list*, dtype=np.float)
Kamran
  • 796
  • 11
  • 34
Jacopo
  • 158
  • 6
3

Some of my columns were categorical. Try printing X.dtypes and checking if any of the entries are as type 'object'. Another helpful command: X[X.dtypes=='object']

Pavel Fedotov
  • 301
  • 3
  • 15
Surya Narayanan
  • 309
  • 4
  • 6
0

I had this error message too. My problem was there were few NULL characters in my input file which I imported into the dataframe that fed Keras/tensorflow.

I knew there were NULLs because:

df.isnull().any()    ## check for nulls ... should say False

... told me there were NULLS (i.e TRUE)

To remove the offending NULLs, I used this:

df = df.dropna(how='any',axis=0) 

... where df was my numpy dataframe.

After that my model.fit ran nicely!

Of course, the error message "Failed to convert a NumPy array to a Tensor (Unsupported object type float)" could have many causes.

My root problem was funky input data. The code above fixed it.

mike g
  • 11
  • 2