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

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