Skip to content

Add shape deduce for mean square error grad. #1010

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/TensorFlowNET.Core/Gradients/math_grad.cs
Original file line number Diff line number Diff line change
Expand Up @@ -840,7 +840,7 @@ public static Tensor[] _PowGrad(Operation op, Tensor[] grads)
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns></returns>
private static (Tensor, Tensor, bool)[] SmartBroadcastGradientArgs(Tensor x, Tensor y, Tensor grad)
public static (Tensor, Tensor, bool)[] SmartBroadcastGradientArgs(Tensor x, Tensor y, Tensor grad)
{
Tensor sx, sy;
if (x.shape.IsFullyDefined &&
Expand Down
33 changes: 28 additions & 5 deletions src/TensorFlowNET.Core/Gradients/nn_grad.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ limitations under the License.
******************************************************************************/

using System;
using System.Diagnostics;
using System.Linq;
using Tensorflow.Operations;
using static Tensorflow.Binding;
Expand Down Expand Up @@ -135,13 +136,35 @@ public static Tensor[] _SquaredDifferenceGrad(Operation op, Tensor[] grads)
{
Tensor x = op.inputs[0];
Tensor y = op.inputs[1];
var grad = grads[0];
var scale = ops.convert_to_tensor(2.0f, dtype: x.dtype);
var x_grad = math_ops.scalar_mul(scale, grads[0]) * (x - y);
return new Tensor[]
var x_grad = math_ops.scalar_mul(scale, grad) * (x - y);
if (math_grad._ShapesFullySpecifiedAndEqual(x, y, grad))
{
x_grad,
-x_grad
};
return new Tensor[] { x_grad, -x_grad };
}
var broadcast_info = math_grad.SmartBroadcastGradientArgs(x, y, grad);
Debug.Assert(broadcast_info.Length == 2);
var (sx, rx, must_reduce_x) = broadcast_info[0];
var (sy, ry, must_reduce_y) = broadcast_info[1];
Tensor gx, gy;
if (must_reduce_x)
{
gx = array_ops.reshape(math_ops.reduce_sum(x_grad, rx), sx);
}
else
{
gx = x_grad;
}
if (must_reduce_y)
{
gy = -array_ops.reshape(math_ops.reduce_sum(x_grad, ry), sy);
}
else
{
gy = -x_grad;
}
return new Tensor[] { gx, gy };
}

/// <summary>
Expand Down