Week 1 Lab 1 (k-means) Axis parameter

Make sure to set the parameter axis=0
What is the use of setting the parameter axis to 0.

Example:
centroids [k]=np.mean(X[idx==k], axis=0)
centroids [k]=np.mean(X[idx==k])

What is the difference in these two lines?

1 Like

Hi @Harshit_Gupta18,

Consider:

X = np.array([ 
    [1,2,3], 
    [4,3,5] 
])

np.mean(X) gives you the mean along all axes, which is (1+2+3+4+3+5)/6 = 3
np.mean(X, axis=0) gives you the mean along the zeroth axis, resulting in np.array([(1+4)/2 , (2+3)/2, (3+5)/2]) = np.array([2.5, 2.5, 4])

np.mean(X, axis=1) gives you the mean along the first axis, resulting in np.array([2, 4]).

I suggest you to try more examples yourself.

Raymond

3 Likes