在将Tensorflow数据集传递到Keras的model.fit函数中时,获取与形状相关的ValueError。
我的数据集的标注具有形状(100个样本x 62个要素)和Y_train (100个样本x 1个标注
可重现的代码如下:
import numpy as np
from tensorflow.keras import layers, Sequential, optimizers
from tensorflow.data import Dataset
num_samples = 100
num_features = 62
num_labels = 1
batch_size = 32
steps_per_epoch = int(num_samples/batch_size)
X_train = np.random.rand(num_samples,num_features)
Y_train = np.random.rand(num_samples, num_labels)
final_dataset = Dataset.from_tensor_slices((X_train, Y_train))
model = Sequential()
model.add(layers.Dense(256, activation='relu',input_shape=(num_features,)))
model.add(layers.Dense(128, activation='relu'))
model.add(layers.Dense(num_labels, activation='softmax'))
model.compile(optimizer=optimizers.Adam(0.001), loss='categorical_crossentropy',metrics=['accuracy'])
history = model.fit(final_dataset,epochs=10,batch_size=batch_size,steps_per_epoch = steps_per_epoch)错误是:
ValueError: Error when checking input: expected dense_input to have shape (62,) but got array with shape (1,)为什么dense_input会得到一个形状为(1,)的数组?我明确地向它传递了一个X_train of shape (n_samples,n_features)。
有趣的是,如果我对数据集应用一个批处理(某个数字)函数,错误就会消失,但我似乎遗漏了一些东西。
发布于 2019-06-08 10:16:15
这是一种故意的行为。
当你使用Tensorflow数据集时,你不应该在“batch_size”的fit方法中指定模型。相反,正如您所提到的,您必须使用函数和tensorflow数据集来生成批处理。
正如这里在文档中提到的
batch_size:整数或无。每次渐变更新的样本数。如果未指定,batch_size将默认为32。如果您的数据是符号张量、数据集、数据集迭代器、生成器或keras.utils.Sequence实例(因为它们生成批)的形式,则不指定batch_size。
因此,经典行为是按照您所做的那样做:使用数据集生成批处理。
如果你想执行多个时期,也可以使用repeat。在.fit端,您必须指定steps_per_epoch以指示一个时期有多少批处理,并为您的时期数指定epochs。
https://stackoverflow.com/questions/56499585
复制相似问题