Skip to content
This repository has been archived by the owner on Mar 12, 2020. It is now read-only.

Example Build Dataset XOR Gate

Deepak Kumar Battini edited this page Nov 20, 2017 · 1 revision

Import the namespaces for this example

using SiaNet;
using SiaNet.Common;
using SiaNet.Model;
using SiaNet.Model.Layers;
using SiaNet.Model.Optimizers;

Select the device CPU or GPU

GlobalParameters.Device = CNTK.DeviceDescriptor.CPUDevice;

Configure logging (Optional step)

Logging.OnWriteLog += Logging_OnWriteLog;

Create new instance of the sequential model

Sequential model = new Sequential();

Configure the training callbacks

model.OnEpochEnd += Model_OnEpochEnd;

Build XOR dataset

XYFrame trainData = new XYFrame();

/*
//One approach of building dataset
trainData.Add(new List<float>() { 0, 0 }, 0);
trainData.Add(new List<float>() { 0, 1 }, 1);
trainData.Add(new List<float>() { 1, 0 }, 1);
trainData.Add(new List<float>() { 1, 1 }, 0);
trainData.YFrame.OneHotEncode();
*/
            
//Second approach
trainData.XFrame.Add(0, 0); trainData.YFrame.Add(0);
trainData.XFrame.Add(0, 1); trainData.YFrame.Add(1);
trainData.XFrame.Add(1, 0); trainData.YFrame.Add(1);
trainData.XFrame.Add(1, 1); trainData.YFrame.Add(0);
trainData.YFrame.OneHotEncode();

Build the model by stacking various neural network layers

model = new Sequential();
model.Add(new Dense(dim: 2, shape: 2, act: OptActivations.ReLU));
model.Add(new Dense(dim: 2));

Compile the model and train

model.Compile(OptOptimizers.SGD, OptLosses.CrossEntropy, OptMetrics.Accuracy);
model.Train(trainData, 100, 2);

Event Functions

private static void Model_OnEpochEnd(int epoch, uint samplesSeen, double loss, Dictionary<string, double> metrics)
{
   Console.WriteLine(string.Format("Epoch: {0}, Loss: {1}, Acc: {2}", epoch, loss, metrics.First().Value));
}