0

I am new at tensorflow.

I try to use very simple formula to add new op in Tensorflow.

But i dont know how to define the op' gradient in code(python or C).

I already studied the sample from

https://www.tensorflow.org/extend/adding_an_op

https://github.com/davidstutz/tensorflow-cpp-op-example/blob/master/_inner_product_grad.py

Then I can't get the point.

Example: F(y,x)=y^2+x^3

bellow I already add the op in C code. And work fine for me.

    #include "tensorflow/core/framework/op.h"
    #include "tensorflow/core/framework/shape_inference.h"
    #include <math.h>
    using namespace tensorflow;

    REGISTER_OP("FunOut")
        .Input("to_funy: float")
        .Input("to_funx: float")
        .Output("funed: float")
        .SetShapeFn([](::tensorflow::shape_inference::InferenceContext* c) {
          c->set_output(0, c->input(0));
          return Status::OK();
        });

    #include "tensorflow/core/framework/op_kernel.h"

    using namespace tensorflow;

    class FunOutOp : public OpKernel {
     public:
      explicit FunOutOp(OpKernelConstruction* context) : OpKernel(context) {}

      void Compute(OpKernelContext* context) override {
        const Tensor& input_tensorY = context->input(0);
        auto inputY = input_tensorY.flat<float>();
        auto input_shapeY = input_tensorY.shape();

        const Tensor& input_tensorX = context->input(1);
        auto inputX = input_tensorX.flat<float>();
        auto input_shapeX = input_tensorX.shape();

        const int All = input_shapeX.dim_size(0);
        // Create an output tensor
        Tensor* output_tensor = NULL;
        OP_REQUIRES_OK(context, context->allocate_output(0,input_tensorY.shape(), &output_tensor));
        auto output_flat = output_tensor->flat<float>();
        for(int i = 0; i<All;i++){
            output_flat(i) = inputY(i)*inputY(i)+inputX(i)*inputX(i)*inputX(i);
        }

      }
    };

    REGISTER_KERNEL_BUILDER(Name("FunOut").Device(DEVICE_CPU), FunOutOp)

should be

        import tensorflow as tf
        from tensorflow.python.framework import ops
        ........
        @ops.RegisterGradient("Fun")
        def _fun_grad(op, grad):

        ......
        ......

        return [,]

Could someone help me? And explain. Thanks so much.

As I know, dF/dx=3*x,dF/dy=2*y, and....

Shawn Lee
  • 1
  • 2
  • for now, I know should return [grad*2*y,grad*3*x].... – Shawn Lee Jun 07 '18 at 03:53
  • If you're still watching this - there's a good example here: https://stackoverflow.com/questions/39048984/tensorflow-how-to-write-op-with-gradient-in-python/39984513#39984513 – linkhyrule5 Jun 29 '18 at 22:32

0 Answers0