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

守給你的承諾、 提交于 2020-01-17 18:18:25

问题


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


来源:https://stackoverflow.com/questions/49531880/why-to-implement-x-deepcopyx-in-the-torch7

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!