【发布时间】:2020-05-29 15:24:15
【问题描述】:
首先,我为什么要使用 Keras?我试图保持尽可能高的水平,这并不意味着我害怕低水平的 Tensorflow;我只是想看看在保持代码尽可能简单易读的同时还能走多远。
我需要我的 Keras 模型(使用 Keras 功能 API 定制)从立体对中读取左侧图像,并最小化需要访问右侧和左侧图像的损失函数。我想将数据存储在tf.data.Dataset。
我尝试了什么:
- 将数据集读取为
(left image, right image),即形状为((W, H, 3), (W, H, 3))的张量,然后使用函数闭包:定义一个返回loss(y_true, y_pred)的keras_loss(left_images),其中y_true是一个持有正确的tf.Tensor图片。这种方法的问题是left_images是tf.data.Dataset并且Tensorflow 抱怨(正确地)我正在尝试对数据集而不是张量进行操作。 -
将数据集读取为
(left image, (left image, right image)),这将使y_true成为tf.Tensor,形状为((W, H, 3), (W, H, 3)),同时包含左右图像。这种方法的问题在于它......不起作用并引发以下错误:ValueError: Error when checking model target: the list of Numpy arrays that you are passing to your model is not the size the model expected. Expected to see 1 array(s), for inputs ['tf_op_layer_resize/ResizeBilinear'] but instead got the following list of 2 arrays: [<tf.Tensor 'args_1:0' shape=(None, 512, 256, 3) dtype=float32>, <tf.Tensor 'args_2:0' shape=(None, 512, 256, 3) dtype=float32>]...
那么,有什么我没有考虑到的吗?我阅读了文档,没有发现什么被认为是y_pred 和什么是y_true,也没有发现如何巧妙地将数据集转换为张量而不将其全部加载到内存中。
我的模型是这样设计的:
def my_model(input_shape):
width = input_shape[0]
height = input_shape[1]
inputs = tf.keras.Input(shape=input_shape)
# < a few more layers >
outputs = tf.image.resize(tf.nn.sigmoid(tf.slice(disp6, [0, 0, 0, 0], [-1, -1, -1, 2])), tf.Variable([width, height]))
model = tf.keras.Model(inputs=inputs, outputs=outputs)
return model
我的数据集是这样构建的(在情况 2 中,而在情况 1 中只有函数 read_stereo_pair_from_line() 发生变化):
def read_img_from_file(file_name):
img = tf.io.read_file(file_name)
# convert the compressed string to a 3D uint8 tensor
img = tf.image.decode_png(img, channels=3)
# Use `convert_image_dtype` to convert to floats in the [0,1] range.
img = tf.image.convert_image_dtype(img, tf.float32)
# resize the image to the desired size.
return tf.image.resize(img, [args.input_width, args.input_height])
def read_stereo_pair_from_line(line):
split_line = tf.strings.split(line, ' ')
return read_img_from_file(split_line[0]), (read_img_from_file(split_line[0]), read_img_from_file(split_line[1]))
# Dataset loading
list_ds = tf.data.TextLineDataset('test/files.txt')
images_ds = list_ds.map(lambda x: read_stereo_pair_from_line(x))
images_ds = images_ds.batch(1)
【问题讨论】:
标签: python tensorflow machine-learning keras loss-function