0

I'm trying to make a custom regularizer in Keras and I need to be able to roll the coefficient array.

I know this may be impossible however any mechanism that can replicate this roll function would be extremely appreciated.

```

def __call__(self, x):
    regularization = 0.

    # Add components if they are given
    if self.l1:
        # \lambda ||x||
        regularization += self.l1 * K.sum(K.abs(x))
    if self.fuse:
        # \lambda \sum{ |x - x_+1| }
        regularization += self.fuse * K.sum(K.abs(x - np.roll(x, 1)))
    if self.abs_fuse:
        # \lambda \sum{ ||x| - |x_+1|| }
        regularization += self.abs_fuse * K.sum(K.abs(K.abs(x) - K.abs(np.roll(x, 1))))

```

4
  • What's the dimension of x? If x is a matrix then it's probably a bit weird. Calling np.roll on a weight matrix will first flatten the matrix, shift the element linearly, and finally reshape it back to a matrix. Is this behavior exactly what you want, or is it np.roll(x, 1, axis=1)? Commented Aug 1, 2017 at 3:11
  • the dimensionality of x is always (m, 1) . And I know from testing it on a toy example with numpy that roll is the behaviour I'm looking for Commented Aug 1, 2017 at 4:07
  • @Yu-Yang EDIT: np.roll(x, 1, axis=1) gives the same result as np.roll(x, 1) in this example but axis=1 is more explicit. Commented Aug 1, 2017 at 4:15
  • I've posted a possible way to implement it, please see if that's what you want. Commented Aug 1, 2017 at 4:22

1 Answer 1

1

Given that x is of shape (m, 1), a possible solution is to use tile:

def roll_reg(x):
    length = K.int_shape(x)[0]
    x_tile = K.tile(x, [2, 1])
    x_roll = x_tile[length - 1:-1]
    return K.sum(K.abs(x - x_roll))

It will result in some extra memory usage, but if x is a 1-dim vector, I guess the overhead won't be too bad.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.