【问题标题】:Using different data types in EagerTensor在 EagerTensor 中使用不同的数据类型
【发布时间】:2019-05-23 10:11:31
【问题描述】:

使用 Tensorflow 2.0 alpha,我在尝试使用以下数据创建 tf.data.Dataset 时收到错误 ValueError: Can't convert Python sequence with mixed types to Tensor

Inspect the complete dataset on Kaggle

显然,存在混合数据类型。 Sex 是字符串,Age 是浮点数/双精度数,SibSpParch 是整数等等。

我的 (Python 3) 代码将此 Pandas Dataframe 转换为 tf.data.Dataset 是基于 Tensorflow 在 How to classify structured data 上的教程,如下所示:

def df_to_dataset(dataframe, shuffle=True, batch_size=32):
  dataframe = dataframe.copy()

  # the 'Survived' column is the label (not shown in the image of the Dataframe but exists in the Dataframe)
  label = dataframe.pop('Survived')

  # create the dataset from the dataframe
  ds = tf.data.Dataset.from_tensor_slices((dict(dataframe), label))

  # if shuffle == true, randomize the entries
  if shuffle:
    ds = ds.shuffle(buffer_size=len(dataframe))
  ds = ds.batch(batch_size)

  return ds

如上所述,该函数在执行时会抛出错误ValueError: Can't convert Python sequence with mixed types to Tensor,例如:

train_ds = df_to_dataset(df_train, batch_size=32) 

(而df_train 是您在图片中看到的熊猫数据框)

现在我想知道我是否遗漏了什么,因为 Tensorflow 的教程(上面提到过)也使用了混合类型的数据框,但是在尝试使用完全相同的 df_to_dataset 函数的示例时,我没有遇到任何错误。

【问题讨论】:

  • 函数本身可以工作,但是你错过了 feature_layer,它在你的代码中定义了特征列。
  • @Sharky 但是特征列是在调用这个函数之后定义的,不是吗?如果是这样,它们不会对该函数的结果产生任何影响。因为在调用 df_to_dataset 而不是例如错误时已经发生错误。训练模型时
  • 奇怪的是,简单地迭代数据集时我没有收到任何错误
  • @Sharky 迭代数据集是什么意思?
  • for i in train_ds: print(i) 其中 i 是一个批次。如果您使用的是 TF2.0

标签: python tensorflow tensorflow-datasets tensorflow2.0


【解决方案1】:

此错误是由于 NaN 值是特定列。 用dataframe['Name'].isnull().sum()) 检测它们并替换。

【讨论】:

  • 非常感谢!当我尝试在所有字符串列上使用df.astype(str) 时,在您写这篇文章的同一时刻意外注意到它
  • 我用dataframe = dataframe.dropna()替换了所有缺失值的列
  • 我猜这是众多选择之一。 NaN 是问题所在,我有点惊讶,数据类型有时会很棘手
猜你喜欢
  • 2012-12-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-26
  • 1970-01-01
  • 2019-06-23
  • 1970-01-01
  • 2017-08-29
相关资源
最近更新 更多