开源 企业版 高校版 私有云 模力方舟 AI 队友
代码拉取完成,页面将自动刷新
捐赠
捐赠前请先登录
扫描微信二维码支付
取消
支付完成
支付提示
将跳转至支付宝完成支付
确定
取消
1 Star 0 Fork 11

pepure/TensorFlow.NET

加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
已有帐号? 立即登录
文件
master
分支 (30)
标签 (6)
master
v0.15-tensorflow1.15
v0.20-tensorflow2.0
sharwell/renormalize
v0.14-maintenance
v0.13-lstm
singlethreaded-support
tensor-conversions
v0.12-rnn
exception-swallow-issue404
numsharp-upgrade-version
unknown-dimension
keras-activations
autocast-tensor
tensor-operators
multithreading
gc-deallocation
perf-ops
v0.11-maintenance
revert-353-add-tf-nn-in_top_k
v0.13
v0.12
v0.10
v0.9
v0.8.0
v0.1.0-Tensor
master
分支 (30)
标签 (6)
master
v0.15-tensorflow1.15
v0.20-tensorflow2.0
sharwell/renormalize
v0.14-maintenance
v0.13-lstm
singlethreaded-support
tensor-conversions
v0.12-rnn
exception-swallow-issue404
numsharp-upgrade-version
unknown-dimension
keras-activations
autocast-tensor
tensor-operators
multithreading
gc-deallocation
perf-ops
v0.11-maintenance
revert-353-add-tf-nn-in_top_k
v0.13
v0.12
v0.10
v0.9
v0.8.0
v0.1.0-Tensor
克隆/下载
克隆/下载
提示
下载代码请复制以下命令到终端执行
为确保你提交的代码身份被 Gitee 正确识别,请执行以下命令完成配置
初次使用 SSH 协议进行代码克隆、推送等操作时,需按下述提示完成 SSH 配置
1 生成 RSA 密钥
2 获取 RSA 公钥内容,并配置到 SSH公钥
在 Gitee 上使用 SVN,请访问 使用指南
使用 HTTPS 协议时,命令行会出现如下账号密码验证步骤。基于安全考虑,Gitee 建议 配置并使用私人令牌 替代登录密码进行克隆、推送等操作
Username for 'https://gitee.com': userName
Password for 'https://userName@gitee.com': # 私人令牌
master
分支 (30)
标签 (6)
master
v0.15-tensorflow1.15
v0.20-tensorflow2.0
sharwell/renormalize
v0.14-maintenance
v0.13-lstm
singlethreaded-support
tensor-conversions
v0.12-rnn
exception-swallow-issue404
numsharp-upgrade-version
unknown-dimension
keras-activations
autocast-tensor
tensor-operators
multithreading
gc-deallocation
perf-ops
v0.11-maintenance
revert-353-add-tf-nn-in_top_k
v0.13
v0.12
v0.10
v0.9
v0.8.0
v0.1.0-Tensor
PythonTest.cs 12.42 KB
一键复制 编辑 原始数据 按行查看 历史
一剑 提交于 2020年03月02日 10:59 +08:00 . Rename IObjectLife to ITensorFlowObject
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334
using System;
using System.Collections;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Newtonsoft.Json.Linq;
using NumSharp;
using Tensorflow;
using static Tensorflow.Binding;
namespace TensorFlowNET.UnitTest
{
/// <summary>
/// Use as base class for test classes to get additional assertions
/// </summary>
public class PythonTest
{
#region python compatibility layer
protected PythonTest self { get => this; }
protected object None
{
get { return null; }
}
#endregion
#region pytest assertions
public void assertItemsEqual(ICollection given, ICollection expected)
{
if (given is Hashtable && expected is Hashtable)
{
Assert.AreEqual(JObject.FromObject(expected).ToString(), JObject.FromObject(given).ToString());
return;
}
Assert.IsNotNull(expected);
Assert.IsNotNull(given);
var e = expected.OfType<object>().ToArray();
var g = given.OfType<object>().ToArray();
Assert.AreEqual(e.Length, g.Length, $"The collections differ in length expected {e.Length} but got {g.Length}");
for (int i = 0; i < e.Length; i++)
{
/*if (g[i] is NDArray && e[i] is NDArray)
assertItemsEqual((g[i] as NDArray).GetData<object>(), (e[i] as NDArray).GetData<object>());
else*/ if (e[i] is ICollection && g[i] is ICollection)
assertEqual(g[i], e[i]);
else
Assert.AreEqual(e[i], g[i], $"Items differ at index {i}, expected {e[i]} but got {g[i]}");
}
}
public void assertAllEqual(ICollection given, ICollection expected)
{
assertItemsEqual(given, expected);
}
public void assertFloat32Equal(float expected, float actual, string msg)
{
float eps = 1e-6f;
Assert.IsTrue(Math.Abs(expected - actual) < eps * Math.Max(1.0f, Math.Abs(expected)), $"{msg}: expected {expected} vs actual {actual}");
}
public void assertFloat64Equal(double expected, double actual, string msg)
{
double eps = 1e-16f;
Assert.IsTrue(Math.Abs(expected - actual) < eps * Math.Max(1.0f, Math.Abs(expected)), $"{msg}: expected {expected} vs actual {actual}");
}
public void assertEqual(object given, object expected)
{
/*if (given is NDArray && expected is NDArray)
{
assertItemsEqual((given as NDArray).GetData<object>(), (expected as NDArray).GetData<object>());
return;
}*/
if (given is Hashtable && expected is Hashtable)
{
Assert.AreEqual(JObject.FromObject(expected).ToString(), JObject.FromObject(given).ToString());
return;
}
if (given is ICollection && expected is ICollection)
{
assertItemsEqual(given as ICollection, expected as ICollection);
return;
}
if (given is float && expected is float)
{
assertFloat32Equal((float)expected, (float)given, "");
return;
}
if (given is double && expected is double)
{
assertFloat64Equal((double)expected, (double)given, "");
return;
}
Assert.AreEqual(expected, given);
}
public void assertEquals(object given, object expected)
{
assertEqual(given, expected);
}
public void assert(object given)
{
if (given is bool)
Assert.IsTrue((bool)given);
Assert.IsNotNull(given);
}
public void assertIsNotNone(object given)
{
Assert.IsNotNull(given);
}
public void assertFalse(bool cond)
{
Assert.IsFalse(cond);
}
public void assertTrue(bool cond)
{
Assert.IsTrue(cond);
}
public void assertAllClose(NDArray array1, NDArray array2, double eps = 1e-5)
{
Assert.IsTrue(np.allclose(array1, array2, rtol: eps));
}
public void assertAllClose(double value, NDArray array2, double eps = 1e-5)
{
var array1 = np.ones_like(array2) * value;
Assert.IsTrue(np.allclose(array1, array2, rtol: eps));
}
public void assertProtoEquals(object toProto, object o)
{
throw new NotImplementedException();
}
#endregion
#region tensor evaluation and test session
//protected object _eval_helper(Tensor[] tensors)
//{
// if (tensors == null)
// return null;
// return nest.map_structure(self._eval_tensor, tensors);
//}
protected object _eval_tensor(object tensor)
{
if (tensor == None)
return None;
//else if (callable(tensor))
// return self._eval_helper(tensor())
else
{
try
{
//TODO:
// if sparse_tensor.is_sparse(tensor):
// return sparse_tensor.SparseTensorValue(tensor.indices, tensor.values,
// tensor.dense_shape)
//return (tensor as Tensor).numpy();
}
catch (Exception)
{
throw new ValueError("Unsupported type: " + tensor.GetType());
}
return null;
}
}
/// <summary>
/// This function is used in many original tensorflow unit tests to evaluate tensors
/// in a test session with special settings (for instance constant folding off)
///
/// </summary>
public T evaluate<T>(Tensor tensor)
{
object result = null;
// if context.executing_eagerly():
// return self._eval_helper(tensors)
// else:
{
using (var sess = tf.Session())
{
var ndarray=tensor.eval(sess);
if (typeof(T) == typeof(double))
{
double x = ndarray;
result=x;
}
else if (typeof(T) == typeof(int))
{
int x = ndarray;
result = x;
}
else
{
result = ndarray;
}
}
return (T)result;
}
}
public Session cached_session()
{
throw new NotImplementedException();
}
//Returns a TensorFlow Session for use in executing tests.
public Session session(Graph graph = null, object config = null, bool use_gpu = false, bool force_gpu = false)
{
//Note that this will set this session and the graph as global defaults.
//Use the `use_gpu` and `force_gpu` options to control where ops are run.If
//`force_gpu` is True, all ops are pinned to `/device:GPU:0`. Otherwise, if
//`use_gpu` is True, TensorFlow tries to run as many ops on the GPU as
//possible.If both `force_gpu and `use_gpu` are False, all ops are pinned to
//the CPU.
//Example:
//```python
//class MyOperatorTest(test_util.TensorFlowTestCase):
// def testMyOperator(self):
// with self.session(use_gpu= True):
// valid_input = [1.0, 2.0, 3.0, 4.0, 5.0]
// result = MyOperator(valid_input).eval()
// self.assertEqual(result, [1.0, 2.0, 3.0, 5.0, 8.0]
// invalid_input = [-1.0, 2.0, 7.0]
// with self.assertRaisesOpError("negative input not supported"):
// MyOperator(invalid_input).eval()
//```
//Args:
// graph: Optional graph to use during the returned session.
// config: An optional config_pb2.ConfigProto to use to configure the
// session.
// use_gpu: If True, attempt to run as many ops as possible on GPU.
// force_gpu: If True, pin all ops to `/device:GPU:0`.
//Yields:
// A Session object that should be used as a context manager to surround
// the graph building and execution code in a test case.
Session s = null;
//if (context.executing_eagerly())
// yield None
//else
//{
s = self._create_session(graph, config, force_gpu);
self._constrain_devices_and_set_default(s, use_gpu, force_gpu);
//}
return s.as_default();
}
private ITensorFlowObject _constrain_devices_and_set_default(Session sess, bool useGpu, bool forceGpu)
{
//def _constrain_devices_and_set_default(self, sess, use_gpu, force_gpu):
//"""Set the session and its graph to global default and constrain devices."""
//if context.executing_eagerly():
// yield None
//else:
// with sess.graph.as_default(), sess.as_default():
// if force_gpu:
// # Use the name of an actual device if one is detected, or
// # '/device:GPU:0' otherwise
// gpu_name = gpu_device_name()
// if not gpu_name:
// gpu_name = "/device:GPU:0"
// with sess.graph.device(gpu_name):
// yield sess
// elif use_gpu:
// yield sess
// else:
// with sess.graph.device("/device:CPU:0"):
// yield sess
return sess;
}
// See session() for details.
private Session _create_session(Graph graph, object cfg, bool forceGpu)
{
var prepare_config = new Func<object, object>((config) =>
{
// """Returns a config for sessions.
// Args:
// config: An optional config_pb2.ConfigProto to use to configure the
// session.
// Returns:
// A config_pb2.ConfigProto object.
//TODO: config
// # use_gpu=False. Currently many tests rely on the fact that any device
// # will be used even when a specific device is supposed to be used.
// allow_soft_placement = not force_gpu
// if config is None:
// config = config_pb2.ConfigProto()
// config.allow_soft_placement = allow_soft_placement
// config.gpu_options.per_process_gpu_memory_fraction = 0.3
// elif not allow_soft_placement and config.allow_soft_placement:
// config_copy = config_pb2.ConfigProto()
// config_copy.CopyFrom(config)
// config = config_copy
// config.allow_soft_placement = False
// # Don't perform optimizations for tests so we don't inadvertently run
// # gpu ops on cpu
// config.graph_options.optimizer_options.opt_level = -1
// # Disable Grappler constant folding since some tests & benchmarks
// # use constant input and become meaningless after constant folding.
// # DO NOT DISABLE GRAPPLER OPTIMIZERS WITHOUT CONSULTING WITH THE
// # GRAPPLER TEAM.
// config.graph_options.rewrite_options.constant_folding = (
// rewriter_config_pb2.RewriterConfig.OFF)
// config.graph_options.rewrite_options.pin_to_host_optimization = (
// rewriter_config_pb2.RewriterConfig.OFF)
return config;
});
//TODO: use this instead of normal session
//return new ErrorLoggingSession(graph = graph, config = prepare_config(config))
return new Session(graph);//, config = prepare_config(config))
}
#endregion
}
}
Loading...
举报
举报成功
我们将于2个工作日内通过站内信反馈结果给你!
请认真填写举报原因,尽可能描述详细。
请选择举报类型
取消
发送
误判申诉

此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。

如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。

取消
提交

简介

TensorFlow.NET 为 TensorFlow 提供 .NET 标准绑定
取消

发行版

暂无发行版

贡献者

全部

近期动态

不能加载更多了
编辑仓库简介
简介内容
主页
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C#
1
https://gitee.com/pepure/TensorFlow.NET.git
git@gitee.com:pepure/TensorFlow.NET.git
pepure
TensorFlow.NET
TensorFlow.NET
master
点此查找更多帮助

搜索帮助

评论
仓库举报
回到顶部
登录提示
该操作需登录 Gitee 帐号,请先登录后再操作。
立即登录
没有帐号,去注册

AltStyle によって変換されたページ (->オリジナル) /