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.

GradientsTest.cs 25 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using Microsoft.VisualStudio.TestTools.UnitTesting;
  5. using NumSharp;
  6. using Tensorflow;
  7. using static Tensorflow.Binding;
  8. namespace TensorFlowNET.UnitTest.gradients_test
  9. {
  10. [TestClass]
  11. public class GradientsTest : PythonTest
  12. {
  13. [TestMethod]
  14. public void BroadcastToGrad()
  15. {
  16. var graph = tf.Graph().as_default();
  17. var x = tf.constant(2, dtype: dtypes.float32);
  18. var y = tf.broadcast_to(x, (2, 4, 3));
  19. var grad = tf.gradients(y, x);
  20. using (var sess = tf.Session(graph))
  21. {
  22. float result = sess.run(grad[0]);
  23. Assert.AreEqual(result, 24.0f);
  24. }
  25. }
  26. [TestMethod]
  27. public void CumsumGrad()
  28. {
  29. var graph = tf.Graph().as_default();
  30. var x = tf.constant(2, dtype: dtypes.float32);
  31. var y = tf.broadcast_to(x, (2, 4, 3));
  32. var z = tf.cumsum(y, axis: 1);
  33. var grad = tf.gradients(z, x);
  34. using (var sess = tf.Session(graph))
  35. {
  36. float result = sess.run(grad[0]);
  37. Assert.AreEqual(result, 60.0f);
  38. }
  39. }
  40. [Ignore("TODO")]
  41. [TestMethod]
  42. public void testGradients()
  43. {
  44. var g = tf.Graph().as_default();
  45. var inp = tf.constant(1.0, shape: new[] { 32, 100 }, name: "in");
  46. var w = tf.constant(1.0, shape: new[] { 100, 10 }, name: "w");
  47. var b = tf.constant(1.0, shape: new[] { 10 }, name: "b");
  48. var xw = math_ops.matmul(inp, w, name: "xw");
  49. var h = nn_ops.bias_add(xw, b, name: "h");
  50. var w_grad = gradients_impl.gradients(new[] { h }, new[] { w })[0];
  51. self.assertEquals("MatMul", w_grad.op.type);
  52. // TODO: Operation._original_op
  53. //self.assertEquals(w_grad.op._original_op, xw.op);
  54. self.assertTrue((bool)w_grad.op.get_attr("transpose_a"));
  55. self.assertFalse((bool)w_grad.op.get_attr("transpose_b"));
  56. }
  57. [TestMethod]
  58. public void testBatchMatMulGradient()
  59. {
  60. var a = tf.constant(np.array(Enumerable.Range(1, 18).Select(elem => (float)elem).ToArray()), shape: new[] { 2, 3, 3 });
  61. var b = tf.divide(a, tf.constant(2.0f));
  62. var c = tf.batch_matmul(a, b);
  63. var g = tf.gradients(c, new[] { a, b }, stop_gradients: new[] { a, b });
  64. var checkG = new[]
  65. {
  66. 3.0f, 7.5f, 12.0f,
  67. 3.0f, 7.5f, 12.0f,
  68. 3.0f, 7.5f, 12.0f,
  69. 16.5f, 21.0f, 25.5f,
  70. 16.5f, 21.0f, 25.5f,
  71. 16.5f, 21.0f, 25.5f,
  72. 12.0f, 12.0f, 12.0f,
  73. 15.0f, 15.0f, 15.0f,
  74. 18.0f, 18.0f, 18.0f,
  75. 39.0f, 39.0f, 39.0f,
  76. 42.0f, 42.0f, 42.0f,
  77. 45.0f, 45.0f, 45.0f
  78. };
  79. using (var sess = tf.Session())
  80. {
  81. var result = sess.run(g);
  82. var resultList = result[0].GetData<float>().ToList();
  83. resultList.AddRange(result[1].GetData<float>());
  84. Console.WriteLine(result.ToString());
  85. CollectionAssert.AreEqual(resultList.ToArray(), checkG);
  86. }
  87. }
  88. [TestMethod]
  89. public void testTanhGradient()
  90. {
  91. var a = tf.constant(1f);
  92. var b = tf.tanh(a);
  93. var g = tf.gradients(b, a);
  94. using (var sess = tf.Session())
  95. {
  96. var result = sess.run(g);
  97. var actual = result[0].GetData<float>()[0];
  98. self.assertEquals(0.41997434127f, actual);
  99. }
  100. }
  101. [TestMethod]
  102. public void testLgammaGrad()
  103. {
  104. var a = tf.constant(5f);
  105. var b = tf.lgamma(a);
  106. var g = tf.gradients(b, a);
  107. using (var sess = tf.Session())
  108. {
  109. var result = sess.run(new object[] { g, b });
  110. var actualDeriv = result[0].GetData<float>()[0];
  111. var actual = result[1].GetData<float>()[0];
  112. self.assertEquals(1.5061177f, actualDeriv);
  113. self.assertEquals(3.17805386f, actual);
  114. }
  115. }
  116. [TestMethod]
  117. public void testSliceGrad()
  118. {
  119. var a = tf.tanh(tf.constant(new[] { 2f, 3f }, shape: new[] { 2, 1 }));
  120. var b = tf.strided_slice(a,
  121. tf.constant(new[] { 0 }, tf.int32, new[] { 1 }),
  122. tf.constant(new[] { 1 }, tf.int32, new[] { 1 }),
  123. tf.constant(new[] { 1 }, tf.int32, new[] { 1 })
  124. );
  125. var g = tf.gradients(b, a);
  126. using (var sess = tf.Session())
  127. {
  128. var result = sess.run(new object[] { g, b });
  129. var actualDeriv = np.squeeze(result[0]);
  130. var actual = np.squeeze(result[1]);
  131. self.assertEquals(new float[] { 1, 0 }, new float[] { actualDeriv[0], actualDeriv[1] });
  132. self.assertEquals(0.9640276f, (float)actual);
  133. }
  134. }
  135. [TestMethod]
  136. public void testConcatGrad()
  137. {
  138. var a1 = tf.constant(new[] { 2f }, shape: new[] { 1 });
  139. var a2 = tf.constant(new[] { 3f }, shape: new[] { 1 });
  140. var a = tf.concat(new List<Tensor>(new[] { a1, a2 }), 0);
  141. var g = tf.gradients(a, a1);
  142. using (var sess = tf.Session())
  143. {
  144. var result = sess.run(new object[] { g, a });
  145. var actualDeriv = result[0].GetData<float>()[0];
  146. var actual = result[1].GetData<float>()[0];
  147. self.assertEquals(1f, actualDeriv);
  148. self.assertEquals(2f, actual);
  149. }
  150. }
  151. [TestMethod]
  152. public void testStopGradientFunction()
  153. {
  154. var ap = tf.constant(1f);
  155. var b = tf.tanh(ap) + gen_array_ops.stop_gradient(ap);
  156. var g = tf.gradients(b, ap);
  157. using (var sess = tf.Session())
  158. {
  159. var result = sess.run(g);
  160. var actual = result[0].GetData<float>()[0];
  161. self.assertEquals(0.41997434127f, actual);
  162. }
  163. }
  164. [Ignore("TODO")]
  165. [TestMethod]
  166. public void testUnusedOutput()
  167. {
  168. //def testUnusedOutput(self):
  169. // with ops.Graph().as_default():
  170. // w = constant(1.0, shape=[2, 2])
  171. // x = constant(1.0, shape=[2, 2])
  172. // wx = math_ops.matmul(w, x)
  173. // split_wx = array_ops.split(value=wx, num_or_size_splits=2, axis=0)
  174. // c = math_ops.reduce_sum(split_wx[1])
  175. // gw = gradients.gradients(c, [w])[0]
  176. // self.assertEquals("MatMul", gw.op.type)
  177. }
  178. [Ignore("TODO")]
  179. [TestMethod]
  180. public void testColocateGradients()
  181. {
  182. //def testColocateGradients(self):
  183. // with ops.Graph().as_default() as g:
  184. // w = constant(1.0, shape=[1, 1])
  185. // x = constant(1.0, shape=[1, 2])
  186. // with g.device("/device:GPU:0"):
  187. // wx = math_ops.matmul(w, x)
  188. // gw = gradients.gradients(wx, [w], colocate_gradients_with_ops=True)[0]
  189. // self.assertEqual(gw.op.colocation_groups(), wx.op.colocation_groups())
  190. }
  191. [Ignore("TODO")]
  192. [TestMethod]
  193. public void testColocateGradientsWithAggregation()
  194. {
  195. //def testColocateGradientsWithAggregation(self):
  196. // with ops.Graph().as_default() as g:
  197. // with g.device("/device:GPU:1"):
  198. // w = constant(1.0, shape=[1, 1])
  199. // x = constant(1.0, shape=[1, 2])
  200. // y = constant(1.0, shape=[1, 2])
  201. // wx = math_ops.matmul(w, x)
  202. // wy = math_ops.matmul(w, y)
  203. // with g.device("/device:GPU:0"):
  204. // z = wx + wy
  205. // gw1 = gradients.gradients(z, [w], colocate_gradients_with_ops=True)[0]
  206. // self.assertEqual(gw1.op.colocation_groups(), wx.op.colocation_groups())
  207. // gw2 = gradients.gradients(z, [w], colocate_gradients_with_ops=False)[0]
  208. // self.assertTrue(wx.op.colocation_groups() != gw2.op.colocation_groups())
  209. }
  210. [Ignore("TODO")]
  211. [TestMethod]
  212. public void testColocateGradientsWithAggregationInMultipleDevices()
  213. {
  214. //def testColocateGradientsWithAggregationInMultipleDevices(self):
  215. // with ops.Graph().as_default() as g:
  216. // with g.device("/device:GPU:1"):
  217. // w = constant(1.0, shape=[1, 1])
  218. // x = constant(1.0, shape=[1, 2])
  219. // y = constant(1.0, shape=[1, 2])
  220. // with g.device("/task:1"):
  221. // wx = math_ops.matmul(w, x)
  222. // with g.device("/task:2"):
  223. // wy = math_ops.matmul(w, y)
  224. // with g.device("/device:GPU:0"):
  225. // z = wx + wy
  226. // gw1 = gradients.gradients(z, [w], colocate_gradients_with_ops=True)[0]
  227. // self.assertEqual(gw1.op.colocation_groups(), w.op.colocation_groups())
  228. // gw2 = gradients.gradients(z, [w], colocate_gradients_with_ops=False)[0]
  229. // self.assertTrue(w.op.colocation_groups() != gw2.op.colocation_groups())
  230. }
  231. [Ignore("TODO")]
  232. [TestMethod]
  233. public void testColocateGradientsWithGateGradients()
  234. {
  235. //def testColocateGradientsWithGateGradients(self):
  236. // if not test_util.is_gpu_available():
  237. // self.skipTest("No GPU available")
  238. // with ops.Graph().as_default() as g:
  239. // with g.device("/device:CPU:0"):
  240. // x = constant(1.0, shape=[1, 1])
  241. // y = constant(1.0, shape=[1, 1])
  242. // s = x + y
  243. // with g.device("/device:GPU:0"):
  244. // z = math_ops.reduce_sum(s)
  245. // gz_x = gradients.gradients(z, [x], colocate_gradients_with_ops=True,
  246. // gate_gradients=True)[0]
  247. // with session.Session():
  248. // # Make sure the placer doesn't complain.
  249. // self.evaluate(gz_x)
  250. }
  251. [Ignore("TODO")]
  252. [TestMethod]
  253. public void testBoundaryStop()
  254. {
  255. //def testBoundaryStop(self):
  256. // # Test that we don't differentiate 'x'. The gradient function for 'x' is
  257. // # set explicitly to None so we will get an exception if the gradient code
  258. // # tries to differentiate 'x'.
  259. // with ops.Graph().as_default():
  260. // c = constant(1.0)
  261. // x = array_ops.identity(c)
  262. // y = x + 1.0
  263. // z = y + 1
  264. // grads = gradients.gradients(z, [x])
  265. // self.assertTrue(all(x is not None for x in grads))
  266. }
  267. [Ignore("TODO")]
  268. [TestMethod]
  269. public void testBoundaryContinue()
  270. {
  271. //@test_util.run_v1_only("b/120545219")
  272. //def testBoundaryContinue(self):
  273. // # Test that we differentiate both 'x' and 'y' correctly when x is a
  274. // # predecessor of y.
  275. // with self.cached_session():
  276. // x = constant(1.0)
  277. // y = x * 2.0
  278. // z = y * 3.0
  279. // grads = gradients.gradients(z, [x, y])
  280. // self.assertTrue(all(x is not None for x in grads))
  281. // self.assertEqual(6.0, grads[0].eval())
  282. }
  283. [Ignore("TODO")]
  284. [TestMethod]
  285. public void testAggregationMethodAccumulateN()
  286. {
  287. //@test_util.run_v1_only("b/120545219")
  288. //def testAggregationMethodAccumulateN(self):
  289. // with self.cached_session():
  290. // x = constant(1.0)
  291. // y = x * 2.0
  292. // z = y + y + y + y + y + y + y + y + y + y
  293. // grads = gradients.gradients(
  294. // z, [x, y],
  295. // aggregation_method=gradients.AggregationMethod.
  296. // EXPERIMENTAL_ACCUMULATE_N)
  297. // self.assertTrue(all(x is not None for x in grads))
  298. // self.assertEqual(20.0, grads[0].eval())
  299. // self.assertEqual(10.0, grads[1].eval())
  300. }
  301. [Ignore("TODO")]
  302. [TestMethod]
  303. public void testAggregationMethodAddN()
  304. {
  305. //@test_util.run_v1_only("b/120545219")
  306. //def testAggregationMethodAddN(self):
  307. // with self.cached_session():
  308. // x = constant(1.0)
  309. // y = x * 2.0
  310. // z = y + y + y + y + y + y + y + y + y + y
  311. // grads = gradients.gradients(
  312. // z, [x, y], aggregation_method=gradients.AggregationMethod.ADD_N)
  313. // self.assertTrue(all(x is not None for x in grads))
  314. // self.assertEqual(20.0, grads[0].eval())
  315. // self.assertEqual(10.0, grads[1].eval())
  316. }
  317. [Ignore("TODO")]
  318. [TestMethod]
  319. public void testAggregationMethodTree()
  320. {
  321. //@test_util.run_v1_only("b/120545219")
  322. //def testAggregationMethodTree(self):
  323. // with self.cached_session():
  324. // x = constant(1.0)
  325. // y = x * 2.0
  326. // z = y + y + y + y + y + y + y + y + y + y
  327. // grads = gradients.gradients(
  328. // z, [x, y],
  329. // aggregation_method=gradients.AggregationMethod.EXPERIMENTAL_TREE)
  330. // self.assertTrue(all(x is not None for x in grads))
  331. // self.assertEqual(20.0, grads[0].eval())
  332. // self.assertEqual(10.0, grads[1].eval())
  333. }
  334. [Ignore("TODO")]
  335. [TestMethod]
  336. public void testNoGradientForStringOutputs()
  337. {
  338. //def testNoGradientForStringOutputs(self):
  339. // with ops.Graph().as_default():
  340. // def _TestOpGrad(_, float_grad, string_grad):
  341. // """Gradient function for TestStringOutput."""
  342. // self.assertEquals(float_grad.dtype, dtypes.float32)
  343. // self.assertFalse(string_grad)
  344. // return float_grad
  345. // ops.RegisterGradient("TestStringOutput")(_TestOpGrad)
  346. // c = constant(1.0)
  347. // x, _ = test_ops.test_string_output(c)
  348. // z = x * 2.0
  349. // w = z * 3.0
  350. // grads = gradients.gradients(z, [c])
  351. // self.assertTrue(isinstance(grads[0], ops.Tensor))
  352. // grads = gradients.gradients(w, [c])
  353. // self.assertTrue(isinstance(grads[0], ops.Tensor))
  354. }
  355. [Ignore("TODO")]
  356. [TestMethod]
  357. public void testSingletonIndexedSlices()
  358. {
  359. //def testSingletonIndexedSlices(self):
  360. // with ops.Graph().as_default():
  361. // x = array_ops.placeholder(dtypes.float32)
  362. // y = array_ops.identity(x)
  363. // dy = ops.IndexedSlices(
  364. // array_ops.placeholder(dtypes.float32),
  365. // array_ops.placeholder(dtypes.int32))
  366. // dx, = gradients.gradients(y, x, grad_ys=dy)
  367. // # The IndexedSlices gradient of tf.identity is the identity map.
  368. // with self.cached_session() as sess:
  369. // vdx, vdy = sess.run(
  370. // [dx, dy], feed_dict={x: [1.0], dy.indices: [0], dy.values: [2.0]})
  371. // self.assertEqual(vdx, vdy)
  372. }
  373. [Ignore("TODO")]
  374. [TestMethod]
  375. public void testNonDifferentiableSwitchInWhileLoop()
  376. {
  377. //@test_util.run_v1_only("b/120545219")
  378. //def testNonDifferentiableSwitchInWhileLoop(self):
  379. // with ops.Graph().as_default():
  380. // v = array_ops.placeholder(dtypes.float32, [])
  381. // def _Step(i, a, ta):
  382. // a += math_ops.cast(v, dtypes.int32)
  383. // return (i + 1, a, ta.write(i, a))
  384. // n = 4
  385. // i, _, ta = control_flow_ops.while_loop(
  386. // lambda i, *_: i < n,
  387. // _Step, [0, 0, tensor_array_ops.TensorArray(
  388. // dtypes.int32, size=n)])
  389. // target = ta.read(i - 1)
  390. // grad, = gradients.gradients(target, v)
  391. // self.assertIsNone(grad)
  392. }
  393. [Ignore("TODO")]
  394. [TestMethod]
  395. public void testVariableReadValueGradient()
  396. {
  397. //def testVariableReadValueGradient(self):
  398. // with ops.Graph().as_default():
  399. // init = constant_op.constant(100.0)
  400. // var = variables.Variable(init)
  401. // gradient = gradients.gradients(var.read_value(), var)
  402. // self.assertIsNotNone(gradient)
  403. }
  404. [Ignore("TODO")]
  405. [TestMethod]
  406. public void testVariableAsGraphElementGradient()
  407. {
  408. //def testVariableAsGraphElementGradient(self):
  409. // with ops.Graph().as_default() as graph:
  410. // init = constant_op.constant(100.0)
  411. // var = variables.Variable(init)
  412. // gradient = gradients.gradients(graph.as_graph_element(var), var)
  413. // self.assertIsNotNone(gradient)
  414. }
  415. [Ignore("TODO")]
  416. [TestMethod]
  417. public void testVariableRefGradient()
  418. {
  419. //@test_util.run_v1_only("b/120545219")
  420. //def testVariableRefGradient(self):
  421. // with ops.Graph().as_default():
  422. // init = constant_op.constant(100.0)
  423. // var = variables.VariableV1(init)
  424. // gradient = gradients.gradients(var._ref(), var)
  425. // self.assertIsNotNone(gradient)
  426. }
  427. [Ignore("TODO")]
  428. [TestMethod]
  429. public void testDependentYs()
  430. {
  431. //@test_util.run_v1_only("b/120545219")
  432. //def testDependentYs(self):
  433. // with self.cached_session():
  434. // x = constant_op.constant(3.0)
  435. // y = math_ops.square(x)
  436. // y1 = math_ops.square(y)
  437. // y2 = math_ops.square(y1)
  438. // g = gradients.gradients([y, y2], x)
  439. // self.assertAllClose(17502.0, g[0].eval())
  440. // g = gradients.gradients(y + y2, x)
  441. // self.assertAllClose(17502.0, g[0].eval())
  442. // z = array_ops.identity(y)
  443. // z2 = array_ops.identity(y2)
  444. // g = gradients.gradients([z, z2], x)
  445. // self.assertAllClose(17502.0, g[0].eval())
  446. }
  447. [Ignore("TODO")]
  448. [TestMethod]
  449. public void testPartialDerivatives()
  450. {
  451. //@test_util.run_v1_only("b/120545219")
  452. //def testPartialDerivatives(self):
  453. // with self.cached_session():
  454. // x = constant_op.constant(1.)
  455. // y = 2 * x
  456. // z = x + y
  457. // totalg = gradients.gradients(z, [x, y])
  458. // self.assertEqual([3.0, 1.0], [g.eval() for g in totalg])
  459. // partialg = gradients.gradients(z, [x, y], stop_gradients=[x, y])
  460. // self.assertEqual([1.0, 1.0], [g.eval() for g in partialg])
  461. }
  462. [Ignore("TODO")]
  463. [TestMethod]
  464. public void testStopGradients()
  465. {
  466. //@test_util.run_v1_only("b/120545219")
  467. //def testStopGradients(self):
  468. // def _MakeGraph(rng, stop_gradients=()):
  469. // def _FunctionOf(xs, k=3):
  470. // return ops.convert_to_tensor(
  471. // sum(math_ops.matmul(rng.rand(k, k), x) for x in xs)
  472. // + rng.rand(k, k))
  473. // a = _FunctionOf([])
  474. // if "a" in stop_gradients: a = array_ops.stop_gradient(a)
  475. // b = _FunctionOf([a])
  476. // if "b" in stop_gradients: b = array_ops.stop_gradient(b)
  477. // c = _FunctionOf([a, b])
  478. // if "c" in stop_gradients: c = array_ops.stop_gradient(c)
  479. // d = _FunctionOf([b, c])
  480. // if "d" in stop_gradients: d = array_ops.stop_gradient(d)
  481. // return dict(a=a, b=b, c=c, d=d)
  482. // def _Gradients(ys, xs, **kwargs):
  483. // dydxs = gradients.gradients(ys, xs, **kwargs)
  484. // dydxs = [0. * x if dydx is None else dydx
  485. // for x, dydx in zip(xs, dydxs)]
  486. // return dydxs
  487. // seed = np.random.randint(1000)
  488. // cases = []
  489. // subsets = [""] + "a b c d ab ac ad bc bd cd abc abd acd bcd abcd".split()
  490. // graph = _MakeGraph(np.random.RandomState(seed))
  491. // for constants in subsets:
  492. // graph_with_stops = _MakeGraph(np.random.RandomState(seed), constants)
  493. // for variables_ in subsets:
  494. // # compute the gradient when stopped using tf.stop_gradients
  495. // grad1 = _Gradients([graph_with_stops["d"]],
  496. // [graph_with_stops[v] for v in variables_])
  497. // # compute the gradient when stopped using the stop_gradients kwarg
  498. // grad2 = _Gradients([graph["d"]],
  499. // [graph[v] for v in variables_],
  500. // stop_gradients=[graph[v] for v in constants])
  501. // cases.append(dict(grad1=grad1, grad2=grad2,
  502. // constants=constants, variables=variables_))
  503. // # evaluate all tensors in one call to session.run for speed
  504. // with self.cached_session() as sess:
  505. // results = sess.run([(case["grad1"], case["grad2"]) for case in cases])
  506. // for (npgrad1, npgrad2), case in zip(results, cases):
  507. // for a, b in zip(npgrad1, npgrad2):
  508. // np.testing.assert_allclose(a, b)
  509. }
  510. [Ignore("TODO")]
  511. [TestMethod]
  512. public void testUnconnectedGradientsNoneUnconnectedGradients()
  513. {
  514. //def testUnconnectedGradientsNoneUnconnectedGradients(self):
  515. // with ops.Graph().as_default():
  516. // x = constant(1.0, shape=[2, 2])
  517. // y = constant(3.0, shape=[3, 1])
  518. // grad = gradients.gradients(
  519. // [y], [x], unconnected_gradients="none")
  520. // self.assertIsNone(grad[0])
  521. }
  522. [Ignore("TODO")]
  523. [TestMethod]
  524. public void testUnconnectedGradientsZerosUnconnectedGradients()
  525. {
  526. //def testUnconnectedGradientsZerosUnconnectedGradients(self):
  527. // with ops.Graph().as_default():
  528. // x = constant(1.0, shape=[2, 2])
  529. // y = constant(3.0, shape=[3, 1])
  530. // grads = gradients.gradients(
  531. // [y], [x], unconnected_gradients="zero")
  532. // with self.cached_session() as sess:
  533. // self.assertAllEqual([[0.0, 0.0], [0.0, 0.0]], self.evaluate(grads)[0])
  534. }
  535. [Ignore("TODO")]
  536. [TestMethod]
  537. public void testUnconnectedGradientsZeroConnectedGradients()
  538. {
  539. //def testUnconnectedGradientsZeroConnectedGradients(self):
  540. // with ops.Graph().as_default():
  541. // x = constant(1.0)
  542. // y = x * 3.0
  543. // grad = gradients.gradients(
  544. // [y], [x], unconnected_gradients="zero")
  545. // with self.cached_session() as sess:
  546. // self.assertEquals(3.0, self.evaluate(grad)[0])
  547. }
  548. [Ignore("TODO")]
  549. [TestMethod]
  550. public void testUnknownUnconnectedGradientsValueGiven()
  551. {
  552. //def testUnknownUnconnectedGradientsValueGiven(self):
  553. // with ops.Graph().as_default():
  554. // x = constant(1.0)
  555. // y = constant(1.0)
  556. // with self.assertRaisesRegexp(
  557. // ValueError, "Unknown value for unconnected_gradients: 'nonsense'"):
  558. // gradients.gradients([y], [x], unconnected_gradients="nonsense")
  559. }
  560. /*
  561. */
  562. }
  563. }