【问题标题】:How to convert NumPy features and labels arrays to TensorFlow Dataset which can be used for model.fit()?如何将 NumPy 特征和标签数组转换为可用于 model.fit() 的 TensorFlow 数据集?
【发布时间】:2020-05-01 08:13:50
【问题描述】:

我有两个简单的 NumPy 数组功能和标签:

features = np.array([
    [6.4, 2.8, 5.6, 2.2],
    [5.0, 2.3, 3.3, 1.0],
    [4.9, 2.5, 4.5, 1.7],
    [4.9, 3.1, 1.5, 0.1],
    [5.7, 3.8, 1.7, 0.3],
])
labels = np.array([2, 1, 2, 0, 0])

我将这两个 NumPy 数组转换为 TensorFlow Dataset,如下所示:

dataset = tf.data.Dataset.from_tensor_slices((features, labels))

我定义并编译了一个模型:

model = keras.Sequential([
    keras.layers.Dense(5, activation=tf.nn.relu, input_shape=(4,)),
    keras.layers.Dense(3, activation=tf.nn.softmax)
])
model.compile(
    optimizer=keras.optimizers.Adam(),
    loss='sparse_categorical_crossentropy',
    metrics=['accuracy']
)

现在我尝试使用fit() 方法训练模型:

model.fit(dataset, epochs=100)

我得到错误:

ValueError: Error when checking input: expected dense_input to have shape (4,) but got array with shape (1,)

如果我将 NumPy 功能和标签数组直接提供给 fit() 方法,那么一切都很好。

model.fit(features, labels, epochs=100)

结果:

Train on 5 samples
Epoch 1/100
5/5 [==============================] - 0s 84ms/sample - loss: 1.8017 - accuracy: 0.4000

Epoch 2/100
5/5 [==============================] - 0s 0s/sample - loss: 1.7910 - accuracy: 0.4000

...............................
Epoch 100/100
5/5 [==============================] - 0s 0s/sample - loss: 1.2484 - accuracy: 0.2000

如果我理解正确,我需要创建将返回元组 (features, labels) 的 TensorFlow 数据集。那么如何将 NumPy 特征和标签数组转换为可用于model.fit() 的 TensorFlow 数据集?

【问题讨论】:

    标签: python numpy tensorflow


    【解决方案1】:

    只需在创建Dataset时设置一个批量大小:

    batch_size = 2
    dataset = tf.data.Dataset.from_tensor_slices((features, labels)).batch(batch_size)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-06-13
      • 2018-07-22
      • 2020-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-02
      • 1970-01-01
      相关资源
      最近更新 更多