Total variation implementation in numpy for a piecewise linear function

Question:

I would like to use total variation in Python, but I wasn’t able to find an existing implementation.

Assuming that I have an array with a finite number of elements, is the implementation with NumPy simply as:

import numpy as np

a = np.array([...], dtype=float)
tv = np.sum(np.abs(np.diff(a)))

My main doubt is how to compute the supremum of tv across all partitions, and if just the sum of the absolute difference might suffice for a finite array of floats.

Edit: My input array represents a piecewise linear function, therefore the supremum over the full set of partitions is indeed the sum of absolute differences between contiguous points.

Asked By: gc5

||

Answers:

Yes, that is correct.

I imagine you’re confused by the mathy definition on the Wikipedia page for total variation. Have a look at the more practical definition on the Wikipedia page for total variation denoising instead.

For an actual code (even Python) implementation, see e.g. Tensorflow’s total_variation(), though this is for one or more (2D, color) images, so the TV is computed for both rows and columns, and then added together.

Answered By: jmd_dk
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.