model.fit 使用 tf.data.experimental.make_csv_dataset 创建的张量流数据集给出错误

问题描述 投票:0回答:1

我是张量流新手。我正在尝试从 CSV 文件读取值并将其加载为张量流数据集。但是,当我尝试运行 model.fit 时,它给出以下错误 - 输入“input_39”缺少数据。您传递了一个带有键 ['Age', 'Number', 'Start'] 的数据字典。需要以下键:['input_39']

这是我的代码-

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

input_file='kyphosis.csv'

all_dataset = tf.data.experimental.make_csv_dataset(input_file, batch_size=1,label_name="Kyphosis",num_epochs=1)

model=tf.keras.models.Sequential()
model.add(tf.keras.layers.Input(3))
model.add(tf.keras.layers.Dense(10))
model.add(tf.keras.layers.Dense(1,activation='sigmoid'))

model.compile(optimizer='adam',loss='binary_crossentropy',run_eagerly=True)

model.fit(all_dataset,epochs=10)

请让我知道我在这里做错了什么。 Tensorflow版本是2.11.0。

我尝试使用 tf.data.Dataset.from_tensor_slices 但遇到相同的错误 -

df=pd.read_csv('kyphosis.csv')
X=df.drop('Kyphosis',axis=1)
y=df['Kyphosis']

all_dataset=tf.data.Dataset.from_tensor_slices((X.to_dict(orient='list'),y))
all_dataset = all_dataset.batch(1)

model=tf.keras.models.Sequential()
model.add(tf.keras.layers.Input(3))
model.add(tf.keras.layers.Dense(10))
model.add(tf.keras.layers.Dense(1,activation='sigmoid'))

model.compile(optimizer='adam',loss='binary_crossentropy')
model.fit(all_dataset,epochs=3)

错误- ValueError:输入“input_41”缺少数据。您传递了一个带有键 ['Age', 'Number', 'Start'] 的数据字典。需要以下键:['input_41']

tensorflow machine-learning
1个回答
0
投票

tf.data.experimental.make_csv_dataset
返回orderedDict,其中键作为特征名称,值作为实际特征。

dataset = tf.data.experimental.make_csv_dataset(
                'test.csv',label_name='target',
                batch_size=1,num_epochs=1)

如果你仔细观察,

dataset

给出的特征和标签
$ dataset.__iter__().next()
>> (OrderedDict([('sepal length (cm)',
               <tf.Tensor: shape=(1,), dtype=float32, numpy=array([5.], dtype=float32)>),
              ('sepal width (cm)',
               <tf.Tensor: shape=(1,), dtype=float32, numpy=array([2.3], dtype=float32)>),
              ('petal length (cm)',
               <tf.Tensor: shape=(1,), dtype=float32, numpy=array([3.3], dtype=float32)>),
              ('petal width (cm)',
               <tf.Tensor: shape=(1,), dtype=float32, numpy=array([1.], dtype=float32)>)]),
 <tf.Tensor: shape=(1,), dtype=int32, numpy=array([1])>)

因此,您不能简单地将这个有序字典作为模型的输入传递。您可以通过编写预处理映射函数将其转换为可解释的格式

def pre_process(features, labels):
    features = tf.stack([value for key, value in features.items()], axis=-1)
    return features, labels

dataset = dataset.map(pre_process)

现在,如果您看一下

dataset
,它将具有可以传递到模型中的功能

$ dataset.__iter__().next()
> (<tf.Tensor: shape=(1, 4), dtype=float32, numpy=array([[5.1, 3.8, 1.6, 0.2]], dtype=float32)>,
 <tf.Tensor: shape=(1,), dtype=int32, numpy=array([0])>)

现在这个数据集可以直接传入模型中进行训练了。

© www.soinside.com 2019 - 2024. All rights reserved.