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.

LinearRegression.cs 4.5 kB

6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. using NumSharp;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Text;
  5. using Tensorflow;
  6. namespace TensorFlowNET.Examples
  7. {
  8. /// <summary>
  9. /// A linear regression learning algorithm example using TensorFlow library.
  10. /// https://github.com/aymericdamien/TensorFlow-Examples/blob/master/examples/2_BasicModels/linear_regression.py
  11. /// </summary>
  12. public class LinearRegression : Python, IExample
  13. {
  14. public int Priority => 3;
  15. public bool Enabled { get; set; } = true;
  16. public string Name => "Linear Regression";
  17. public bool ImportGraph { get; set; } = false;
  18. public int training_epochs = 1000;
  19. // Parameters
  20. float learning_rate = 0.01f;
  21. int display_step = 50;
  22. NumPyRandom rng = np.random;
  23. NDArray train_X, train_Y;
  24. int n_samples;
  25. public bool Run()
  26. {
  27. // Training Data
  28. PrepareData();
  29. // tf Graph Input
  30. var X = tf.placeholder(tf.float32);
  31. var Y = tf.placeholder(tf.float32);
  32. // Set model weights
  33. // We can set a fixed init value in order to debug
  34. // var rnd1 = rng.randn<float>();
  35. // var rnd2 = rng.randn<float>();
  36. var W = tf.Variable(-0.06f, name: "weight");
  37. var b = tf.Variable(-0.73f, name: "bias");
  38. // Construct a linear model
  39. var pred = tf.add(tf.multiply(X, W), b);
  40. // Mean squared error
  41. var cost = tf.reduce_sum(tf.pow(pred - Y, 2.0f)) / (2.0f * n_samples);
  42. // Gradient descent
  43. // Note, minimize() knows to modify W and b because Variable objects are trainable=True by default
  44. var optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost);
  45. // Initialize the variables (i.e. assign their default value)
  46. var init = tf.global_variables_initializer();
  47. // Start training
  48. return with(tf.Session(), sess =>
  49. {
  50. // Run the initializer
  51. sess.run(init);
  52. // Fit all training data
  53. for (int epoch = 0; epoch < training_epochs; epoch++)
  54. {
  55. foreach (var (x, y) in zip<float>(train_X, train_Y))
  56. {
  57. sess.run(optimizer,
  58. new FeedItem(X, x),
  59. new FeedItem(Y, y));
  60. }
  61. // Display logs per epoch step
  62. if ((epoch + 1) % display_step == 0)
  63. {
  64. var c = sess.run(cost,
  65. new FeedItem(X, train_X),
  66. new FeedItem(Y, train_Y));
  67. Console.WriteLine($"Epoch: {epoch + 1} cost={c} " + $"W={sess.run(W)} b={sess.run(b)}");
  68. }
  69. }
  70. Console.WriteLine("Optimization Finished!");
  71. var training_cost = sess.run(cost,
  72. new FeedItem(X, train_X),
  73. new FeedItem(Y, train_Y));
  74. Console.WriteLine($"Training cost={training_cost} W={sess.run(W)} b={sess.run(b)}");
  75. // Testing example
  76. var test_X = np.array(6.83f, 4.668f, 8.9f, 7.91f, 5.7f, 8.7f, 3.1f, 2.1f);
  77. var test_Y = np.array(1.84f, 2.273f, 3.2f, 2.831f, 2.92f, 3.24f, 1.35f, 1.03f);
  78. Console.WriteLine("Testing... (Mean square loss Comparison)");
  79. var testing_cost = sess.run(tf.reduce_sum(tf.pow(pred - Y, 2.0f)) / (2.0f * test_X.shape[0]),
  80. new FeedItem(X, test_X),
  81. new FeedItem(Y, test_Y));
  82. Console.WriteLine($"Testing cost={testing_cost}");
  83. var diff = Math.Abs((float)training_cost - (float)testing_cost);
  84. Console.WriteLine($"Absolute mean square loss difference: {diff}");
  85. return diff < 0.01;
  86. });
  87. }
  88. public void PrepareData()
  89. {
  90. train_X = np.array(3.3f, 4.4f, 5.5f, 6.71f, 6.93f, 4.168f, 9.779f, 6.182f, 7.59f, 2.167f,
  91. 7.042f, 10.791f, 5.313f, 7.997f, 5.654f, 9.27f, 3.1f);
  92. train_Y = np.array(1.7f, 2.76f, 2.09f, 3.19f, 1.694f, 1.573f, 3.366f, 2.596f, 2.53f, 1.221f,
  93. 2.827f, 3.465f, 1.65f, 2.904f, 2.42f, 2.94f, 1.3f);
  94. n_samples = train_X.shape[0];
  95. }
  96. }
  97. }

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