在Transfer Learning ValueError中:无法将NumPy数组转换为张量

时间:2020-10-13 01:55:53

标签: python numpy tensorflow deep-learning transfer-learning

我正在使用Iris数据集进行转移学习

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

无法将NumPy数组转换为张量(不支持的对象类型 浮动)

我需要帮助解决此错误。

在导入的库下面

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

使用熊猫读取csv文件

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

转换为numpy数组进行分类

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

建立神经网络,

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

编译NN模型

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

适合模型,请关注这一部分

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

错误在下面给出,

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 个答案:

答案 0 :(得分:1)

您可以尝试以下操作:

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

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

似乎不支持该列之一。因此,只需将其转换为数据类型为float的numpy数组即可。

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

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