机器学习算法:降维算法|python与r语言代码实现

在过去的4-5年中,数据捕获在每一个可能的阶段都有指数增长。企业/政府机构/研究机构不仅提供新的来源,而且正在非常详细地获取数据。

例如:电子商务公司正在捕捉更多关于客户的细节,比如他们的人口统计、网络爬行历史、他们喜欢或不喜欢什么、购买历史、反馈和许多其他信息,以便比最近的杂货店老板更能给予他们个性化的关注。

作为一名数据科学家,我们提供的数据也包括许多特性,这听起来有利于建立良好的健壮模型,但是存在一个挑战。你如何识别出1000或2000的高重要变量?在这种情况下,降维算法可以和其他各种算法如决策树、随机森林、主成分分析、因子分析、基于相关矩阵的识别、缺失值比等一起使用。

Python 代码

#Import Library
from sklearn import decomposition
#Assumed you have training and test data set as train and test
# Create PCA obeject pca= decomposition.PCA(n_components=k) #default value of k =min(n_sample, n_features)
# For Factor analysis
#fa= decomposition.FactorAnalysis()
# Reduced the dimension of training dataset using PCA
train_reduced = pca.fit_transform(train)
#Reduced the dimension of test dataset
test_reduced = pca.transform(test)
#For more detail on this, please refer  this link.

R 语言代码

library(stats)
pca <- princomp(train, cor = TRUE)
train_reduced  <- predict(pca,train)
test_reduced  <- predict(pca,test)
THE END