Function that can indicates how well the vector is sorted

40 Views Asked by At

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?

2

There are 2 best solutions below

0
On

A function that does what you want that can be computed in quadratic time is to loop over all unordered pairs of elements and add $1$ to a sum if they're not inverted and add $0$ if they are. There is a way to also compute this in $O(n\log n) $ time similar to merge sort.

This is simply the complement of the number of inversions of the array, and it satisfies your conditions.

2
On

[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 $$