1. np.expand_dims
>> X = np.random.randint(0, 9, (2, 3))
>> mean_X = np.mean(X, axis=0)
>> X - mean_X # 这样做是没有问题的
>> mean_X = np.mean(X, axis=1)
>> X - mean_X
ValueError: operands could not be broadcast together with shapes (2,3) (2,)
此时便需要手动的调整 mean_X 的维度,使其能够 broadcast,有以下三种方式,在指定的轴上进行 broadcast:
- mean_X[:, None]
- mean_X[:, np.newaxis]
- mean_X = np.expand_dims(mean_X, axis=1)