You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

NeuralNetXor.cs 3.4 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using NumSharp;
  5. using Tensorflow;
  6. namespace TensorFlowNET.Examples
  7. {
  8. /// <summary>
  9. /// Simple vanilla neural net solving the famous XOR problem
  10. /// https://github.com/amygdala/tensorflow-workshop/blob/master/workshop_sections/getting_started/xor/README.md
  11. /// </summary>
  12. public class NeuralNetXor : Python, IExample
  13. {
  14. public int Priority => 2;
  15. public bool Enabled { get; set; } = true;
  16. public string Name => "NN XOR";
  17. public int num_steps = 5000;
  18. private (Operation, Tensor, RefVariable) make_graph(Tensor features,Tensor labels, int num_hidden = 8)
  19. {
  20. var stddev = 1 / Math.Sqrt(2);
  21. var hidden_weights = tf.Variable(tf.truncated_normal(new int []{2, num_hidden}, stddev: (float) stddev ));
  22. // Shape [4, num_hidden]
  23. var hidden_activations = tf.nn.relu(tf.matmul(features, hidden_weights));
  24. var output_weights = tf.Variable(tf.truncated_normal(
  25. new[] {num_hidden, 1},
  26. stddev: (float) (1 / Math.Sqrt(num_hidden))
  27. ));
  28. // Shape [4, 1]
  29. var logits = tf.matmul(hidden_activations, output_weights);
  30. // Shape [4]
  31. var predictions = tf.sigmoid(tf.squeeze(logits));
  32. var loss = tf.reduce_mean(tf.square(predictions - tf.cast(labels, tf.float32)));
  33. var gs = tf.Variable(0, trainable: false);
  34. var train_op = tf.train.GradientDescentOptimizer(0.2f).minimize(loss, global_step: gs);
  35. return (train_op, loss, gs);
  36. }
  37. public bool Run()
  38. {
  39. var graph = tf.Graph();
  40. var init=with(graph.as_default(), g =>
  41. {
  42. var features = tf.placeholder(tf.float32, new TensorShape(4, 2));
  43. var labels = tf.placeholder(tf.int32, new TensorShape(4));
  44. var (train_op, loss, gs) = make_graph(features, labels);
  45. return tf.global_variables_initializer();
  46. });
  47. // Start tf session
  48. with<Session>(tf.Session(), sess =>
  49. {
  50. init.run();
  51. var step = 0;
  52. var xy = np.array(new bool[,]
  53. {
  54. {true, false, },
  55. {true, true, },
  56. {false, false, },
  57. {false, true, },
  58. }, dtype: np.float32);
  59. var y_ = np.array(new[] {true, false, false, true}, dtype: np.int32);
  60. while (step < num_steps)
  61. {
  62. // original python:
  63. //_, step, loss_value = sess.run(
  64. // [train_op, gs, loss],
  65. // feed_dict={features: xy, labels: y_}
  66. // )
  67. // TODO: how the hell to port that to c#?
  68. // var ( _, step, loss_value) = sess.run(new object[] {train_op, gs, loss},feed_dict: new {"features": xy, "labels": y_});
  69. }
  70. //tf.logging.info('Final loss is: {}'.format(loss_value))
  71. //Console.WriteLine($"Final loss is: {loss_value}");
  72. });
  73. return true;
  74. }
  75. public void PrepareData()
  76. {
  77. }
  78. }
  79. }

tensorflow框架的.NET版本,提供了丰富的特性和API,可以借此很方便地在.NET平台下搭建深度学习训练与推理流程。