28

How can I calculate the 1-norm of the difference of two vectors, ||a - b||_1 = sum(|a_i - b_i|) in Python?

a = [1,2,3,4]  
b = [2,3,4,5]

||a - b||_1 = 4  
kquinn
  • 10,433
  • 4
  • 35
  • 35

5 Answers5

41

Python has powerful built-in types, but Python lists are not mathematical vectors or matrices. You could do this with lists, but it will likely be cumbersome for anything more than trivial operations.

If you find yourself needing vector or matrix arithmetic often, the standard in the field is NumPy, which probably already comes packaged for your operating system the way Python also was.

I share the confusion of others about exactly what it is you're trying to do, but perhaps the numpy.linalg.norm function will help:

>>> import numpy
>>> a = numpy.array([1, 2, 3, 4])
>>> b = numpy.array([2, 3, 4, 5])
>>> numpy.linalg.norm((a - b), ord=1)
4

To show how that's working under the covers:

>>> a
array([1, 2, 3, 4])
>>> b
array([2, 3, 4, 5])
>>> (a - b)
array([-1, -1, -1, -1])
>>> numpy.linalg.norm((a - b))
2.0
>>> numpy.linalg.norm((a - b), ord=1)
4
bignose
  • 30,281
  • 14
  • 77
  • 110
15

In NumPy, for two vectors a and b, this is just

numpy.linalg.norm(a - b, ord=1)
kquinn
  • 10,433
  • 4
  • 35
  • 35
10

You appear to be asking for the sum of the differences between the paired components of the two arrays:

>>> A=[1,2,3,4]
>>> B=[2,3,4,5]
>>> sum(abs(a - b) for a, b in zip(A, B))
4
Alnitak
  • 334,560
  • 70
  • 407
  • 495
  • the l1 norm is what that is; it is a really obscure way of saying it, but in math you write it all the time. The notation is `||x||`, which usually defaults to the euclidean norm (vector distance, in the physical sense), but `x / ||x||_1` would be probability of an item in `x`, while `x / ||x||_2` would be the unit vector – Chris Apr 26 '18 at 14:08
  • it goes back to the pythagorean theorem: the l1 norm would be a+b (manhattan distance), in the triangle, while the l2 norm would be the length of the hypotenuse – Chris Apr 26 '18 at 14:13
5

It is not clear what exactly is required here, but here is my guess

a=[1,2,3,4]
b=[2,3,4,5]
def a_b(a,b):
    return sum(map(lambda a:abs(a[0]-a[1]), zip(a,b)))

print a_b(a,b)
Anurag Uniyal
  • 85,954
  • 40
  • 175
  • 219
1

Using Numpy you can calculate any norm between two vectors using the linear algebra package.

 import numpy as np
 a = np.array([[2,3,4])
 b = np.array([0,-1,7])
      
 # L1 Norm
 np.linalg.norm(a-b, ord=1)

 # L2 Norm
 np.linalg.norm(a-b, ord=2)

# L3 Norm
 np.linalg.norm(a-b, ord=3)

# Ln Norm
 np.linalg.norm(a-b, ord=n)

Example:

enter image description here

Arpan Saini
  • 4,623
  • 1
  • 42
  • 50