pca是一个python包,它执行主成分分析并绘制有见地的图。

pca的Python项目详细描述


pca

PythonPyPI VersionLicenseGithub ForksGitHub Open IssuesProject StatusDownloadsDownloads

     Star it if you like it!

pca是一个python包,用于执行主成分分析和创建有见地的绘图。PCA的核心是建立在sklearn功能的基础上,以便在与其他软件包组合时找到最大的兼容性。在

但这个方案可以做得更多。除了常规的pca,它还可以执行SparsePCATruncatedSVD。根据您的输入数据,将选择最佳方法。在

其他功能包括:

  • Biplot绘制加载情况
  • 确定解释的方差
  • 提取性能最佳的功能
  • 带有加载的散点图
  • 使用Hotelling T2和/或SPE/Dmodx检测异常值

这本笔记本将展示一些例子。在

目录

安装

  • 从PyPI安装pca(推荐)。pca与Python3.6+兼容,可在Linux、MacOS X和Windows上运行。在
  • 它是根据麻省理工学院的许可证发行的。在

要求

  • 不需要创建新环境,但如果您希望这样做:
^{pr2}$

安装

pip install pca
  • 从GitHub源安装最新版本:
git clone https://github.com/erdogant/pca.git
cd pca
python setup.py install

导入pca包

frompcaimportpca

加载示例数据

importnumpyasnpfromsklearn.datasetsimportload_iris# Load datasetX=pd.DataFrame(data=load_iris().data,columns=load_iris().feature_names,index=load_iris().target)# Load pcafrompcaimportpca# Initialize to reduce the data up to the nubmer of componentes that explains 95% of the variance.model=pca(n_components=0.95)# Reduce the data towards 3 PCsmodel=pca(n_components=3)# Fit transformresults=model.fit_transform(X)

X看起来像这样:

