title: Memory Efficient L2 norm using Python broadcasting
body: <p>I am trying to implement a way to cluster points in a  test dataset based on their similarity to a sample dataset, using Euclidean distance. The test dataset has  500 points, each point is a N dimensional vector (N=1024). The training dataset has around 10000 points and each point is also a 1024- dim vector. The goal is to find the L2-distance between each test point and  all the sample points to find the closest sample (without using any python distance functions).  Since the test array and training array have different sizes, I tried using broadcasting:</p>
  
  <pre><code>    import numpy as np
      dist = np.sqrt(np.sum( (test[:,np.newaxis] - train)**2, axis=2))
  </code></pre>
  
  <p>where test is an array of shape (500,1024) and train is an array of shape (10000,1024). I am getting a MemoryError. However, the same code works for smaller arrays. For example:</p>
  
  <pre><code>     test= np.array([[1,2],[3,4]])
       train=np.array([[1,0],[0,1],[1,1]])
  </code></pre>
  
  <p>Is there a more memory efficient way to do the above computation without loops? Based on the posts online, we can implement L2- norm using matrix multiplication sqrt(X * X-2*X * Y+Y * Y). So I tried the following:</p>
  
  <pre><code>    x2 = np.dot(test, test.T)
      y2 = np.dot(train,train.T)
      xy = 2* np.dot(test,train.T)
  
      dist = np.sqrt(x2 - xy + y2)
  </code></pre>
  
  <p>Since the matrices have different shapes, when I tried to broadcast, there is a dimension mismatch and  I am not sure what is the right way to broadcast (dont have much experience with Python broadcasting). I would like to know what is the right way to implement the L2 distance computation as a matrix multiplication in Python, where the matrices have different shapes. The resultant distance matrix should have dist[i,j] = Euclidean distance between test point i and sample point j.</p>
  
  <p>thanks</p>