In Transfer Learning ValueError: Failed to convert a NumPy array to a Tensor

180 Views Asked by At

I am Practicing on Transfer Learning with Iris dataset.

For the following code I get the following error messege:

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

I Need help in solving this error.

Below the imported libraries

import pandas as pd
import io
import requests
import numpy as np
from sklearn import metrics
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Activation
from tensorflow.keras.callbacks import EarlyStopping

read the csv file using pandas

df = pd.read_csv("Iris.csv", na_values=['NA', '?'])
df.columns
#output of df.colums
Index(['Id', 'SepalLengthCm', 'SepalWidthCm', 'PetalLengthCm', 'PetalWidthCm',
       'Species'],
      dtype='object')

convert into numpy array for classification

x = df[['SepalLengthCm', 'SepalWidthCm', 'PetalLengthCm', 'PetalWidthCm', 'Species']].values
dummies  = pd.get_dummies(df['Species'])   #classification
species = dummies.columns
y = dummies.values

Build the Neural Network,

model = Sequential()
model.add(Dense(50, input_dim = x.shape[1], activation= 'relu'))   #Hidden Layer-->1
model.add(Dense(25, activation= 'relu'))     #Hidden Layer-->2
model.add(Dense(y.shape[1], activation= 'softmax'))     #Output

Compile the NN model

model.compile(loss ='categorical_crossentropy', optimizer ='adam')

Fit the model and Please concern in this part

model_fit=model.fit(x,y, verbose=2, epochs=10, steps_per_epoch=3)

Error is given below,

ValueError                                Traceback (most recent call last)
<ipython-input-48-0ff464178023> in <module>()
----> 1 model_fit=model.fit(x,verbose=2, epochs=10, steps_per_epoch=3)

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).
1

There are 1 best solutions below

1
On BEST ANSWER

You can try the following:

X = np.asarray(x).astype(np.float32)

model_fit=model.fit(X,y, verbose=2, epochs=10, steps_per_epoch=3)

It seems that one of the column is not supported. So just convert it to numpy array with data type float.

Note you define x in a wrong way that contain the class. It should be:

x = df[['SepalLengthCm', 'SepalWidthCm', 'PetalLengthCm', 'PetalWidthCm']].values