使用自定义 Torch class 序列化失败
Serialization fails with custom Torch class
序列化可能会失败,创建的 class 对象包含 __pairs
:
test = torch.class('test')
function test:__init()
self.data = {}
end
function test:__pairs(...)
return pairs(self.data, ...)
end
function test:get_data()
print(self.data)
end
a = test.new()
a.data = {"asdasd"}
b = torch.serialize(a)
c = torch.deserialize(b)
print(torch.typename(c))
print(c:get_data())
以下returns:
test
nil
torch.serialization
后面的引擎位于 File-class. The File:writeObject
us the key function. For the above example the action for a Torch class starts at line 201 中:
elseif typeidx == TYPE_TORCH then
类型在 File:isWritableObject
中标识。
也许可以实现元表功能 write
but in the above example the problem was non-torch metatable function __pairs
that should be __pairs__
(see torch.getmetatable
):
test = torch.class('test')
function test:__init()
self.data = {}
end
function test:__pairs__(...)
return pairs(self.data, ...)
end
function test:get_data()
print(self.data)
end
a = test.new()
a.data = {"asdasd"}
b = torch.serialize(a)
c = torch.deserialize(b)
print(torch.typename(c))
print(c:get_data())
这给出了预期的:
test
{
1 : "asdasd"
}
序列化可能会失败,创建的 class 对象包含 __pairs
:
test = torch.class('test')
function test:__init()
self.data = {}
end
function test:__pairs(...)
return pairs(self.data, ...)
end
function test:get_data()
print(self.data)
end
a = test.new()
a.data = {"asdasd"}
b = torch.serialize(a)
c = torch.deserialize(b)
print(torch.typename(c))
print(c:get_data())
以下returns:
test
nil
torch.serialization
后面的引擎位于 File-class. The File:writeObject
us the key function. For the above example the action for a Torch class starts at line 201 中:
elseif typeidx == TYPE_TORCH then
类型在 File:isWritableObject
中标识。
也许可以实现元表功能 write
but in the above example the problem was non-torch metatable function __pairs
that should be __pairs__
(see torch.getmetatable
):
test = torch.class('test')
function test:__init()
self.data = {}
end
function test:__pairs__(...)
return pairs(self.data, ...)
end
function test:get_data()
print(self.data)
end
a = test.new()
a.data = {"asdasd"}
b = torch.serialize(a)
c = torch.deserialize(b)
print(torch.typename(c))
print(c:get_data())
这给出了预期的:
test
{
1 : "asdasd"
}