【问题标题】:In Transfer Learning ValueError: Failed to convert a NumPy array to a Tensor在迁移学习 ValueError 中:无法将 NumPy 数组转换为张量
【发布时间】:2021-01-27 07:55:33
【问题描述】:

我正在使用 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

使用 pandas 读取 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).

【问题讨论】:

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


    【解决方案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
    

    【讨论】:

    • @ImdadulHaque 你是否也注意到了这张纸条?关于x的建设
    猜你喜欢
    • 2020-07-23
    • 1970-01-01
    • 2023-04-08
    • 1970-01-01
    • 1970-01-01
    • 2021-10-19
    • 2020-10-31
    • 1970-01-01
    • 2021-06-26
    相关资源
    最近更新 更多