Python 旋转分量加载矩阵
我正在寻找Python中显示旋转PCA组件矩阵的方法 我已经编写了一个Python函数,它接收熊猫数据帧并返回PCA分析的一些基本元素。我还有其他地方提到的“varimax”旋转函数。然而,我似乎找不到任何东西来显示“旋转”组件矩阵。目前,PCA仅显示未旋转的组件加载矩阵。在下面的第一个函数中,x_comp2返回已排序、未旋转的加载矩阵。相比之下,如果您在PCA或FA中要求“旋转”,SPSS(和其他人)将返回旋转的加载矩阵。旋转组件矩阵有助于解释加载到每个组件上的变量Python 旋转分量加载矩阵,python,pca,Python,Pca,我正在寻找Python中显示旋转PCA组件矩阵的方法 我已经编写了一个Python函数,它接收熊猫数据帧并返回PCA分析的一些基本元素。我还有其他地方提到的“varimax”旋转函数。然而,我似乎找不到任何东西来显示“旋转”组件矩阵。目前,PCA仅显示未旋转的组件加载矩阵。在下面的第一个函数中,x_comp2返回已排序、未旋转的加载矩阵。相比之下,如果您在PCA或FA中要求“旋转”,SPSS(和其他人)将返回旋转的加载矩阵。旋转组件矩阵有助于解释加载到每个组件上的变量 #function to
#function to run PCA analysis. yes, I'm sure this can be cleaner... first attempt. x is the name of the dataframe, n is the number of Principal Components to extract.
def pca(x, n):
pca = PCA(n_components=n)
l = len(x.columns)
x_pca = pca.fit(x.iloc[:,0:l])
pca_t = pca.transform(x.iloc[:,0:l])
e = pca.explained_variance_
x_comp = pd.DataFrame(x_pca.components_.T * np.sqrt(x_pca.explained_variance_))
x_comp['variable'] = np.array(x.columns[0:l])
x_comp1 = pd.DataFrame(x_comp.set_index('variable'))
x_comp2 = x_comp1.apply(lambda x: np.where(x < .2,'',round(x,2)))
x_comp2.sort_values([0,1], ascending=False)
var=pd.DataFrame(np.cumsum(np.round(x_pca.explained_variance_ratio_, decimals=3)*100))
return x_comp2, var, pca_t, e
#function to perform Varimax rotation
def varimax(Phi, gamma = 1.0, q = 20, tol = 1e-6):
from scipy import eye, asarray, dot, sum, linalg
p,k = Phi.shape
R = eye(k)
d=0
for i in range(q):
d_old = d
Lambda = dot(Phi, R)
u,s,vh = linalg.svd(dot(Phi.T,asarray(Lambda)**3 - (gamma/p) * dot(Lambda, np.diag(np.diag(dot(Lambda.T,Lambda))))))
R = dot(u,vh)
d = sum(s)
if d_old!=0 and d/d_old < 1 + tol: break
return dot(Phi, R)
运行PCA分析的函数。是的,我相信这会更干净。。。第一次尝试。x是数据帧的名称,n是要提取的主成分的数量。
def pca(x,n):
pca=pca(n_分量=n)
l=len(x列)
x_pca=pca.fit(x.iloc[:,0:l])
pca\u t=pca.transform(x.iloc[:,0:l])
e=主成分分析方差_
x_comp=pd.DataFrame(x_pca.components.T*np.sqrt(x_pca.explained\u variance))
x_comp['variable']=np.array(x.columns[0:l])
x_comp1=pd.DataFrame(x_comp.set_索引('variable'))
x_comp2=x_comp1.应用(λx:np.式中(x<.2',四舍五入(x,2)))
x_comp2.排序_值([0,1],升序=False)
var=pd.数据帧(np.cumsum(np.round(x_pca.explained_方差_比率,小数=3)*100))
返回x_comp2,var,pca_t,e
#用于执行Varimax旋转的函数
def varimax(Phi,伽马=1.0,q=20,tol=1e-6):
来自scipy进口眼、asarray、dot、sum、linalg
p、 k=φ形状
R=眼睛(k)
d=0
对于范围(q)内的i:
d_old=d
λ=点(φ,R)
u、 s,vh=linalg.svd(点(φT,asarray(λ)**3-(伽马/p)*点
R=点(u,vh)
d=总和
如果你老了=0和d/d_旧<1+tol:中断
返回点(φ,R)