如何使用TensorFlow构建多输入图形?

11

是否可以定义一个包含多个输入的TensorFlow图形呢? 例如,我想要给图形两张图片和一段文本,每个输入都会经过一些层和一个全连接层的处理。然后有一个节点计算损失函数,考虑这三种表示的联合损失函数。目标是让这三个网络在考虑联合表示损失的情况下进行反向传播。 这可能吗?有关于它的任何示例/教程吗?

1个回答

15

这是非常简单明了的事情。对于“一个输入”,您可能会有类似以下内容:

def build_column(x, input_size):

    w = tf.Variable(tf.random_normal([input_size, 20]))
    b = tf.Variable(tf.random_normal([20]))
    processing1 = tf.nn.sigmoid(tf.matmul(x, w) + b)

    w = tf.Variable(tf.random_normal([20, 3]))
    b = tf.Variable(tf.random_normal([3]))
    return tf.nn.sigmoid(tf.matmul(processing1, w) + b)

input1 = tf.placeholder(tf.float32, [None, 2])
output1 = build_column(input1, 2) # 2-20-3 network

你可以随时添加更多类似的“列”,并合并它们。

input1 = tf.placeholder(tf.float32, [None, 2])
output1 = build_column(input1, 2)

input2 = tf.placeholder(tf.float32, [None, 10])
output2 = build_column(input1, 10)

input3 = tf.placeholder(tf.float32, [None, 5])
output3 = build_column(input1, 5)


whole_model = output1 + output2 + output3 # since they are all the same size

然后您将获得类似于以下的网络:

 2-20-3\
        \
10-20-3--SUM (dimension-wise)
        /
 5-20-3/

或者使输出为单个值

w1 = tf.Variable(tf.random_normal([3, 1]))
w2 = tf.Variable(tf.random_normal([3, 1]))
w3 = tf.Variable(tf.random_normal([3, 1]))

whole_model = tf.matmul(output1, w1) + tf.matmul(output2, w2) + tf.matmul(output3, w3)

获取

 2-20-3\
        \
10-20-3--1---
        /
 5-20-3/

1
谢谢Lejlot!一个后续问题:上面的build_column()没有被重复使用,对吧?如果我们想要将相同的build_column()参数用于两个图像输入,然后连接输出,该怎么办? - Fosa

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接