'(Keras) ValueError: Failed to convert a NumPy array to a Tensor (Unsupported object type float)
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!!!
Solution 1:[1]
Try inserting dtype=np.float
when creating the np
array:
np.array(*your list*, dtype=np.float)
Solution 2:[2]
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']
Solution 3:[3]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Kamran |
Solution 2 | Pavel Fedotov |
Solution 3 | mike g |