2016-11-28 113 views
1

我有movielens dataset,我想將PCA應用於它,但sklearn PCA函數似乎不能正確執行它。
我有718 * 8913矩陣的行表示用戶和列表示電影 這裏是我的Python代碼:在movielens數據集上應用sklearn PCA

加載影片的名字和電影分級

movies = pd.read_csv('movies.csv') 
ratings = pd.read_csv('ratings.csv') 
ratings.drop(['timestamp'], axis=1, inplace=True) 
def replace_name(x): 
    return movies[movies['movieId']==x].title.values[0] 
ratings.movieId = ratings.movieId.map(replace_name) 
M = ratings.pivot_table(index=['userId'], columns=['movieId'], values='rating') 
df1 = M.replace(np.nan, 0, regex=True) 

規範

X_std = StandardScaler().fit_transform(df1) 

應用PCA

pca = PCA() 
result = pca.fit_transform(X_std) 
print result.shape 
plt.plot(np.cumsum(pca.explained_variance_ratio_)) 
plt.xlabel('number of components') 
plt.ylabel('cumulative explained variance') 
plt.show() 

我沒有設置任何組件編號,因此我預計PCA會在新維度中返回718 * 8913矩陣,但pca結果大小爲718 * 718,pca.explained_variance_ratio_大小爲718,並且它的所有成員的總和爲1,但這是怎麼回事可能!!!
我有8913的功能,它只返回718和它們的方差之和等於1任何一個可以解釋這裏有什麼問題嗎?
我的情節圖片結果: enter image description here 正如你可以在上面的圖片中看到它只包含718組件和它的總和爲1但我有8913功能,他們走了嗎?

較小的例如測試

我即使scikit嘗試學習可以在PCA Here is the Link的文檔頁面中找到我修改這個例子,只是增加的功能

import numpy as np 
from sklearn.decomposition import PCA 
import pandas as pd 
X = np.array([[-1, -1,3,4,-1, -1,3,4], [-2, -1,5,-1, -1,3,4,2], [-3, -2,1,-1, -1,3,4,1], 
[1, 1,4,-1, -1,3,4,2], [2, 1,0,-1, -1,3,4,2], [3, 2,10,-1, -1,3,4,10]]) 
ipca = PCA(n_components = 7) 
print (X.shape) 
ipca.fit(X) 
result = ipca.transform(X) 
print (result.shape); 

,並在數PCA例子這個例子中我們有6個樣本和8個發起人,我將n_components設置爲7,但結果大小爲6 * 6。
我認爲,當特徵數大於樣本數更大scikit學組件的最大數量PCA將返回等於樣本

回答

1

參見PCA的documentation。 由於您未將n_components參數傳遞給PCA(),因此sklearn使用min(n_samples, n_features)作爲n_components的值,這就是爲什麼您將縮減的功能集設置爲等於n_samples。

我相信你的方差等於1,因爲你沒有設置n_components,從文檔:

如果沒有設置n_components然後所有組件的存儲和總和解釋方差 等於到1.0。

+0

我厭倦了n_components每n_components超過718 dose't工作做大終於返回718個組件 –

+0

這裏的答案似乎表明,從根本上,尺寸的最大數量PCA可以減少爲min(N_SAMPLES次,n_features) :http://stackoverflow.com/questions/22557883/scikit-learn-pca-dimension-reduction-data-lot-of-features-and-few-samples?rq=1 –