mdabros/SharpLearning

Exception when serializing neural net to XML

gianlucabertani opened this issue · 2 comments

Hello,

I am using SharpLearning.Neural version 0.31.8 in a .Net Core 3.1 project. After training a neural network and obtaining the predictor model, I try to serialize it to an XML file using the suggested procedure:

GenericXmlDataContractSerializer xmlSerializer = new GenericXmlDataContractSerializer();
xmlSerializer.Serialize<IPredictorModel<double>>(_model, () => new StreamWriter(filePath));

It fails with the following SerializationException:

System.Runtime.Serialization.SerializationException: An object of type 'SharpLearning.InputOutput.Serialization.GenericXmlDataContractSerializer+GenericResolver' which derives from DataContractResolver returned false from its TryResolveType method when attempting to resolve the name for an object of type 'MathNet.Numerics.LinearAlgebra.Storage.DenseVectorStorage`1[[System.Single, System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]]', indicating that the resolution failed. Change the TryResolveType implementation to return true.

Any help?

Ok, solved it by myself.

You actually need to specify a couple of additional types on the GenerixXmlDataContractSerializer constructor:

GenericXmlDataContractSerializer xmlSerializer = new GenericXmlDataContractSerializer(new Type[] {
    typeof(MathNet.Numerics.LinearAlgebra.Storage.DenseVectorStorage<float>),
    typeof(MathNet.Numerics.LinearAlgebra.Storage.DenseColumnMajorMatrixStorage<float>)
});

xmlSerializer.Serialize<IPredictorModel<double>>(_model, () => new StreamWriter(filePath));

This does the trick, in case anyone else stumbles on the same problem.

Hi @gianlucabertani,

Thanks for posting both the question, and the solution, this will surely help others :-).

Best regards
Mads