【问题标题】:Select specific features in a Tensorflow 1 layer选择 Tensorflow 1 层中的特定特征
【发布时间】:2020-03-15 07:27:20
【问题描述】:

我遵循this 教程并使用Github page 中的 ipynb 笔记本在 Google Colaboratory 中生成 deepdream 图像。本教程使用 Inception5h 网络。该模型中的 12 层通常用于生成图像。

每一层由大约 500 个单独的特征组成,它们可以识别不同的模式。可以选择层中的特定特征,这会产生不同的结果。我已经在第 6 层“mixed4a:0”中生成了每个特征的图像。我现在要做的是混合这些功能。

这样选择一个特定的层:

layer_tensor = model.layer_tensors[5]
# selects layer 6 out of 12

我可以像这样选择一系列功能:

layer_tensor = model.layer_tensors[5][:,:,:,0:3]
# selects feature 0 to 2 from layer 6

我想要做的是选择特定功能而不是一系列功能。我已经尝试了一些显然不起作用的方法。

layer_tensor = model.layer_tensors[5][:,:,:,0,2,4]
layer_tensor = model.layer_tensors[5][:,:,:,0:2:4]
layer_tensor = model.layer_tensors[5][:,:,:,[0,2,4]]
layer_tensor = model.layer_tensors[5][:,:,:,[0:2:4]]
layer_tensor = model.layer_tensors[5][:,:,:,(0,2,4)]

为了弄清楚“layer_tensor”是什么类型的对象/事物/数据结构,我尝试用不同的参数打印它:

layer_tensor = model.layer_tensors[5]
# prints Tensor("mixed4a:0", shape=(?, ?, ?, 508), dtype=float32, device=/device:CPU:0)
# "mixed4a:0" is the layer name. 508 in 'shape' is the number of features in the layer

layer_tensor = model.layer_tensors[5][:,:,:,0:100]
# prints: Tensor("strided_slice_127:0", shape=(?, ?, ?, 100), dtype=float32)

layer_tensor = model.layer_tensors[5][:,:,:,0]
# prints: Tensor("strided_slice_128:0", shape=(?, ?, ?), dtype=float32)

我是 Tensorflow 和神经网络的新手。有谁知道如何选择不同的功能,而不仅仅是一系列功能?提前致谢!

要运行代码,请将“DeepDream_using_tensorflow.ipynb”文件加载到 Google Colaboratory。选择带有 GPU 后端的 Python3 运行时。将文件“download.py”和“inception5h.py”上传到运行时,它应该可以正常工作。

【问题讨论】:

    标签: python tensorflow conv-neural-network deep-dream tensorflow-layers


    【解决方案1】:

    您可以使用tf.gather通过以下方式实现您所需要的。

    # don't forget to have a look over the deep_dream_final_output.html file to see the processed outputs.
    
    indices = [1,3,5]
    layer_tensor = tf.transpose(
        tf.gather(
            tf.transpose(model.layer_tensors[10], [3,0,1,2]), indices
            ), 
        [1,2,3,0])
    print(layer_tensor)
    img_result = recursive_optimize(layer_tensor=layer_tensor, image=image,
                     num_iterations=10, step_size=3.0, rescale_factor=0.7,
                     num_repeats=4, blend=0.2)
    

    它看起来很复杂,但它所做的只是跟随。

    • 转置layer_tensor s.t.最后一个轴(即您要切片的轴)是第一个轴(因为它使切片更容易)
    • 使用tf.gather 进行切片。我们正在采用 1,3,5 功能。它可以是一个索引列表
    • 将张量转回正确的形状(即将第一个轴发送到最后面)。

    希望这很清楚。

    【讨论】:

    • 这很好用,非常感谢!我已经通过 API 查看了 tf.gather() 之类的函数,但是当您甚至不知道张量的属性或数据结构时,该 API 可能会非常令人生畏。我收到一条警告,上面写着 UserWarning: Converting sparse IndexedSlices to a dense Tensor of unknown shape。这可能会消耗大量内存。 “将稀疏的 IndexedSlices 转换为形状未知的密集张量。”。不过,我没有遇到任何 RAM 使用高峰。
    • 是的,我遇到了同样的警告。但我认为您不必担心此实例/问题中的错误。对于非常大的张量来说可能是个问题。但说实话,我不知道为什么会弹出这个警告。
    猜你喜欢
    • 2018-09-25
    • 1970-01-01
    • 2017-06-26
    • 2023-03-13
    • 1970-01-01
    • 2013-02-21
    • 2018-06-01
    相关资源
    最近更新 更多