'System.Threading.CancellationToken'...is not marked as serializable

655 views Asked by At

I am using Accord.NET to create and save a StepwiseLogisticRegressionModel. When I try to serialize and save the model, I am getting the following error:

Type 'System.Threading.CancellationToken' in Assembly 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' is not marked as serializable.

Saving other models such as NaiveBayes seems to work fine.

Here is the code that I have tried:

StepwiseLogisticRegressionAnalysis model;
string file = Path.Combine(path, filename);
Serializer.Save(obj: model, path: file);

and

StepwiseLogisticRegressionAnalysis model;
string file = Path.Combine(path, filename);
using(FileStream stream = new FileStream(filename, FileMode.Create))
{
    var binaryFormatter = new BinaryFormatter();
    binaryFormatter.Serialize(stream, best);
}

How do I resolve this?


Edit: Here is a working example:

double[][] inputs =
{
    //            Age  Smoking
    new double[] { 55,    0   },  // 1
    new double[] { 28,    0   },  // 2
    new double[] { 65,    1   },  // 3
    new double[] { 46,    0   },  // 4
    new double[] { 86,    1   },  // 5
    new double[] { 56,    1   },  // 6
    new double[] { 85,    0   },  // 7
    new double[] { 33,    0   },  // 8
    new double[] { 21,    1   },  // 9
    new double[] { 42,    1   },  // 10
    new double[] { 33,    0   },  // 11
    new double[] { 20,    1   },  // 12
    new double[] { 43,    1   },  // 13
    new double[] { 31,    1   },  // 14
    new double[] { 22,    1   },  // 15
    new double[] { 43,    1   },  // 16
    new double[] { 46,    0   },  // 17
    new double[] { 86,    1   },  // 18
    new double[] { 56,    1   },  // 19
    new double[] { 55,    0   },  // 20
};

double[] output =
{
    0, 0, 0, 1, 1, 1, 0, 0, 0, 1,
    0, 1, 1, 1, 1, 1, 0, 1, 1, 0
};

var regression = new StepwiseLogisticRegressionAnalysis(inputs, output,
    new[] { "Age", "Smoking" }, "Cancer");

regression.Learn(inputs, output); 

var path = $@"C:\";
var filename = "StepWiseRegressionModel.accord";
string file = Path.Combine(path, filename);
Serializer.Save(regression, file);
1

There are 1 answers

1
A.Z. On BEST ANSWER

It looks like there's a private field somewhere in StepwiseLogisticRegressionAnalysis (or a subobject) that contains a CancellationToken, which can't be serialized.

You should try serializing the output model of the analysis (see the regression.Current.Regression property).

Just keep in mind that binary serialization of an object is fairly fragile, unless it's specifically supported. The deserialization environment has to be the exact same as the serialization (same library versions, C# versions, OS version, etc). Serializing the data, then reconstructing the object from it would be better if possible.