tensorflow - Keras 是否有一种无需额外数据处理措施即可读取 TFRecord 数据集的方法?
问题描述
我是一名高中生,试图学习 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 不能正确解释文件中的张量?
解决方案
在将数据传递给 Keras 并使用输入层之前,您需要对数据进行批处理。以下对我来说很好:
import tensorflow as tf
ds = tf.data.Dataset.from_tensors((
{'dense_input': [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7]}, [ 0.0, 0.1, -0.1]))
ds = ds.repeat(32).batch(32)
model = tf.keras.models.Sequential(
[
tf.keras.Input(shape=(7,), name='dense_input'),
tf.keras.layers.Dense(20, activation = 'relu'),
tf.keras.layers.Dense(3, activation = 'linear'),
]
)
model.compile(optimizer = 'adam', loss = 'mean_absolute_error', metrics = ['accuracy'])
model.fit(ds, epochs = 1)
推荐阅读
- m2doc - M2DOC:如何传递对象集合
- javascript - Does state persist upon rerender of components?
- php - PHP Install Amazon Linux Cloud Formation
- excel - 如何使用 python 自动运行日常 SQL 脚本(Oracle)?
- c# - How to properly implement multiple Vector3.Lerps in series?
- cassandra - cassandra not working on ubuntu 18.04 LTS
- windows - Windows 10 Pro 和 Hyper-V 上的 Vagrant SMB 共享文件夹上的“常规访问被拒绝错误”
- java - dockerized 环境中的 Argon2 参数
- c++ - 替代“矢量
调整[10]" - fhir-server-for-azure - 为 MS Fhir 服务客户端应用程序