why to implement x=deepcopy(x) in the Torch7? [dup

2019-09-22 03:51发布

问题:

This question is an exact duplicate of:

  • what is mean by implement color_content_masks = deepcopy(color_content_masks) in the Torch7 code below?
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)

The code above is a torch project about deep photo style transfer. You can find the code in https://github.com/luanfujun/deep-photo-styletransfer . The function deepcopy() is as below which is the same as recommended in Lua official site.

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

As you can see, in the If statement color_content_masks and color_style_masks is change directly, so why do we need to implement a deepcopy??

回答1:

it look like the following situation:

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
--]]