X=array([[5.1, 3.5, 1.4, 0.2],
         [4.9, 3. , 1.4, 0.2],
         [4.7, 3.2, 1.3, 0.2],
         [4.6, 3.1, 1.5, 0.2],
         ...
         [5. , 3.6, 1.4, 0.2],
         [5.4, 3.9, 1.7, 0.4],
         [4.6, 3.4, 1.4, 0.3],
         [5. , 3.4, 1.5, 0.2],

labx=[0, 0, 0, 0,...,2, 2, 2, 2, 2]
label=['label1','label2','label3','label4']

绘制散点图

fig,ax=model.scatter()

制作双打印

fig,ax=model.biplot(n_feat=4)

绘制图

fig,ax=model.plot()

制作3d打印

fig,axmodel.scatter3d()fig,ax=model.biplot3d(n_feat=2)

PCA标准化。

从数据中规范化第一个和更多个组件。 如果数据在其第一个分量中被不需要的或有偏差的方差分开,那么这是有用的。比如性别或实验地点等

print(X.shape)(150,4)# Normalize out 1st component and return datamodel=pca()Xnew=model.norm(X,pcexclude=[1])print(Xnorm.shape)(150,4)# In this case, PC1 is "removed" and the PC2 has become PC1 etcax=pca.biplot(model)

提取特征重要性的示例:

# Import librariesimportnumpyasnpimportpandasaspdfrompcaimportpca# Lets create a dataset with features that have decreasing variance. # We want to extract feature f1 as most important, followed by f2 etcf1=np.random.randint(0,100,250)f2=np.random.randint(0,50,250)f3=np.random.randint(0,25,250)f4=np.random.randint(0,10,250)f5=np.random.randint(0,5,250)f6=np.random.randint(0,4,250)f7=np.random.randint(0,3,250)f8=np.random.randint(0,2,250)f9=np.random.randint(0,1,250)# Combine into dataframeX=np.c_[f1,f2,f3,f4,f5,f6,f7,f8,f9]X=pd.DataFrame(data=X,columns=['f1','f2','f3','f4','f5','f6','f7','f8','f9'])# Initializemodel=pca()# Fit transformout=model.fit_transform(X)# Print the top features. The results show that f1 is best, followed by f2 etcprint(out['topfeat'])#     PC      feature# 0  PC1      f1# 1  PC2      f2# 2  PC3      f3# 3  PC4      f4# 4  PC5      f5# 5  PC6      f6# 6  PC7      f7# 7  PC8      f8# 8  PC9      f9

绘制图

model.plot()

Explained variance

做双掷。可以很好地看到,第一个方差最大的特征(f1)几乎是水平的,而第二个方差最大的(f2)几乎是垂直的。这是预期的,因为大部分方差是f1,其次是f2等

ax=model.biplot(n_feat=10,legend=False)

biplot

在3d中的双标绘。在这里我们可以看到在z方向的绘图中添加了预期的f3。在

ax=model.biplot3d(n_feat=10,legend=False)

biplot3d

检测和绘制异常值的示例。

为了检测PCA多维空间中的任何异常值,合并了hotellings T2检验。 这基本上意味着我们计算了顶部n_组件的卡方检验(默认值是PC1到PC5)。 由于主成分分析的性质,预计在前几个分量中会出现最大的方差(以及异常值)。 因此,可能不需要深入PC空间,但深度是可选的。 这种方法产生一个P值矩阵(samples x PCs),然后使用fishers方法组合每个样本的P值。 这种方法允许确定异常值和异常值的排名(最强tot弱)。设置离群值的截止值可以用alpha设置(默认值:0.05)。你知道吗

frompcaimportpcaimportpandasaspdimportnumpyasnp# Create dataset with 100 samplesX=np.array(np.random.normal(0,1,500)).reshape(100,5)# Create 5 outliersoutliers=np.array(np.random.uniform(5,10,25)).reshape(5,5)# Combine dataX=np.vstack((X,outliers))# Initialize model. Alpha is the threshold for the hotellings T2 test to determine outliers in the data.model=pca(alpha=0.05)# Fit transformout=model.fit_transform(X)# [pca] >The PCA reduction is performed on the [5] columns of the input dataframe.# [pca] >Column labels are auto-completed.# [pca] >Row labels are auto-completed.# [pca] >Fitting using PCA..# [pca] >Computing loadings and PCs..# [pca] >Computing explained variance..# [pca] >Number of components is [4] that covers the [95.00%] explained variance.# [pca] >Outlier detection using Hotelling T2 test with alpha=[0.05] and n_components=[4]# [pca] >Outlier detection using SPE/DmodX with n_std=[2]

关于离群值的信息存储在dict‘outliers’中(见下文)。 使用hotellingt2检验计算出的离群值是y_probay_scorey\ubool。 使用SPE/DmodX计算的离群值是y_bool_SPEy_score_SPE,其中y_score_SPE是中心到样本的欧几里得距离。 行与输入样本一致。在

print(out['outliers'])#            y_proba      y_score  y_bool  y_bool_spe  y_score_spe# 1.0   9.799576e-01     3.060765   False       False     0.993407# 1.0   8.198524e-01     5.945125   False       False     2.331705# 1.0   9.793117e-01     3.086609   False       False     0.128518# 1.0   9.743937e-01     3.268052   False       False     0.794845# 1.0   8.333778e-01     5.780220   False       False     1.523642# ..             ...          ...     ...         ...          ...# 1.0   6.793085e-11    69.039523    True        True    14.672828# 1.0  2.610920e-291  1384.158189    True        True    16.566568# 1.0   6.866703e-11    69.015237    True        True    14.936442# 1.0  1.765139e-292  1389.577522    True        True    17.183093# 1.0  1.351102e-291  1385.483398    True        True    17.319038

制定计划

model.biplot(legend=True,SPE=True,hotellingt2=True)model.biplot3d(legend=True,SPE=True,hotellingt2=True)# Create only the scatter plotsmodel.scatter(legend=True,SPE=True,hotellingt2=True)model.scatter3d(legend=True,SPE=True,hotellingt2=True)

可以很容易地选择离群值:

# Select the outliersXoutliers=X[out['outliers']['y_bool'],:]# Select the other setXnormal=X[~out['outliers']['y_bool'],:]

如果需要,也可以使用hotellin直接检测异常值g T2和/或SPE/DmodX功能。在

^{pr21}$

仅绘制方向(箭头)的示例。

frompcaimportpca# Initializemodel=pca()# Example with DataFrameX=np.array(np.random.normal(0,1,500)).reshape(100,5)X=pd.DataFrame(data=X,columns=np.arange(0,X.shape[1]).astype(str))# Fit transformout=model.fit_transform(X)# Make plot with parameters: set cmap to None and label and legend to False. Only directions will be plotted.model.biplot(cmap=None,label=False,legend=False)

引文

如果这对你的研究有用,请在你的出版物中引用distfit。以下是BibTeX条目示例:

@misc{erdogant2019pca,title={pca},author={Erdogan Taskesen},year={2019},howpublished={\url{https://github.com/erdogant/pca}},}

维护人员

Erdogan Taskesen, github: [erdogant](https://github.com/erdogant)
Contributions are welcome.

欢迎加入QQ群-->: 979659372 Python中文网_新手群

推荐PyPI第三方库


热门话题
java根据收到的短信找出手机的位置   java可以使用selenium在单个脚本中混合ios自动化和web自动化   java如何将@RequestParam映射到对象?   java JFrame关闭操作   java如何使用给定的JNDI名称连接到Websphere数据源?   hibernate Java一对多持久化哈希集   java如何设置JdbcUserDetailsManager以使用我的表?   java JUNIT测试Eclipse IDE引发错误   安卓如何根据Java中对象的一个成员变量从arraylist中删除另一个arraylist中存在的对象?   java使用枚举类中的方法,当在运行时获取枚举时   Java ArrayList中的安卓 NullPointerException   java如何使用jinterop在远程机器中编写二进制文件?   Java是跨平台的吗?   java将主题设置为具有自定义绘图功能的按钮   java Spring安全Oauth2:在Tomcat中成功注销,但在Glashfish中无法注销   使用HttpUrlConnection的Java类引发IOException,无法读取或写入   java Primefaces SelectOneRadio,选择了NoSelection选项   java在安卓中从字符串数组中删除元素   Java异常构造函数和方法   树映射中的java顺序错误