【发布时间】: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 是浮点数/双精度数,SibSp 和 Parch 是整数等等。
我的 (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