[英]How to convert NumPy features and labels arrays to TensorFlow Dataset which can be used for model.fit()?
我有兩個簡單的 NumPy arrays 功能和標簽:
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 arrays 轉換為 TensorFlow 數據集,如下所示:
dataset = tf.data.Dataset.from_tensor_slices((features, labels))
我定義並編譯了一個 model:
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 :
model.fit(dataset, epochs=100)
我得到錯誤:
ValueError: Error when checking input: expected dense_input to have shape (4,) but got array with shape (1,)
如果我將 NumPy 功能和標簽 arrays 直接提供給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
如果我理解正確,我需要創建 TensorFlow 數據集,它將返回 tuple (features, labels)
。 那么如何將 NumPy 特征和標簽 arrays 轉換為 TensorFlow 可用於model.fit()
的數據集?
只需在創建Dataset
時設置批量大小:
batch_size = 2
dataset = tf.data.Dataset.from_tensor_slices((features, labels)).batch(batch_size)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.