Skip to content

Commit ad1f1e4

Browse files
committed
Examples: added NeuralNetXor
1 parent 911e046 commit ad1f1e4

7 files changed

Lines changed: 180 additions & 5 deletions

File tree

‎src/TensorFlowNET.Core/APIs/tf.math.cs‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -298,5 +298,8 @@ public static Tensor cast(Tensor x, TF_DataType dtype = TF_DataType.DtInvalid, s
298298

299299
public static Tensor argmax(Tensor input, int axis = -1, string name = null, int? dimension = null, TF_DataType output_type = TF_DataType.TF_INT64)
300300
=> gen_math_ops.arg_max(input, axis, name: name, output_type: output_type);
301+
302+
public static Tensor square(Tensor x, string name = null)
303+
=> gen_math_ops.square(x, name: name);
301304
}
302305
}

‎src/TensorFlowNET.Core/APIs/tf.nn.cs‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,9 @@ public static Tensor embedding_lookup(RefVariable @params,
2626
partition_strategy: partition_strategy,
2727
name: name);
2828

29-
public static IActivation relu => new relu();
29+
public static IActivation relu() => new relu();
30+
31+
public static Tensor relu(Tensor features, string name = null) => gen_nn_ops.relu(features, name);
3032

3133
public static Tensor[] fused_batch_norm(Tensor x,
3234
RefVariable scale,

‎src/TensorFlowNET.Core/APIs/tf.random.cs‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,5 +29,13 @@ public static Tensor random_uniform(int[] shape,
2929
TF_DataType dtype = TF_DataType.TF_FLOAT,
3030
int? seed = null,
3131
string name = null) => random_ops.random_uniform(shape, minval, maxval, dtype, seed, name);
32+
33+
public static Tensor truncated_normal(int[] shape,
34+
float mean = 0.0f,
35+
float stddev = 1.0f,
36+
TF_DataType dtype = TF_DataType.TF_FLOAT,
37+
int? seed = null,
38+
string name = null)
39+
=> random_ops.truncated_normal(shape, mean, stddev, dtype, seed, name);
3240
}
3341
}

‎src/TensorFlowNET.Core/Operations/NnOps/gen_nn_ops.cs‎

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
using System;
22
using System.Collections.Generic;
3+
using System.Linq;
34
using System.Text;
5+
using Tensorflow.Operations.Activation;
46

57
namespace Tensorflow.Operations
68
{
@@ -173,5 +175,59 @@ public static (Tensor, Tensor) softmax_cross_entropy_with_logits(Tensor features
173175

174176
return (_op.outputs[0], _op.outputs[1]);
175177
}
178+
179+
/// <summary>
180+
/// Computes rectified linear: `max(features, 0)`.
181+
/// </summary>
182+
/// <param name="features">A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `half`, `uint32`, `uint64`, `qint8`.</param>
183+
/// <param name="name">A name for the operation (optional).</param>
184+
/// <returns>A `Tensor`. Has the same type as `features`.</returns>
185+
public static Tensor relu(Tensor features, string name = null)
186+
{
187+
188+
//_ctx = _context._context
189+
//if _ctx is not None and _ctx._eager_context.is_eager:
190+
// try:
191+
// _result = _pywrap_tensorflow.TFE_Py_FastPathExecute(
192+
// _ctx._context_handle, _ctx._eager_context.device_name, "Relu", name,
193+
// _ctx._post_execution_callbacks, features)
194+
// return _result
195+
// except _core._FallbackException:
196+
// try:
197+
// return relu_eager_fallback(
198+
// features, name=name, ctx=_ctx)
199+
// except _core._SymbolicException:
200+
// pass # Add nodes to the TensorFlow graph.
201+
// except (TypeError, ValueError):
202+
// result = _dispatch.dispatch(
203+
// relu, features=features, name=name)
204+
// if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
205+
// return result
206+
// raise
207+
// except _core._NotOkStatusException as e:
208+
// if name is not None:
209+
// message = e.message + " name: " + name
210+
// else:
211+
// message = e.message
212+
// _six.raise_from(_core._status_to_exception(e.code, message), None)
213+
//# Add nodes to the TensorFlow graph.
214+
//try:
215+
OpDefLibrary _op_def_lib = new OpDefLibrary();
216+
var _op = _op_def_lib._apply_op_helper("Relu", name: name, args: new { features });
217+
return _op.outputs[0];
218+
//except (TypeError, ValueError):
219+
// result = _dispatch.dispatch(
220+
// relu, features=features, name=name)
221+
// if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
222+
// return result
223+
// raise
224+
// var _result = _op.outputs.ToArray();
225+
//_inputs_flat = _op.inputs
226+
//_attrs = ("T", _op.get_attr("T"))
227+
//_execute.record_gradient(
228+
// "Relu", _inputs_flat, _attrs, _result, name)
229+
//_result, = _result
230+
// return _result;
231+
}
176232
}
177233
}
Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Text;
4+
using NumSharp;
5+
using Tensorflow;
6+
7+
namespace TensorFlowNET.Examples
8+
{
9+
/// <summary>
10+
/// Simple vanilla neural net solving the famous XOR problem
11+
/// https://github.com/amygdala/tensorflow-workshop/blob/master/workshop_sections/getting_started/xor/README.md
12+
/// </summary>
13+
public class NeuralNetXor : Python, IExample
14+
{
15+
public int Priority => 2;
16+
public bool Enabled { get; set; } = true;
17+
public string Name => "NN XOR";
18+
19+
public int num_steps = 5000;
20+
21+
private (Operation, Tensor, RefVariable) make_graph(Tensor features,Tensor labels, int num_hidden = 8)
22+
{
23+
var stddev = 1 / Math.Sqrt(2);
24+
var hidden_weights = tf.Variable(tf.truncated_normal(new int []{2, num_hidden}, stddev: (float) stddev ));
25+
26+
// Shape [4, num_hidden]
27+
var hidden_activations = tf.nn.relu(tf.matmul(features, hidden_weights));
28+
29+
var output_weights = tf.Variable(tf.truncated_normal(
30+
new[] {num_hidden, 1},
31+
stddev: (float) (1 / Math.Sqrt(num_hidden))
32+
));
33+
34+
// Shape [4, 1]
35+
var logits = tf.matmul(hidden_activations, output_weights);
36+
37+
// Shape [4]
38+
var predictions = tf.sigmoid(tf.squeeze(logits));
39+
var loss = tf.reduce_mean(tf.square(predictions - tf.cast(labels, tf.float32)));
40+
41+
var gs = tf.Variable(0, trainable: false);
42+
var train_op = tf.train.GradientDescentOptimizer(0.2f).minimize(loss, global_step: gs);
43+
44+
return (train_op, loss, gs);
45+
}
46+
47+
public bool Run()
48+
{
49+
50+
var graph = tf.Graph();
51+
52+
var init=with(graph.as_default(), g =>
53+
{
54+
var features = tf.placeholder(tf.float32, new TensorShape(4, 2));
55+
var labels = tf.placeholder(tf.int32, new TensorShape(4));
56+
57+
var (train_op, loss, gs) = make_graph(features, labels);
58+
return tf.global_variables_initializer();
59+
});
60+
61+
// Start tf session
62+
with<Session>(tf.Session(), sess =>
63+
{
64+
init.run();
65+
var step = 0;
66+
var xy = np.array(new bool[,]
67+
{
68+
{true, false, },
69+
{true, true, },
70+
{false, false, },
71+
{false, true, },
72+
}, dtype: np.float32);
73+
74+
var y_ = np.array(new[] {true, false, false, true}, dtype: np.int32);
75+
while (step < num_steps)
76+
{
77+
// original python:
78+
//_, step, loss_value = sess.run(
79+
// [train_op, gs, loss],
80+
// feed_dict={features: xy, labels: y_}
81+
// )
82+
// TODO: how the hell to port that to c#?
83+
// var ( _, step, loss_value) = sess.run(new object[] {train_op, gs, loss},feed_dict: new {"features": xy, "labels": y_});
84+
}
85+
//tf.logging.info('Final loss is: {}'.format(loss_value))
86+
//Console.WriteLine($"Final loss is: {loss_value}");
87+
88+
});
89+
return true;
90+
}
91+
92+
public void PrepareData()
93+
{
94+
}
95+
}
96+
}

