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 2.3 kB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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 : IExample
  13. {
  14. private NumPyRandom rng = np.random;
  15. public void Run()
  16. {
  17. // Parameters
  18. double learning_rate = 0.01;
  19. int training_epochs = 1000;
  20. int display_step = 50;
  21. // Training Data
  22. var train_X = np.array(3.3, 4.4, 5.5, 6.71, 6.93, 4.168, 9.779, 6.182, 7.59, 2.167,
  23. 7.042, 10.791, 5.313, 7.997, 5.654, 9.27, 3.1);
  24. var train_Y = np.array(1.7, 2.76, 2.09, 3.19, 1.694, 1.573, 3.366, 2.596, 2.53, 1.221,
  25. 2.827, 3.465, 1.65, 2.904, 2.42, 2.94, 1.3);
  26. var n_samples = train_X.shape[0];
  27. // tf Graph Input
  28. var X = tf.placeholder(tf.float64);
  29. var Y = tf.placeholder(tf.float64);
  30. // Set model weights
  31. var W = tf.Variable(rng.randn<double>(), name: "weight");
  32. var b = tf.Variable(rng.randn<double>(), name: "bias");
  33. var part1 = tf.multiply(X, W);
  34. var pred = tf.add(part1, b);
  35. // Mean squared error
  36. var sub = pred - Y;
  37. var pow = tf.pow(sub, 2);
  38. var reduce = tf.reduce_sum(pow);
  39. var cost = reduce / (2d * n_samples);
  40. // radient 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);
  43. optimizer.minimize(cost);
  44. // Initialize the variables (i.e. assign their default value)
  45. var init = tf.global_variables_initializer();
  46. // Start training
  47. Python.with<Session>(tf.Session(), sess =>
  48. {
  49. // Run the initializer
  50. sess.run(init);
  51. });
  52. }
  53. }
  54. }

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