-1
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?

4

1 回答 1

-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
--]]
于 2018-03-28T13:24:47.003 回答