How to write object to disk(save in a file) - c#

I am using example code below from accord.net framework website, Any ways this code is working fine what i want to achieve is save object to the file..
I want to save DynamicTimeWarping class type object, kernel in following code to the disk(Save in a file)
DynamicTimeWarping kernel = new DynamicTimeWarping(length: 3);
I have tried using XMLSerializer but visual studio is giving error that it can not be serialized because it does not have parameterless constructor.
double[][][] sequences =
{
{
new double[] { 1, 1, 1 }, // first observation of the first sequence
new double[] { 1, 2, 1 }, // second observation of the first sequence
new double[] { 1, 4, 2 }, // third observation of the first sequence
new double[] { 2, 2, 2 }, // fourth observation of the first sequence
},
new double[][] // second sequence (note that this sequence has a different length)
{
new double[] { 1, 1, 1 }, // first observation of the second sequence
new double[] { 1, 5, 6 }, // second observation of the second sequence
new double[] { 2, 7, 1 }, // third observation of the second sequence
},
new double[][] // third sequence
{
new double[] { 8, 2, 1 }, // first observation of the third sequence
},
new double[][] // fourth sequence
{
new double[] { 8, 2, 5 }, // first observation of the fourth sequence
new double[] { 1, 5, 4 }, // second observation of the fourth sequence
}
};
int[] outputs =
{
-1,-1, // First two sequences are of class -1 (those start with {1,1,1})
1, 1, // Last two sequences are of class +1 (don't start with {1,1,1})
};
double[][] inputs = new double[sequences.Length][];
for (int i = 0; i < sequences.Length; i++)
inputs[i] = Matrix.Concatenate(sequences[i]);
// Now we have to setup the Dynamic Time Warping kernel. We will have to
// inform the length of the fixed-length observations contained in each
// arbitrary-length sequence:
//
DynamicTimeWarping kernel = new DynamicTimeWarping(length: 3);
// Now we can create the machine. When using variable-length
// kernels, we will need to pass zero as the input length:
var svm = new KernelSupportVectorMachine(kernel, inputs: 0);
/ / Create the Sequential Minimal Optimization learning algorithm
var smo = new SequentialMinimalOptimization(svm, inputs, outputs)
{
Complexity = 1.5
};
// And start learning it!
double error = smo.Run(); // error will be 0.0
// At this point, we should have obtained an useful machine. Let's
// see if it can understand a few examples it hasn't seem before:
double[][] a =
{
new double[] { 1, 1, 1 },
new double[] { 7, 2, 5 },
new double[] { 2, 5, 1 },
};
double[][] b =
{
new double[] { 7, 5, 2 },
new double[] { 4, 2, 5 },
new double[] { 1, 1, 1 },
};
int resultA = System.Math.Sign(svm.Compute(Matrix.Concatenate(a))); // -1
int resultB = System.Math.Sign(svm.Compute(Matrix.Concatenate(b))); // +1

Looks like this Class in that framework has SerializableAttribute added.
This example should do:
https://msdn.microsoft.com/en-us/library/system.serializableattribute%28v=vs.110%29.aspx

Related

Zero out subarrays if sums don't match

Given two Lists of integer arrays of the form:
genData = { {1,2,3,4}, {1,2,3,4}, {1,2,3,4}, {1,2,3,4}};
orgData = {{1,2,3,4}, {1,2,3,4}, {2,4,6,8}, {1,2,3,4}};
I'd like to determine if the sum of two subarrays at the same index in both lists don't match. If the sums match, do nothing. If the sums don't match, convert every integer in both subarrays into a 0.
For example, in the two lists above the subarrays at index 2 have a non-matching sum (10 vs 20). I'd like to convert the lists to
genData = { {1,2,3,4}, {1,2,3,4}, {0,0,0,0}, {1,2,3,4} };
orgData = { {1,2,3,4}, {1,2,3,4}, {0,0,0,0}, {1,2,3,4} };
I'm trying to first create a list if sums by trying
var genDataSum = genDataList.ForEach(x => x.Sum());
But obviously, that's throwing up errors..."Cannot assign void to an implicitly typed value".
Any help or guidance will be greatly appreciated.
You need to use select to get the sum. list.foreach works like normal for loop.
List<int[]> genData = new List<int[]>
{
new int[] { 1, 2, 3, 4 },
new int[] { 1, 2, 3, 4 },
new int[] { 1, 2, 3, 4 },
new int[] { 1, 2, 3, 4 }
};
List<int[]> orgData = new List<int[]>
{
new int[] { 1, 2, 3, 4 },
new int[] { 1, 2, 3, 4 },
new int[] { 2, 4, 6, 8 },
new int[] { 1, 2, 3, 4 }
};
var sumsGenData = genData.Select(a => a.Sum()).ToList();
var sumsOrgData = orgData.Select(a => a.Sum()).ToList();
for (int i = 0; i < sumsGenData.Count; i++)
{
if (sumsGenData[i] != sumsOrgData[i])
{
orgData[i] = new int[] { 0, 0, 0, 0 };
}
}
ForEach doesn't return anything. Use Select.
var orgData = { {1,2,3,4}, {1,2,3,4}, {0,0,0,0}, {1,2,3,4} };
var sums = orgData.Select( a => a.Sum() );

