human
Can you provide a the Python code you requested given the following:
I am working on the file "GTSDB/GTSDB_RPN_Train.ipynb".
The first task is:
Losses
Loss functions as defined in the frcnn paper:
L({pi}, {ti}) = (1/Ncls) Σ Lcls(pi, pi*) + λ(1/Nreg) Σ pi* Lreg(ti, ti*)
In this implementation we ignore the balancing factor λ and the normalization, which the paper say is okay:
L({pi}, {ti}) = Σ Lcls(pi, pi*) + Σ pi* Lreg(ti, ti*)
where Lcls is binary log loss
and Lreg is robust loss
Here, rpn_cls_loss is Σ Lcls(pi, pi*)
and rpn_regr_loss is Σ pi* Lreg(ti, ti*)
Can you write Python code for it?
assistant
#Here is the Python code you requested.

def rpn_regr_loss(num_ancs):
    def loss(ytrue, ypred, ptrue):
        # ytrue.shape = (rows, cols, num_ancs * 4)
        # ypred.shape = (rows, cols, num_ancs * 4)
        # ptrue.shape = (rows, cols, num_ancs * 4)
        # ancs.shape  = (rows, cols, num_ancs * 4)
        
        dy = ytrue - ypred
        sw = K.cast(K.less(K.abs(dy), 1), dtype=K.floatx())
        r1 = sw*dy*dy*.5
        r2 = (1-sw)*(K.abs(dy)-.5)
        return K.sum((r1+r2) * ptrue)
    return lambda ytrue, ypred: \
        loss(ytrue[...,4*num_ancs:],
             ypred,
             ytrue[...,:4*num_ancs])

def rpn_cls_loss(num_ancs):
    def loss(postrue, negtrue, ppred):
        # Add epsilon = 1e-4 to prevent log(0)
        return K.sum(- postrue * K.log(1e-4 + ppred)
                     - negtrue * K.log(1e-4 + 1-ppred))
    return lambda ptrue, ppred: \
        loss(ptrue[...,:num_ancs], ptrue[...,num_ancs:], ppred)