TITLE: Function that can indicates how well the vector is sorted
QUESTION [1 upvotes]: I have vectors Y and W. I know constrain that Y should be sorted by W. So if Wi < Wn than Yi < Yn. And I need some function Z(preferably differentiated, maybe not everywhere) that returns how good the Y is sorted by W. If all elements are sorted Z is max if all are in incorrect order min, the more are sorted the more should be Z.
I want to use it in the deep learning as a loss to make a monotonicity constraint using it. Any idea or hint?

REPLY [0 votes]: [It is quite easy to make such a function. A pair $(x, y)$ is 'sorted' if $x \leq y$. A function that measures how 'sorted' it is can be defined by $\max(0, x-y)$. If $x \leq y$ its value is $0$, and otherwise its value is $x-y$. You can, for example, use $[\max(0, x-y)]^2$ instead, which is differentiable.
For an entire vector $\bf x$, you can use
$$
\sum_{i=1}^{n-1} [\max(0, x_i-x_{i+1})]^2
$$
{"set_name": "stack_exchange", "score": 1, "question_id": 3170868}