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.

Program.cs 1.8 kB

6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. using System;
  2. using System.Collections.Generic;
  3. using Tensorflow;
  4. using Keras.Layers;
  5. using NumSharp;
  6. namespace Keras.Example
  7. {
  8. class Program
  9. {
  10. static void Main(string[] args)
  11. {
  12. Console.WriteLine("================================== Keras ==================================");
  13. #region data
  14. var batch_size = 1000;
  15. var (X, Y) = XOR(batch_size);
  16. //var (X, Y, batch_size) = (np.array(new float[,]{{1, 0 },{1, 1 },{0, 0 },{0, 1 }}), np.array(new int[] { 0, 1, 1, 0 }), 4);
  17. #endregion
  18. #region features
  19. var (features, labels) = (new Tensor(X), new Tensor(Y));
  20. var num_steps = 10000;
  21. #endregion
  22. #region model
  23. var m = new Model();
  24. //m.Add(new Dense(8, name: "Hidden", activation: tf.nn.relu())).Add(new Dense(1, name:"Output"));
  25. m.Add(
  26. new ILayer[] {
  27. new Dense(8, name: "Hidden_1", activation: tf.nn.relu()),
  28. new Dense(1, name: "Output")
  29. });
  30. m.train(num_steps, (X, Y));
  31. #endregion
  32. Console.ReadKey();
  33. }
  34. static (NDArray, NDArray) XOR(int samples)
  35. {
  36. var X = new List<float[]>();
  37. var Y = new List<float>();
  38. var r = new Random();
  39. for (int i = 0; i < samples; i++)
  40. {
  41. var x1 = (float)r.Next(0, 2);
  42. var x2 = (float)r.Next(0, 2);
  43. var y = 0.0f;
  44. if (x1 == x2)
  45. y = 1.0f;
  46. X.Add(new float[] { x1, x2 });
  47. Y.Add(y);
  48. }
  49. return (np.array(X.ToArray()), np.array(Y.ToArray()));
  50. }
  51. }
  52. }