Accord and Mulit-label Support Vector Machines

I'm working through the example in the docs for a multi-class support vector machine - http://accord-framework.net/docs/html/T_Accord_MachineLearning_VectorMachines_MultilabelSupportVectorMachine.htm
Though, I'm not getting a 0 error rate, and when I try to compute values, they do not give the output values they should. Is there something wrong with the example?
static void Main(string[] args)
{
// Sample input data
double[][] inputs =
{
new double[] { 0 },
new double[] { 1 },
new double[] { 2 },
new double[] { 3 },
};
// Outputs for each of the inputs
int[][] outputs =
{
new[] {1,-1,-1,-1},
new[] {-1,1,-1,-1},
new[] {-1,-1,1,-1},
new[] {-1,-1,-1,1},
};
// Create a new Linear kernel
IKernel kernel = new Linear();
// Create a new Multi-class Support Vector Machine with one input,
// using the linear kernel and for four disjoint classes.
var machine = new MultilabelSupportVectorMachine(1, kernel, 4);
// Create the Multi-label learning algorithm for the machine
var teacher = new MultilabelSupportVectorLearning(machine, inputs, outputs);
// Configure the learning algorithm to use SMO to train the
// underlying SVMs in each of the binary class subproblems.
teacher.Algorithm = (svm, classInputs, classOutputs, i, j) =>
new SequentialMinimalOptimization(svm, classInputs, classOutputs);
// Run the learning algorithm
double error = teacher.Run();
error = teacher.Run(); // 0.1875 error rate
var answer = machine.Compute(new double[] {2}); // gives -1,-1,-1,-1, instead of -1,-1,1,-1
Should the error rate be zero, and why does it seem that only an input of 0 gives the right output?
To answer the question, it is very likely that there was something wrong with that particular example. Most examples have been updated to reflect the new .Learn() API that was put in place last year.
Now you may see that the documentation page for Multi-label Support Vector Machine has also changed addresses due the new API and is now at
http://accord-framework.net/docs/html/T_Accord_MachineLearning_VectorMachines_MultilabelSupportVectorMachine_1.htm
And now it includes this example, among others:
// Let's say we have the following data to be classified
// into three possible classes. Those are the samples:
//
double[][] inputs =
{
// input output
new double[] { 0, 1, 1, 0 }, // 0
new double[] { 0, 1, 0, 0 }, // 0
new double[] { 0, 0, 1, 0 }, // 0
new double[] { 0, 1, 1, 0 }, // 0
new double[] { 0, 1, 0, 0 }, // 0
new double[] { 1, 0, 0, 0 }, // 1
new double[] { 1, 0, 0, 0 }, // 1
new double[] { 1, 0, 0, 1 }, // 1
new double[] { 0, 0, 0, 1 }, // 1
new double[] { 0, 0, 0, 1 }, // 1
new double[] { 1, 1, 1, 1 }, // 2
new double[] { 1, 0, 1, 1 }, // 2
new double[] { 1, 1, 0, 1 }, // 2
new double[] { 0, 1, 1, 1 }, // 2
new double[] { 1, 1, 1, 1 }, // 2
};
int[] outputs = // those are the class labels
{
0, 0, 0, 0, 0,
1, 1, 1, 1, 1,
2, 2, 2, 2, 2,
};
// Create the multi-class learning algorithm for the machine
var teacher = new MulticlassSupportVectorLearning<Gaussian>()
{
// Configure the learning algorithm to use SMO to train the
// underlying SVMs in each of the binary class subproblems.
Learner = (param) => new SequentialMinimalOptimization<Gaussian>()
{
// Estimate a suitable guess for the Gaussian kernel's parameters.
// This estimate can serve as a starting point for a grid search.
UseKernelEstimation = true
}
};
// Configure parallel execution options
teacher.ParallelOptions.MaxDegreeOfParallelism = 1;
// Learn a machine
var machine = teacher.Learn(inputs, outputs);
// Obtain class predictions for each sample
int[] predicted = machine.Decide(inputs);
// Get class scores for each sample
double[] scores = machine.Score(inputs);
// Compute classification error
double error = new ZeroOneLoss(outputs).Loss(predicted);

multiple classification using Liblinear in Accord.net Framework

I need to implement multiple classification classifier using Liblinear. Accord.net machine learning framework provides all of Liblinear properties except the Crammer and Singer’s formulation for multi-class classification. This is the process.
The usual way of learning a multi-class machine is by using the MulticlassSupportVectorLearning class. This class can teach one-vs-one machines that can then be queried using either voting or elimination strategies.
As such, here is an example on how linear training can be done for multiple classes:
// Let's say we have the following data to be classified
// into three possible classes. Those are the samples:
//
double[][] inputs =
{
// input output
new double[] { 0, 1, 1, 0 }, // 0
new double[] { 0, 1, 0, 0 }, // 0
new double[] { 0, 0, 1, 0 }, // 0
new double[] { 0, 1, 1, 0 }, // 0
new double[] { 0, 1, 0, 0 }, // 0
new double[] { 1, 0, 0, 0 }, // 1
new double[] { 1, 0, 0, 0 }, // 1
new double[] { 1, 0, 0, 1 }, // 1
new double[] { 0, 0, 0, 1 }, // 1
new double[] { 0, 0, 0, 1 }, // 1
new double[] { 1, 1, 1, 1 }, // 2
new double[] { 1, 0, 1, 1 }, // 2
new double[] { 1, 1, 0, 1 }, // 2
new double[] { 0, 1, 1, 1 }, // 2
new double[] { 1, 1, 1, 1 }, // 2
};
int[] outputs = // those are the class labels
{
0, 0, 0, 0, 0,
1, 1, 1, 1, 1,
2, 2, 2, 2, 2,
};
// Create a one-vs-one multi-class SVM learning algorithm
var teacher = new MulticlassSupportVectorLearning<Linear>()
{
// using LIBLINEAR's L2-loss SVC dual for each SVM
Learner = (p) => new LinearDualCoordinateDescent()
{
Loss = Loss.L2
}
};
// Learn a machine
var machine = teacher.Learn(inputs, outputs);
// Obtain class predictions for each sample
int[] predicted = machine.Decide(inputs);
// Compute classification accuracy
double acc = new GeneralConfusionMatrix(expected: outputs, predicted: predicted).Accuracy;
You can also try to solve a multiclass decision problem using the one-vs-rest strategy. In this case, you can use the MultilabelSupportVectorLearning teaching algorithm instead of the multi-class one shown above.

How to declare 2D integer array in C#?

I am at beginner level of programming, and I would like to know how to declare a 2-dimension array in C#. I did look it up on Google but I couldn't find a solution.
Please answer this question at my level.
Thanks
you can do it like this. See details here
int[,] array2D = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };
2D integer array
Declaration
int[,] array = new int[4, 2];
Initialization
int[,] array = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };
Complete explanation with example :http://msdn.microsoft.com/en-us/library/2yd9wwz4.aspx
// Two-dimensional array.
int[,] array2D = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };
// The same array with dimensions specified.
int[,] array2Da = new int[4, 2] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };
// A similar array with string elements.
string[,] array2Db = new string[3, 2] { { "one", "two" }, { "three", "four" },
{ "five", "six" } };
// Three-dimensional array.
int[, ,] array3D = new int[,,] { { { 1, 2, 3 }, { 4, 5, 6 } },
{ { 7, 8, 9 }, { 10, 11, 12 } } };
// The same array with dimensions specified.
int[, ,] array3Da = new int[2, 2, 3] { { { 1, 2, 3 }, { 4, 5, 6 } },
{ { 7, 8, 9 }, { 10, 11, 12 } } };
i think you have not searched google....
follow below link to see tutorial
http://www.tutorialspoint.com/csharp/csharp_multi_dimensional_arrays.htm
int [,] a = int [3,4] = {
{0, 1, 2, 3} , /* initializers for row indexed by 0 */
{4, 5, 6, 7} , /* initializers for row indexed by 1 */
{8, 9, 10, 11} /* initializers for row indexed by 2 */
};
Use MSDN for Micrsoft technologies, it is well documented http://msdn.microsoft.com/en-us/library/2yd9wwz4.aspx
It ranked #1 in google search for me when writing: 2d integer array c#
This page might also provide useful information: What are the differences between a multidimensional array and an array of arrays in C#?
int[,] array2D = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };
The sum2D() Method
private double sum2D(double[,] ar)
{
double sum = 0.0;
foreach (double d in ar)
sum += d;
return sum;
}

Copy only some portion of values from a Two dimentional array

How can i copy only a small portion of two dimensional array to another two dimensional array
int[,] a = new int[3, 4] { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } };
int[,] b = new int[3, 2];
I want array b to hold values like { { 2, 3 }, { 6, 7 }, { 10, 11 } }
Thanks
There you go:
var b = a.Select(_ => _.Skip(1).Take(2).ToArray()).ToArray();

Categories