TF-slim не может сжать при вычислении sparse_softmax_cross_entropy_loss двух сцепленных моделей - PullRequest
0 голосов
/ 16 апреля 2019

Я пытаюсь объединить выходные данные двух одновременно работающих моделей Slim ResNet-v1-101 с удаленным последним слоем (logits).Моя цель состоит в том, чтобы 'захватить' выходные данные из последних блоков каждой ветви, объединить их и уменьшить до [batch_size x 1 x 1 x num_clases] тензора, поэтому, имея [batch_size x num_classes] lables тензор, я мог бы легко вычислить sparse_softmax_cross_entropy.Здесь batch_size=2 и num_classes=3.

Когда я пытаюсь рассчитать убыток, я получаю следующую ошибку:

tenorsflow.python.framework.errors_impl.InvalidArgumentError: Cannot squeeze dim [3], ожидаемый размер 1, получил 3 для 'sparse_softmax_cross_entropy_loss / remove_squeezable_dimensions / Squeeze' (op: 'Squeeze') с входными формами: [2,?,?, 3].

Ошибка имеет смысл - последний слой Tensor("conv3_1/Relu:0", shape=(1, 1, 512, 3), dtype=float32) - это свертка 1x1 с 512 входными и 3 выходными фильтрами.

Мои вопросы:

1) Я конкатенируюмодель выводит правильно?Является ли последний конвер из последнего блока хорошим местом для получения дескриптора?

2) Учитывая, что у меня есть вывод правильного размера (размер пакета из 2 и 3 выходных фильтров должен дать [batch_size x ? x ? x num_classes]) - почему потеряоп жаловать?

3) Есть ли какая-либо другая проблема с моим решением, которая вызывает его сбой?

Код:

with tf.variable_scope("rgb_branch"):
    with tf.contrib.slim.arg_scope(resnet_v1.resnet_arg_scope()):
        rgb_logits, rgb_end_points = resnet_v1.resnet_v1_101(features[0], self.num_classes, global_pool=True, is_training=is_training)        

        #Exclude logits
        rgb_variables_to_restore = tf.contrib.slim.get_variables_to_restore(exclude=['rgb_branch/resnet_v1_101/logits'])

        # Strip the scope name for assingment map
        rgb_assignment_map = { rgb_variables_to_restore[0].name.split(':')[0] : rgb_variables_to_restore[0]}
        rgb_assignment_map.update({ v.name.split(':')[0].split('/', 1)[1] : v for v in rgb_variables_to_restore[1:] })

        tf.train.init_from_checkpoint(self.pre_trained_model_path, rgb_assignment_map)


with tf.variable_scope("depth_branch"):
    with tf.contrib.slim.arg_scope(resnet_v1.resnet_arg_scope()):     
        depth_logits, depth_end_points = resnet_v1.resnet_v1_101(features[1], self.num_classes, global_pool=True, is_training=is_training)        

        #Exclude rgb branch already existing in the graph and logits
        depth_variables_to_restore = tf.contrib.slim.get_variables_to_restore(exclude=['rgb_branch', 'depth_branch/resnet_v1_101/logits'])

        # Strip the scope name for assingment map
        depth_assignment_map = { depth_variables_to_restore[0].name.split(':')[0] : depth_variables_to_restore[0]}
        depth_assignment_map.update({ v.name.split(':')[0].split('/', 1)[1] : v for v in depth_variables_to_restore[1:] })

        tf.train.init_from_checkpoint(self.pre_trained_model_path, depth_assignment_map)

rgb_branch_last_conv = tf.contrib.framework.get_variables('rgb_branch/resnet_v1_101/block4/unit_3/bottleneck_v1/conv3')[0]
depth_branch_last_conv = tf.contrib.framework.get_variables('depth_branch/resnet_v1_101/block4/unit_3/bottleneck_v1/conv3')[0]

model = tf.concat( [rgb_branch_last_conv, depth_branch_last_conv], axis=0, name='branches_concat')
model = slim.conv2d(model, 512, [1, 1], scope='conv1_1')
model = slim.conv2d(model, 128, [1, 1], scope='conv2_1')
model = slim.conv2d(model, 3, [1, 1], scope='conv3_1')

print(model, tf.shape(model))
print(labels, tf.shape(labels))

loss = tf.losses.sparse_softmax_cross_entropy(logits=model, labels=labels)  
...