为什么在火炬中实现x = deepcopy(x)


if is_pooling then 
for k = 1, #color_codes do 
    color_content_masks[k] = image.scale(color_content_masks[k], math.ceil(color_content_masks[k]:size(2)/2), math.ceil(color_content_masks[k]:size(1)/2)) 
    color_style_masks[k] = image.scale(color_style_masks[k], math.ceil(color_style_masks[k]:size(2)/2), math.ceil(color_style_masks[k]:size(1)/2)) 
end
elseif is_conv then 
local sap = nn.SpatialAveragePooling(3,3,1,1,1,1):float() 
for k = 1, #color_codes do 
    color_content_masks[k] = sap:forward(color_content_masks[k]:repeatTensor(1,1,1))[1]:clone() 
    color_style_masks[k] = sap:forward(color_style_masks[k]:repeatTensor(1,1,1))[1]:clone() 
end 
end
color_content_masks = deepcopy(color_content_masks) 
color_style_masks = deepcopy(color_style_masks)

上面的代码是有关深色照片样式转移的火炬项目。您可以在https://github.com/luanfujun/deep-photo-styletransfer中找到代码。功能deepcopy((如下所示,与LUA官方站点中的建议相同。

function deepcopy(orig) 
    local orig_type = type(orig) 
    local copy 
    if orig_type == 'table' then 
        copy = {} 
        for orig_key, orig_value in next, orig, nil do   
            copy[deepcopy(orig_key)] = deepcopy(orig_value) 
        end 
        setmetatable(copy, deepcopy(getmetatable(orig))) 
    else -- number, string, boolean, etc 
        copy = orig 
    end 
return copy 
end

您可以看到,在if语句color_content_masks和color_style_masks中直接更改,所以为什么我们需要实现deepcopy ??

看起来像以下情况:

a = createSomeTable()
...
b = a -- now b references same table as a, and modifying b will modify a
...
b = deepcopy(b) 
--[[
 now we performed deep copy - b references copy of table a
 and modifying b will not modify a
--]]

相关内容

  • 没有找到相关文章

最新更新