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

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