如何加载 Tensorflow 数据集 "Iris" 并将标签更改为单热编码

How to load Tensorflow Dataset "Iris" and change the labels into one-hot encode

我试图直接从 tensorflow 数据集加载“iris”数据集,但我卡住了。 我习惯于使用 CSV。

import tensorflow as tf
import tensorflow_datasets as tfds

data = tfds.load("iris",split='train[:80%]', as_supervised=True)
data = data.batch(10)
features, labels = data

我不知道应该如何分离特征 X,y。标签与特征处于不同的张量中,但我不知道如何访问它们才能使用。我想对标签进行一次热编码并将它们输入到模型中,但我被困在这里了。

tensorflow 文档很少包含有关如何执行此操作的信息。非常感谢任何帮助

您可以在 .map() 方法和 tf.one_hot 中 one-hot 您的标签,就像这样:

data = data.batch(10).map(lambda x, y: (x, tf.one_hot(y, depth=3)))

print(next(iter(data))[1])
<tf.Tensor: shape=(10, 3), dtype=float32, numpy=
array([[1., 0., 0.],
       [0., 0., 1.],
       [0., 1., 0.],
       [0., 0., 1.],
       [1., 0., 0.],
       [0., 1., 0.],
       [0., 1., 0.],
       [0., 1., 0.],
       [1., 0., 0.],
       [0., 0., 1.]], dtype=float32)>

Fully-working 最小示例:

import tensorflow as tf
import tensorflow_datasets as tfds

data = tfds.load("iris",split='train[:80%]', as_supervised=True)
data = data.batch(10).map(lambda x, y: (x, tf.one_hot(y, depth=3))).repeat()

model = tf.keras.models.Sequential([
    tf.keras.layers.Dense(8, activation='relu'),
    tf.keras.layers.Dense(16, activation='relu'),
    tf.keras.layers.Dense(3, activation='softmax')
])

model.compile(loss='categorical_crossentropy', optimizer='adam', 
    metrics=['categorical_accuracy'])

history = model.fit(data, steps_per_epoch=8, epochs=10)
Epoch 10/10
1/8 [==>...........................] - ETA: 0s - loss: 0.8848 - cat_acc: 0.6000
8/8 [==============================] - 0s 4ms/step - loss: 0.8549 - cat_acc: 0.5250