Skip to content

Commit f3427cb

Browse files
committed
fixed operand should be mul/x:0 SciSharp#155
1 parent 8c2c18a commit f3427cb

4 files changed

Lines changed: 43 additions & 3 deletions

File tree

‎src/TensorFlowNET.Core/Gradients/gradients_impl.py.cs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -146,7 +146,7 @@ public static Tensor[] _GradientsHelper(Tensor[] ys,
146146
var inputs = _NonEagerInputs(op, xs).ToList();
147147
foreach (var (t_in, in_grad) in Python.zip(inputs, in_grads))
148148
{
149-
if(in_grad != null)
149+
if(in_grad.op != null)
150150
{
151151
in_grad.shape = t_in.shape;
152152
_SetGrad(grads, t_in, in_grad);

‎src/TensorFlowNET.Core/Python.cs‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,25 @@ public static void with<T>(IPython py, Action<T> action) where T : IPython
5353
}
5454
}
5555

56+
public static TOut with<TIn, TOut>(IPython py, Func<TIn, TOut> action) where TIn : IPython
57+
{
58+
try
59+
{
60+
py.__enter__();
61+
return action((TIn)py);
62+
}
63+
catch (Exception ex)
64+
{
65+
Console.WriteLine(ex.ToString());
66+
throw ex;
67+
}
68+
finally
69+
{
70+
py.__exit__();
71+
py.Dispose();
72+
}
73+
}
74+
5675
public static IEnumerable<(T, T)> zip<T>(NDArray t1, NDArray t2)
5776
{
5877
int index = 0;

‎src/TensorFlowNET.Core/Tensors/Tensor.Operators.cs‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,16 @@ public partial class Tensor
2323
return gen_math_ops.sub(t1, t2);
2424
}
2525

26+
public static Tensor operator *(double x, Tensor y)
27+
{
28+
return Python.with<ops.name_scope, Tensor>(new ops.name_scope("", "mul", new { x, y }),
29+
scope =>
30+
{
31+
var x1 = ops.convert_to_tensor(x, y.dtype.as_base_dtype(), name: "x");
32+
return gen_math_ops.mul(x1, y, name: scope);
33+
});
34+
}
35+
2636
public static Tensor operator *(Tensor x, Tensor y)
2737
{
2838
Tensor t = null;

‎test/TensorFlowNET.UnitTest/GradientTest.cs‎

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,19 @@ public void Gradients()
1414
{
1515
var a = tf.constant(0.0);
1616
var b = 2.0 * a;
17-
var c = a + b;
18-
var g = tf.gradients(c, new Tensor[] { a, b }, stop_gradients: new Tensor[] { a, b });
17+
Assert.AreEqual(b.name, "mul:0");
18+
Assert.AreEqual(b.op.inputs[0].name, "mul/x:0");
19+
Assert.AreEqual(b.op.inputs[1].name, "Const:0");
20+
21+
var ys = a + b;
22+
Assert.AreEqual(ys.name, "add:0");
23+
Assert.AreEqual(ys.op.inputs[0].name, "Const:0");
24+
Assert.AreEqual(ys.op.inputs[1].name, "mul:0");
25+
26+
var xs = new Tensor[] { a, b };
27+
var g = tf.gradients(ys, xs, stop_gradients: new Tensor[] { a, b });
28+
Assert.AreEqual(g[0].name, "gradients/Fill:0");
29+
Assert.AreEqual(g[1].name, "gradients/Fill:0");
1930
}
2031
}
2132
}

0 commit comments

Comments
 (0)