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

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