What to do when I got this "NumPy array to a Tensor (Unsupported object type float)." in this specific situation?

Viewed 211

I have some doubts. I got data with some categorical and numerical features. Here the data

In general, there are 3 categorical variables, where 7 different types correspond to the variable p1, 2 types for p2, and 2 types for p3. From p4-p7 and product are numerical.

The libraries that I am using are:

 import pandas as pd 
 import numpy as np 
 import tensorflow as tf

 tf.__version__
 2.3.0

After I have determined the X data and y data (last column), I encoded the categorical ones.

from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import OneHotEncoder
ct= ColumnTransformer(transformers=[('encoder', OneHotEncoder(), [0,1,2])], remainder = 'passthrough')
X = np.array(ct.fit_transform(X))

I used that encoding type because the column-1 and column-2 are not numerical (these define the type of operation like 'batch' and 'continuous', or 'light' and 'dark'), the column 0 is related to specific substrates (organic compounds), some are complex(with unknown molecular weight) and the others are simple(with a molecular weight well known).

So from the result of that encoding, I got this:

enter image description here

As we see, each category has its own code, and the number of columns has increased. Now I have '15 columns'.

Then, I proceeded to split the data

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 1)

And I normalized only the original numerical data in X_train and X_test

from sklearn.preprocessing import MinMaxScaler
scalar = MinMaxScaler()
X_train[:,11:]=scalar.fit_transform(X_train[:,11:])
X_test[:,11:]=scalar.transform(X_test[:,11:]) 

Finally, I wanted to construct the ANN with the input layer, hidden layers, and one output layer.

ann = tf.keras.models.Sequential()
ann.add(tf.keras.layers.Dense(units=15, activation='relu'))
ann.add(tf.keras.layers.Dense(units=7, activation='relu'))
ann.add(tf.keras.layers.Dense(units=1))

After I have defined the structure of the ANN, I wanted to train

ann.compile(optimizer = 'adam', loss = 'mean_squared_error')

and the problem comes here

ann.fit(X_train, y_train, batch_size = 32, epochs = 100) 

Here it is showing me this:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-47-0ccb0e29ce49> in <module>()
----> 1 ann.fit(X_train, y_train, batch_size = 100, epochs = 728) # propagacion in batchs

13 frames
/usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/constant_op.py in 
convert_to_eager_tensor(value, ctx, dtype)
 96       dtype = dtypes.as_dtype(dtype).as_datatype_enum
 97   ctx.ensure_initialized()
---> 98   return ops.EagerTensor(value, ctx.device_name, dtype)
 99 
100 

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

So, How can I solve this?

1 Answers

You can resolve the issue by doing a Numpy conversion as below while fit method.

ann.fit(np.asarray(X_train,dtype=np.float32), np.asarray(y_train,dtype=np.float32), batch_size = 32, epochs = 100)  

Or as @4.Pi.n suggested in the comment you can change the dtype to float32 using the below code.

ann.fit(X_train.astype('float32'), y_train.astype('float32'), batch_size = 32, epochs = 100)
Related