# Use Earth Mover's Distance as loss function in Tensorflow

## Issue

I want to compute Earth Mover’s Distance between two pointclouds as loss function in Tensorflow.

``````pointclouds1 = tf.placeholder(tf.float32, shape=(batch_size, num_point, 3))
pointclouds2 = tf.placeholder(tf.float32, shape=(batch_size, num_point, 3))
//'3' means xyz coordinate

def get_loss(pointclouds1, pointclouds2):
loss = EMD.getEMD(pointclouds1,pointclouds2)
return loss
``````

Unfortunately,I get the error:

``````File "F:\pointclouds\utils\EMD.py", line 71, in groundDistance
return np.linalg.norm(x1 - x2, norm)
File "C:\Users\xu\Anaconda3\lib\site-packages\numpy\linalg\linalg.py", line 2257, in norm
raise ValueError("Improper number of dimensions to norm.")
ValueError: Improper number of dimensions to norm.
``````

The EMD.py is from https://github.com/chalmersgit/EMD/blob/master/EMD.py

But I can use the file to operate numpy array directly:

``````>>python EMD.py
EMD
We got: 160.542759771
C example got 160.54277
Success
``````

I guess it means I cannot operate Tensor directly, so what should I do?

## Solution

Is the function `EMD.getEMD` actually doing the computation? It appears to be the case, and if my assumption is correct you’re misunderstanding tensorflow.

Tensorflow development progresses in two stages, first you build a graph of your operations, we usually separate all of this code into a `build_graph()` function. At this point no data is passed in, we are only defining the operations that we’ll do.

Second, you create a session, pass in the variable, and ask tensorflow to compute certain values, such as the loss. You’ll actually do computations in tensorflow using a call to

``````sess.run([ops_to_compute], feed_dict={placeholder_1:input_1, placeholder_2:input_2, ...})
``````

In order to use a custom loss function, you’ll need to define the loss function in tensorflow. If you ever use a numpy function in the definition of the loss function you know you’ve done it wrong. You have to define the loss function using tensorflow operations.

It’s usually quite trivial to do so. You’ll generally just look at the numpy operations that you have in your current code and re-create the same tensorflow operation. 