public static FunctionBinder.ParamsFunction <X> FiniteDifference_ <X>(IList <IVar> inputs, Scalar <X> output, Tensor <X> .Shared x, IDictionary givens = null) { var epsilon = Scalar <X>("epsilon"); var i_ = Scalar <int>("i"); var j_ = Scalar <int>("j"); var k_ = Scalar <int>("k"); var indexes = new Scalar <int> .Var[0]; if (x.NDim == 1) { indexes = new[] { i_ } } ; if (x.NDim == 2) { indexes = new[] { i_, j_ } } ; if (x.NDim == 3) { indexes = new[] { i_, j_, k_ } } ; var inputSet = new List <IVar>(); foreach (var i in inputs) { inputSet.Add(i); } foreach (var i in indexes) { inputSet.Add(i); } inputSet.Add(epsilon); var eps = Op.OneHot(x.Shape, indexes, epsilon); var out_m_eps = (Scalar <X>)output.Patch(new Patch { [x] = x - eps }); var out_p_eps = (Scalar <X>)output.Patch(new Patch { [x] = x + eps }); var delta = (out_p_eps - out_m_eps) / (Numeric <X> .Two * epsilon); return(Function(inputSet, delta, givens: givens)); }
public static Tensor <Type> operator -(Tensor <Type> x) { switch (x) { case Elementwise unary when unary.Abstraction is Scalars.Neg <Type> : return(unary.Inputs[0]); // -(-x) = x case Elementwise binary when binary.Abstraction is Scalars.Sub <Type> : return(binary.Inputs[1] - binary.Inputs[0]); // -(x - y) = y - x case Fill <Type> fill: return(Op.Const(-fill.x, fill.Shape)); case OneHot <Type> oneHot: return(Op.OneHot(oneHot.Shape, oneHot.Index, -oneHot.Content)); default: return(Op.Apply(x, _x => - _x)); } }