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.

Model.cs 4.7 kB

6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143
  1. /*****************************************************************************
  2. Copyright 2018 The TensorFlow.NET Authors. All Rights Reserved.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. ******************************************************************************/
  13. using Keras.Layers;
  14. using NumSharp;
  15. using System;
  16. using System.Collections.Generic;
  17. using System.Text;
  18. using Tensorflow;
  19. using static Keras.Keras;
  20. using static Tensorflow.Python;
  21. namespace Keras
  22. {
  23. public class Model
  24. {
  25. public Tensor Flow;
  26. List<ILayer> layer_stack;
  27. public TensorShape InputShape;
  28. public Model()
  29. {
  30. layer_stack = new List<ILayer>();
  31. }
  32. public Model Add(ILayer layer)
  33. {
  34. layer_stack.Add(layer);
  35. return this;
  36. }
  37. public Model Add(IEnumerable<ILayer> layers)
  38. {
  39. layer_stack.AddRange(layers);
  40. return this;
  41. }
  42. public Tensor getFlow()
  43. {
  44. try
  45. {
  46. return Flow;
  47. }
  48. catch (Exception ex)
  49. {
  50. return null;
  51. }
  52. }
  53. public (Operation, Tensor, Tensor) make_graph(Tensor features, Tensor labels)
  54. {
  55. // TODO : Creating Loss Functions And Optimizers.....
  56. #region Model Layers Graph
  57. /*
  58. var stddev = 1 / Math.Sqrt(2);
  59. var d1 = new Dense(num_hidden);
  60. d1.__build__(features.getShape());
  61. var hidden_activations = tf.nn.relu(d1.__call__(features));
  62. var d1_output = d1.output_shape(features.getShape());
  63. var d2 = new Dense(1);
  64. d2.__build__(d1.output_shape(features.getShape()), seed: 17, stddev: (float)(1/ Math.Sqrt(num_hidden)));
  65. var logits = d2.__call__(hidden_activations);
  66. var predictions = tf.sigmoid(tf.squeeze(logits));
  67. */
  68. #endregion
  69. #region Model Graph Form Layer Stack
  70. var flow_shape = features.TensorShape;
  71. Flow = features;
  72. for (int i = 0; i < layer_stack.Count; i++)
  73. {
  74. layer_stack[i].__build__(flow_shape);
  75. flow_shape = layer_stack[i].output_shape(flow_shape);
  76. Flow = layer_stack[i].__call__(Flow);
  77. }
  78. var predictions = tf.sigmoid(tf.squeeze(Flow));
  79. #endregion
  80. #region loss and optimizer
  81. var loss = tf.reduce_mean(tf.square(predictions - tf.cast(labels, tf.float32)), name: "loss");
  82. var gs = tf.Variable(0, trainable: false, name: "global_step");
  83. var train_op = tf.train.GradientDescentOptimizer(0.2f).minimize(loss, global_step: gs);
  84. #endregion
  85. return (train_op, loss, gs);
  86. }
  87. public float train(int num_steps, (NDArray, NDArray) training_dataset)
  88. {
  89. var (X, Y) = training_dataset;
  90. var x_shape = X.shape;
  91. var batch_size = x_shape[0];
  92. var graph = tf.Graph().as_default();
  93. var features = tf.placeholder(tf.float32, new TensorShape(batch_size, 2));
  94. var labels = tf.placeholder(tf.float32, new TensorShape(batch_size));
  95. var (train_op, loss, gs) = this.make_graph(features, labels);
  96. var init = tf.global_variables_initializer();
  97. float loss_value = 0;
  98. with(tf.Session(graph), sess =>
  99. {
  100. sess.run(init);
  101. var step = 0;
  102. while (step < num_steps)
  103. {
  104. var result = sess.run(
  105. new ITensorOrOperation[] { train_op, gs, loss },
  106. new FeedItem(features, X),
  107. new FeedItem(labels, Y));
  108. loss_value = result[2];
  109. step = result[1];
  110. if (step % 1000 == 0)
  111. Console.WriteLine($"Step {step} loss: {loss_value}");
  112. }
  113. Console.WriteLine($"Final loss: {loss_value}");
  114. });
  115. return loss_value;
  116. }
  117. }
  118. }