Example 2 – another simple example

As in the previous section, the following example also solves a simple problem, while demonstrating how to save and load a graph as well:

var cns = new ConvNetSharp<float>();

To create a graph, input the following code:

Op<float> cost;
Op<float> fun;
if (File.Exists("test.graphml"))
{
Console.WriteLine("Loading graph from disk.");
var ops = SerializationExtensions.Load<float>("test", true);
fun = ops[0];
cost = ops[1];
}
else
{
var x = cns.PlaceHolder("x");
var y = cns.PlaceHolder("y");
var W = cns.Variable(1.0f, "W", true);
var b = cns.Variable(2.0f, "b", true);
fun = x * W + b;
cost = (fun - y) * (fun - y);
}
var optimizer = new AdamOptimizer<float>(cns, 0.01f, 0.9f, 0.999f, 1e-08f);
using (var session = new Session<float>())
{

Next, to compute the dCost/dW at every node of the graph, we use the following code:

session.Differentiate(cost);
float currentCost;
do
{
var dico = new Dictionary<string, Volume<float>> { { "x", -2.0f }, { "y", 1.0f } };
currentCost = session.Run(cost, dico);
Console.WriteLine($"cost: {currentCost}");
var result = session.Run(fun, dico);
session.Run(optimizer, dico);
}
while (currentCost > 1e-5);
float finalW = session.GetVariableByName(fun, "W").Result;
float finalb = session.GetVariableByName(fun, "b").Result;
Console.WriteLine($"fun = x * {finalW} + {finalb}");
fun.Save("test", cost);

To display the graph, input the following code:

var vm = new ViewModel<float>(cost);
var app = new Application();
app.Run(new GraphControl { DataContext = vm });
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset