forked from SciSharp/TensorFlow.NET
-
Notifications
You must be signed in to change notification settings - Fork 0
/
NeuralNetXor.cs
190 lines (154 loc) · 6.38 KB
/
NeuralNetXor.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
/*****************************************************************************
Copyright 2018 The TensorFlow.NET Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
******************************************************************************/
using System;
using NumSharp;
using Tensorflow;
using TensorFlowNET.Examples.Utility;
using static Tensorflow.Binding;
namespace TensorFlowNET.Examples
{
/// <summary>
/// Simple vanilla neural net solving the famous XOR problem
/// https://github.com/amygdala/tensorflow-workshop/blob/master/workshop_sections/getting_started/xor/README.md
/// </summary>
public class NeuralNetXor : IExample
{
public bool Enabled { get; set; } = true;
public string Name => "NN XOR";
public bool IsImportingGraph { get; set; } = false;
public int num_steps = 10000;
private NDArray data;
private (Operation, Tensor, Tensor) make_graph(Tensor features,Tensor labels, int num_hidden = 8)
{
var stddev = 1 / Math.Sqrt(2);
var hidden_weights = tf.Variable(tf.truncated_normal(new int []{2, num_hidden}, seed:1, stddev: (float) stddev ));
// Shape [4, num_hidden]
var hidden_activations = tf.nn.relu(tf.matmul(features, hidden_weights));
var output_weights = tf.Variable(tf.truncated_normal(
new[] {num_hidden, 1},
seed: 17,
stddev: (float) (1 / Math.Sqrt(num_hidden))
));
// Shape [4, 1]
var logits = tf.matmul(hidden_activations, output_weights);
// Shape [4]
var predictions = tf.tanh(tf.squeeze(logits));
var loss = tf.reduce_mean(tf.square(predictions - tf.cast(labels, tf.float32)), name:"loss");
var gs = tf.Variable(0, trainable: false, name: "global_step");
var train_op = tf.train.GradientDescentOptimizer(0.2f).minimize(loss, global_step: gs);
return (train_op, loss, gs);
}
public bool Run()
{
PrepareData();
float loss_value = 0;
if (IsImportingGraph)
loss_value = RunWithImportedGraph();
else
loss_value = RunWithBuiltGraph();
return loss_value < 0.0628;
}
private float RunWithImportedGraph()
{
var graph = tf.Graph().as_default();
tf.train.import_meta_graph("graph/xor.meta");
Tensor features = graph.get_operation_by_name("Placeholder");
Tensor labels = graph.get_operation_by_name("Placeholder_1");
Tensor loss = graph.get_operation_by_name("loss");
Tensor train_op = graph.get_operation_by_name("train_op");
Tensor global_step = graph.get_operation_by_name("global_step");
var init = tf.global_variables_initializer();
float loss_value = 0;
// Start tf session
using (var sess = tf.Session(graph))
{
sess.run(init);
var step = 0;
var y_ = np.array(new int[] { 1, 0, 0, 1 }, dtype: np.int32);
while (step < num_steps)
{
// original python:
//_, step, loss_value = sess.run(
// [train_op, gs, loss],
// feed_dict={features: xy, labels: y_}
// )
(_, step, loss_value) = sess.run((train_op, global_step, loss), (features, data), (labels, y_));
if (step == 1 || step % 1000 == 0)
Console.WriteLine($"Step {step} loss: {loss_value}");
}
Console.WriteLine($"Final loss: {loss_value}");
}
return loss_value;
}
private float RunWithBuiltGraph()
{
var graph = tf.Graph().as_default();
var features = tf.placeholder(tf.float32, new TensorShape(4, 2));
var labels = tf.placeholder(tf.int32, new TensorShape(4));
var (train_op, loss, gs) = make_graph(features, labels);
var init = tf.global_variables_initializer();
float loss_value = 0;
// Start tf session
using (var sess = tf.Session(graph))
{
sess.run(init);
var step = 0;
var y_ = np.array(new int[] { 1, 0, 0, 1 }, dtype: np.int32);
while (step < num_steps)
{
(_, step, loss_value) = sess.run((train_op, gs, loss), (features, data), (labels, y_));
if (step == 1 || step % 1000 == 0)
Console.WriteLine($"Step {step} loss: {loss_value}");
}
Console.WriteLine($"Final loss: {loss_value}");
}
return loss_value;
}
public void PrepareData()
{
data = new float[,]
{
{1, 0 },
{1, 1 },
{0, 0 },
{0, 1 }
};
if (IsImportingGraph)
{
// download graph meta data
string url = "https://raw.githubusercontent.com/SciSharp/TensorFlow.NET/master/graph/xor.meta";
Web.Download(url, "graph", "xor.meta");
}
}
public Graph ImportGraph()
{
throw new NotImplementedException();
}
public Graph BuildGraph()
{
throw new NotImplementedException();
}
public void Train(Session sess)
{
throw new NotImplementedException();
}
public void Predict(Session sess)
{
throw new NotImplementedException();
}
public void Test(Session sess)
{
throw new NotImplementedException();
}
}
}