Added dim parameter to specify number of components to extract