【发布时间】:2020-02-23 06:20:35
【问题描述】:
我是一名试图学习 TensorFlow 基础知识的高中生。我目前正在使用 TFRecords 输入文件构建模型,这是 TensorFlow 的默认数据集文件类型,已从原始原始数据压缩。我目前正在使用一种复杂的方式将数据解析为 numpy 数组,以便 Keras 对其进行解释。虽然 Keras 是 TF 的一部分,但它应该能够轻松读取 TFRecord 数据集。 Keras 有没有其他方法可以理解 TFRecord 文件?
我使用 _decodeExampleHelper 方法准备训练数据。
def _decodeExampleHelper(example) :
dataDictionary = {
'xValues' : tf.io.FixedLenFeature([7], tf.float32),
'yValues' : tf.io.FixedLenFeature([3], tf.float32)
}
# Parse the input tf.Example proto using the data dictionary
example = tf.io.parse_single_example(example, dataDictionary)
xValues = example['xValues']
yValues = example['yValues']
# The Keras Sequential network will have "dense" as the name of the first layer; dense_input is the input to this layer
return dict(zip(['dense_input'], [xValues])), yValues
data = tf.data.TFRecordDataset(workingDirectory + 'training.tfrecords')
parsedData = data.map(_decodeExampleHelper)
我们可以看到parsedData在下面的代码块中具有正确的尺寸。
tmp = next(iter(parsedData))
print(tmp)
这会输出 Keras 应该能够解释的正确维度的第一组数据。
({'dense_input': <tf.Tensor: id=273, shape=(7,), dtype=float32, numpy=
array([-0.6065675 , -0.610906 , -0.65771157, -0.41417238, 0.89691925,
0.7122903 , 0.27881026], dtype=float32)>}, <tf.Tensor: id=274, shape=(3,), dtype=float32, numpy=array([ 0. , -0.65868723, -0.27960175], dtype=float32)>)
这是一个非常简单的模型,只有两层,并使用我刚刚解析的数据对其进行训练。
model = tf.keras.models.Sequential(
[
tf.keras.layers.Dense(20, activation = 'relu', input_shape = (7,)),
tf.keras.layers.Dense(3, activation = 'linear'),
]
)
model.compile(optimizer = 'adam', loss = 'mean_absolute_error', metrics = ['accuracy'])
model.fit(parsedData, epochs = 1)
尽管dense_input 为7,但model.fit(parsedData, epochs = 1) 行给出了ValueError: Error when checking input: expected dense_input to have shape (7,) but got array with shape (1,) 的错误。
在这种情况下会出现什么问题?为什么 Keras 不能正确解释文件中的张量?
【问题讨论】:
标签: tensorflow tfrecord