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 2.0 kB

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