Q: numpy knn with vectorizing nested matrices I'm trying to implement the KNN algorithm with numpy and its vectorizing. 
import numpy as np

A = np.array([[11,12,13], [21,22,23], [31,32,33]])
B = np.array([[41,42,43], [51,52,53], [61,62,63]])
C = np.array([[71,72,73], [81,82,83], [91,92,93]])

X = np.array([A, B, C])

f = lambda a,b: (a-b)**2
np.sqrt(np.vectorize(f)(A, X).reshape(3,9).sum(axis=1))
# array([   0.,   90.,  180.])

If I use it this way, I get a 3x1 matrix of the distances of all vectors to A. 
To get all distances of all vectors to each other, I would need a result matrix as follows:
array([[   0.,   90.,  180.],
       [  90.,    0.,   90.],
       [ 180.,   90.,    0.]])

How can I improve the operation so that I get the desired result?

A: In [843]: np.sqrt(f(X[:,None],X).reshape(3,3,9).sum(axis=-1))
Out[843]: 
array([[   0.,   90.,  180.],
       [  90.,    0.,   90.],
       [ 180.,   90.,    0.]])

You don't need vectorize.  f works with arrays directly.
But looking at
In [841]: f(X[:,None],X).reshape(3,3,9)
Out[841]: 
array([[[   0,    0,    0,    0,    0,    0,    0,    0,    0],
        [ 900,  900,  900,  900,  900,  900,  900,  900,  900],
        [3600, 3600, 3600, 3600, 3600, 3600, 3600, 3600, 3600]],

       [[ 900,  900,  900,  900,  900,  900,  900,  900,  900],
        [   0,    0,    0,    0,    0,    0,    0,    0,    0],
        [ 900,  900,  900,  900,  900,  900,  900,  900,  900]],

       [[3600, 3600, 3600, 3600, 3600, 3600, 3600, 3600, 3600],
        [ 900,  900,  900,  900,  900,  900,  900,  900,  900],
        [   0,    0,    0,    0,    0,    0,    0,    0,    0]]], dtype=int32)

makes me suspect you are calculating more values than needed.  But I haven't tried to look at the bigger picture.