‎test/TensorFlowNET.Examples/TextClassification/cnn_models/VdCnn.cs‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,7 @@ public VdCnn(int alphabet_size, int document_max_len, int num_class)
6666
filters: num_filters[0],
6767
kernel_size: new int[] { filter_sizes[0], embedding_size },
6868
kernel_initializer: cnn_initializer,
69-
activation: tf.nn.relu);
69+
activation: tf.nn.relu());
7070

7171
conv0 = tf.transpose(conv0, new int[] { 0, 1, 3, 2 });
7272
});
@@ -99,12 +99,12 @@ public VdCnn(int alphabet_size, int document_max_len, int num_class)
9999
// ============= Fully Connected Layers =============
100100
with(tf.name_scope("fc-1"), scope =>
101101
{
102-
fc1_out = tf.layers.dense(h_flat, 2048, activation: tf.nn.relu, kernel_initializer: fc_initializer);
102+
fc1_out = tf.layers.dense(h_flat, 2048, activation: tf.nn.relu(), kernel_initializer: fc_initializer);
103103
});
104104

105105
with(tf.name_scope("fc-2"), scope =>
106106
{
107-
fc2_out = tf.layers.dense(fc1_out, 2048, activation: tf.nn.relu, kernel_initializer: fc_initializer);
107+
fc2_out = tf.layers.dense(fc1_out, 2048, activation: tf.nn.relu(), kernel_initializer: fc_initializer);
108108
});
109109

110110
with(tf.name_scope("fc-3"), scope =>
@@ -148,7 +148,7 @@ private Tensor conv_block(Tensor input, int i, bool max_pool = true)
148148
// batch normalization
149149
conv = tf.layers.batch_normalization(conv, training: is_training);
150150
// relu
151-
conv = tf.nn.relu.Activate(conv);
151+
conv = tf.nn.relu(conv);
152152
conv = tf.transpose(conv, new int[] { 0, 1, 3, 2 });
153153
});
154154
}

‎test/TensorFlowNET.UnitTest/ExamplesTests/ExamplesTest.cs‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,16 @@ public void TextClassificationWithMovieReviews()
108108
tf.Graph().as_default();
109109
new TextClassificationWithMovieReviews() { Enabled = true }.Run();
110110
}
111+
112+
[Ignore]
113+
[TestMethod]
114+
public void NeuralNetXor()
115+
{
116+
tf.Graph().as_default();
117+
new NeuralNetXor() { Enabled = true }.Run();
118+
}
119+
111120

121+
112122
}
113123
}

0 commit comments

Comments
 (0)