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

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

我正在使用 Iris 数据集练习 迁移学习

对于以下代码,我收到以下错误消息:

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

我需要帮助解决这个错误。

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')

拟合模型请关注这部分

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

您可以尝试以下方法:

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

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

似乎不​​支持其中一列。所以只需将其转换为数据类型为 float 的 numpy 数组即可。

请注意,您以错误的方式定义了包含 class 的 x。应该是:

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