0

I got (150, 4) and (4,) How to calculate the euclidean distance

from sklearn.metrics.pairwise import euclidean_distances
center_distances = np.array(euclidean_distances(X, middle_point))

and I getting this error

ValueError: Expected 2D array, got 1D array instead:
array=[5.84333333 3.05733333 3.758      1.19933333].
Reshape your data either using array.reshape(-1, 1) if your data has a single feature or 
array.reshape(1, -1) if it contains a single sample.
Ivan
  • 34,531
  • 8
  • 55
  • 100
Joseph_
  • 39
  • 6

1 Answers1

1

You need to broadcast middle_point to the shape of X. You can do so by expanding one dimension on the first axis. You can either do:

  • with np.expand_dims:

    >>> np.expand_dims(middle_point, 1)`)
    
  • with slice tricks and None (equivalent to np.newaxis):

    >>> middle_point[None]
    

This allows to broadcast middle_point to an array of shape (1, 4).

As a result you get an array containing the distances between each of the 150 points in X and the unique point in middle_point:

>>> euclidean_distances(X, middle_point[None])
# shape (150, 1)
Ivan
  • 34,531
  • 8
  • 55
  • 100