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.9 kB

6 years ago
6 years ago
6 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  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 T New<T>(object args) where T : IPyClass
  17. {
  18. var instance = Activator.CreateInstance<T>();
  19. instance.__init__(instance, args);
  20. return instance;
  21. }
  22. public static void with(IPython py, Action<IPython> action)
  23. {
  24. try
  25. {
  26. py.__enter__();
  27. action(py);
  28. }
  29. catch (Exception ex)
  30. {
  31. Console.WriteLine(ex.ToString());
  32. throw ex;
  33. }
  34. finally
  35. {
  36. py.__exit__();
  37. py.Dispose();
  38. }
  39. }
  40. public static void with<T>(T py, Action<T> action) where T : IPython
  41. {
  42. try
  43. {
  44. py.__enter__();
  45. action(py);
  46. }
  47. catch (Exception ex)
  48. {
  49. Console.WriteLine(ex.ToString());
  50. throw ex;
  51. }
  52. finally
  53. {
  54. py.__exit__();
  55. py.Dispose();
  56. }
  57. }
  58. public static TOut with<TIn, TOut>(TIn py, Func<TIn, TOut> action) where TIn : IPython
  59. {
  60. try
  61. {
  62. py.__enter__();
  63. return action(py);
  64. }
  65. catch (Exception ex)
  66. {
  67. Console.WriteLine(ex.ToString());
  68. return default(TOut);
  69. }
  70. finally
  71. {
  72. py.__exit__();
  73. py.Dispose();
  74. }
  75. }
  76. public static float time()
  77. {
  78. return (float)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds;
  79. }
  80. public static IEnumerable<(T, T)> zip<T>(NDArray t1, NDArray t2)
  81. {
  82. for (int i = 0; i < t1.size; i++)
  83. yield return (t1.Data<T>(i), t2.Data<T>(i));
  84. }
  85. public static IEnumerable<(T1, T2)> zip<T1, T2>(IList<T1> t1, IList<T2> t2)
  86. {
  87. for (int i = 0; i < t1.Count; i++)
  88. yield return (t1[i], t2[i]);
  89. }
  90. public static IEnumerable<(int, T)> enumerate<T>(IList<T> values)
  91. {
  92. for (int i = 0; i < values.Count; i++)
  93. yield return (i, values[i]);
  94. }
  95. }
  96. public interface IPython : IDisposable
  97. {
  98. void __enter__();
  99. void __exit__();
  100. }
  101. public class PyObject<T> where T : IPyClass
  102. {
  103. public T Instance { get; set; }
  104. }
  105. }

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