gpt4 book ai didi

python - 如何将 NumPy 特征和标签数组转换为可用于 model.fit() 的 TensorFlow 数据集?

转载 作者:行者123 更新时间:2023-12-04 10:06:58 24 4
gpt4 key购买 nike

我有两个简单的 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 = 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,)

如果我直接向 fit() 提供 NumPy 功能和标签数组方法然后一切都很好。
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

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

最佳答案

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

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

关于python - 如何将 NumPy 特征和标签数组转换为可用于 model.fit() 的 TensorFlow 数据集?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61538955/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com