我有两个简单的NumPy数组功能和标签:
@Override
public String toString() {
return date.toString() + 'T' + time.toString();
}
我将这两个NumPy数组转换为TensorFlow数据集,如下所示:
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])
我定义并编译模型:
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)
如果我直接将NumPy功能和标签数组提供给ValueError: Error when checking input: expected dense_input to have shape (4,) but got array with shape (1,)
方法,那么一切都很好。
fit()
结果:
model.fit(features, labels, epochs=100)
如果我理解正确,则需要创建TensorFlow数据集,该数据集将返回元组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
。那么如何将NumPy特征和标签数组转换为可用于(features, labels)
的TensorFlow数据集?
答案 0 :(得分:1)
创建Dataset
时只需设置批次大小:
batch_size = 2
dataset = tf.data.Dataset.from_tensor_slices((features, labels)).batch(batch_size)