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.

Python.cs 2.4 kB

6 years ago
6 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. using NumSharp.Core;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Text;
  5. namespace Tensorflow
  6. {
  7. /// <summary>
  8. /// Mapping C# functions to Python
  9. /// </summary>
  10. public class Python
  11. {
  12. protected void print(object obj)
  13. {
  14. Console.WriteLine(obj.ToString());
  15. }
  16. public static void with(IPython py, Action<IPython> action)
  17. {
  18. try
  19. {
  20. py.__enter__();
  21. action(py);
  22. }
  23. catch (Exception ex)
  24. {
  25. Console.WriteLine(ex.ToString());
  26. throw ex;
  27. }
  28. finally
  29. {
  30. py.__exit__();
  31. py.Dispose();
  32. }
  33. }
  34. public static void with<T>(IPython py, Action<T> action) where T : IPython
  35. {
  36. try
  37. {
  38. py.__enter__();
  39. action((T)py);
  40. }
  41. catch (Exception ex)
  42. {
  43. Console.WriteLine(ex.ToString());
  44. throw ex;
  45. }
  46. finally
  47. {
  48. py.__exit__();
  49. py.Dispose();
  50. }
  51. }
  52. public static TOut with<TIn, TOut>(IPython py, Func<TIn, TOut> action) where TIn : IPython
  53. {
  54. try
  55. {
  56. py.__enter__();
  57. return action((TIn)py);
  58. }
  59. catch (Exception ex)
  60. {
  61. Console.WriteLine(ex.ToString());
  62. throw ex;
  63. }
  64. finally
  65. {
  66. py.__exit__();
  67. py.Dispose();
  68. }
  69. }
  70. public static IEnumerable<(T, T)> zip<T>(NDArray t1, NDArray t2)
  71. {
  72. int index = 0;
  73. yield return(t1.Data<T>(index), t2.Data<T>(index));
  74. }
  75. public static IEnumerable<(T, T)> zip<T>(IList<T> t1, IList<T> t2)
  76. {
  77. for (int i = 0; i < t1.Count; i++)
  78. yield return (t1[i], t2[i]);
  79. }
  80. public static IEnumerable<(int, T)> enumerate<T>(IList<T> values)
  81. {
  82. for (int i = 0; i < values.Count; i++)
  83. yield return (i, values[i]);
  84. }
  85. }
  86. public interface IPython : IDisposable
  87. {
  88. void __enter__();
  89. void __exit__();
  90. }
  91. }

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