Tensorflow API、Tensorflow集线器和Keras输入形状



我使用的是tf=2.0.0和tensorflow hub。目前我正在使用Tensorflow数据API加载我的数据,该数据存储在tfrecords文件中。

我成功地加载了数据集并编译了模型,但当我试图将数据拟合到模型中时,我得到了错误:

检查输入时出错:预期inputs_input具有1个维度,但得到了形状为(64,1(的阵列

这就是我加载数据的方式:

def _dataset_parser(value):
"""Parse a record from value."""
featdef={
'id':  tf.io.FixedLenFeature([1], tf.int64),
'question': tf.io.FixedLenFeature([1], tf.string),
'label': tf.io.FixedLenFeature([1], tf.int64)
}
example = tf.io.parse_single_example(value, featdef)
label = tf.cast(example['label'], tf.int32)
question = tf.cast(example['question'], tf.string)
return example['question'], example['label']
def _input(epochs, batch_size, filenames):
dataset = tf.data.TFRecordDataset(filenames)
dataset = dataset.repeat(epochs)
dataset = dataset.prefetch(1)
# Parse records.
dataset = dataset.map(_dataset_parser)
dataset = dataset.shuffle(100)
# Batch it up.
dataset = dataset.batch(batch_size)
iterator = tf.compat.v1.data.make_one_shot_iterator(dataset)
question_batch, label_batch = iterator.get_next()
label_batch = tf.one_hot(label_batch, NUM_CLASSES)
return question_batch, label_batch

train_ds = _input(20, 64, ['train_xs.tfrecords'])

这是我的型号:

model = tf.keras.Sequential([
hub.KerasLayer(HUB_URL, dtype=tf.string, input_shape=[], output_shape=[WIDTH], name='inputs'),
tf.keras.layers.Dense(256, 'relu', name ='layer_1'),
tf.keras.layers.Dense(128, 'relu', name = 'layer_2'),
tf.keras.layers.Dense(NUM_CLASSES, activation='softmax', name='output')
])
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=["accuracy"])

我已经尝试过将入口层的输入形状设置为(None,1(,但它一直失败,不确定问题是否是由TensorFlow集线器引起的,但我尝试过从实用的ml书中运行这个例子:

model = tf.keras.Sequential([
hub.KerasLayer("https://tfhub.dev/google/tf2-preview/nnlm-en-dim50/1",
dtype=tf.string, input_shape=[], output_shape=[50]),
tf.keras.layers.Dense(128, activation="relu"),
tf.keras.layers.Dense(1, activation="sigmoid")
])
model.compile(loss="binary_crossentropy", optimizer="adam",
metrics=["accuracy"])
datasets, info = tfds.load("imdb_reviews", as_supervised=True, with_info=True)
train_size = info.splits["train"].num_examples
batch_size = 32
train_set = datasets["train"].repeat().batch(batch_size).prefetch(1)
history = model.fit(train_set, steps_per_epoch=5, epochs=5)#steps_per_epoch=train_size // batch_size, epochs=5)

它工作得很好,但我发现的一个区别是,如果我在我得到的书中的例子上打印train_set:

<PrefetchDataset shapes: ((None,), (None,)), types: (tf.string, tf.int64)>

而在我的代码中,当我打印给模型的数据集时,我会得到这个:

(<tf.Tensor: id=11409, shape=(64, 1), dtype=string, numpy=  array([[b'Restroom score out of 9'],
[b'Name'],
[b'Lastname'],
[b'Type of house'],
[b'Inspection date'],
[b'Pet'],
[b'Phone'], dtype=object)>,  <tf.Tensor: id=11414, shape=(64, 1, 80), dtype=float32, numpy=  array([[[0., 0., 0., ...,
0., 0., 0.]],
[[0., 0., 0., ..., 0., 0., 0.]],
[[0., 0., 0., ..., 0., 0., 0.]],
...,
[[0., 0., 0., ..., 0., 0., 0.]],
[[0., 0., 0., ..., 0., 0., 0.]],
[[0., 0., 0., ..., 0., 0., 0.]]], dtype=float32)>)

有人知道为什么数据的形状不同吗?

如果有人感兴趣,这是对我有用的最后一段代码:

model = tf.keras.Sequential([
hub.KerasLayer(HUB_URL, dtype=tf.string, input_shape=[], output_shape=[WIDTH], name='inputs'),
name=INPUT_TENSOR_NAME),
tf.keras.layers.Dense(256, 'relu', name ='layer_1'),
tf.keras.layers.Dense(128, 'relu', name = 'layer_2'),
tf.keras.layers.Dense(NUM_CLASSES, activation='softmax', name='output')
])
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=["accuracy"])
def _dataset_parser(value):
"""Parse a record from value."""
featdef={
'id':  tf.io.FixedLenFeature([], tf.int64),
'question': tf.io.FixedLenFeature([], tf.string),
'label': tf.io.FixedLenFeature([], tf.int64)
}
example = tf.io.parse_single_example(value, featdef)
label = tf.cast(example['label'], tf.int64)
question = tf.cast(example['question'], tf.string)
return question, tf.one_hot(label, NUM_CLASSES)
def _input(epochs, batch_size, filenames):
dataset = tf.data.TFRecordDataset(filenames)
dataset = dataset.repeat(epochs)
dataset = dataset.prefetch(1)
# Parse records.
dataset = dataset.map(_dataset_parser)
dataset = dataset.shuffle(100)
# Batch it up.
dataset = dataset.batch(batch_size)

return dataset
train_ds = _input(1, 10, ['train_xs.tfrecords'])
model.fit(train_ds,epochs=1)

不确定原因,但通过将特性定义更改为

featdef={
'id':  tf.io.FixedLenFeature([], tf.int64),
'question': tf.io.FixedLenFeature([], tf.string),
'label': tf.io.FixedLenFeature([], tf.int64)
}

它工作

最新更新