Hello, I was trying to save a decision forest to a file but then I cannot load it.
I am using C# on a Win7 64bits PC.
An exception is thrown in
alglib.dfunserialize(str, out df);Code:
System.IndexOutOfRangeException was caught
Message=Index was outside the bounds of the array.
Source=alglibnet2
StackTrace:
at alglib.serializer.str2int(Char[] buf, Int32& offs)
at alglib.serializer.unserialize_int()
at alglib.dforest.dfunserialize(serializer s, decisionforest forest)
at alglib.dfunserialize(String s_in, decisionforest& obj)
at gesturePresenter.RDFClassifier.load(String filename) in C:\gestures3d\SVN\code\gesturePresenter\gesturePresenter\RDFClassifier.cs:line 127
InnerException:
Here is a summary of my code, maybe I did something wrong ? (the classification works well)
Code:
class RDFClassifier
{
private alglib.decisionforest df;
private alglib.dfreport dfreport;
private int nbSamples;
private int nbFeatures;
private int nbClasses;
public void testCaseXOR()
{
FeatureVectors samples = new FeatureVectors();
FeatureVector fv1 = new FeatureVector(new double[] { 0, 0, 0 }, 1); // {X1, X2, Y}
FeatureVector fv2 = new FeatureVector(new double[] { 0, 1, 1 }, 1);
FeatureVector fv3 = new FeatureVector(new double[] { 1, 0, 1 }, 1);
FeatureVector fv4 = new FeatureVector(new double[] { 1, 1, 0 }, 1);
samples.Add(fv1);
samples.Add(fv2);
samples.Add(fv3);
samples.Add(fv4);
createForest(samples, 16, 0.95);
classify(new double[] { 0.2, 1.3 });
save("test.rdf");
load("test.rdf");
classify(new double[] { 0.2, 1.3 });
}
public void createForest(FeatureVectors learningSamples, int nTrees, double ratio)
{
int info = 0;
df = new alglib.decisionforest();
dfreport = new alglib.dfreport();
nbSamples = learningSamples.SamplesCount;
nbFeatures = learningSamples.FeaturesDimension;
nbClasses = learningSamples.ClassesDimension;
alglib.dfbuildrandomdecisionforest(
learningSamples.Vectors,
nbSamples,
nbFeatures,
nbClasses,
nTrees,
ratio,
out info,
out df,
out dfreport);
if (info != 1) { throw new Exception("Random Forest Creation not solved"); }
}
public double[] classify(double[] data)
{
if (df == null) { throw new InvalidOperationException("Random Decision Forest not initialized"); }
double[] result = new double[nbClasses];
alglib.dfprocess(df, data, ref result);
return result;
}
public void save(string fileName)
{
if (df == null) { return; }
string str = "";
alglib.dfserialize(df, out str);
using (TextWriter tw = new StreamWriter(fileName, false))
{
tw.WriteLine(str);
tw.Close();
}
}
public void load(string filename)
{
try
{
using (StreamReader sr = new StreamReader(filename))
{
string str = sr.ReadLine();
alglib.dfunserialize(str, out df);
sr.Close();
}
}
catch (Exception e)
{
// ends up here :-(
}
}
}
I hope you'll find the problem and be able to correct it if it is a bug.
Thanks for your good work !