无监督学习-主成分分析和聚类分析

聚类分析(cluster analysis)是将一组研究对象分为相对同质的群组(clusters)的统计分析技术,即将观测对象的群体按照相似性和相异性进行不同群组的划分,划分后每个群组内部各对象相似度很高,而不同群组之间的对象彼此相异度很高。

回归、分类、聚类的区别 :

  • 有监督学习 --->> 回归、分类    /   无监督学习  --->>聚类
  • 回归 -->>产生连续结果,可用于预测
  • 分类 -->>产生连续结果,可用于预测
  • 聚类 -->>产生一组集合,可用于降维

一、PCA主成分分析

 

二、PCA主成分的python实现方法

通过sklearn的PCA类实现,from sklearn.decomposition import PCA

pca = PCA(n_components=1) # n_components参数表示最终维度

pca.fit(data) #创建模型

data_pca = pca.transform(data) #降维,创建模型和降维可通过一步实现fit_transform

data_inverse = pca.inverse_transform(data_pca) #根据降维结果反算原始数据

1.二维数据降维

rng = np.random.RandomState(8)
data = np.dot(rng.rand(2,2),rng.randn(2,200)).T  #矩阵相乘
df = pd.DataFrame({'X1':data[:,0],'X2':data[:,1]})
print(df.shape)
print(df.head())
plt.scatter(df['X1'],df['X2'],alpha = 0.8,marker = '.')
plt.axis('equal')  #坐标轴每个单位表示的刻度相同
# (200, 2)
#          X1        X2
# 0 -1.174787 -1.404131
# 1 -1.374449 -1.294660
# 2 -2.316007 -2.166109
# 3  0.947847  1.460480
# 4  1.762375  1.640622

from sklearn.decomposition import PCA
pca = PCA(n_components=1) # n_components参数表示最终维度
pca.fit(df)
print(pca.explained_variance_)
print(pca.components_)
# print(pca.n_components) #返回保留的成分个数
# print(pca.explained_variance_ratio_) 
# 结果降为几个维度,就有几个特征值;原始数据有几个维度,就有几个特征向量
# explained_variance_:特征值
# components_:返回具有最大方差的成分,即特征向量# 这里是shape(200,2)降为shape(200,1),只有1个特征值,对应2个特征向量
# 降维后主成分 A1 = 0.7788006 * X1 + 0.62727158 * X2
# 成分的结果值 = 2.80 * (-0.77*x1 -0.62 * x2) #通过这个来筛选它的主成分

df_pca = pca.transform(df)  # 数据转换,将原始二维数据转换为降维后的一维数据
df_inverse = pca.inverse_transform(df_pca)  # 数据转换,将降维后的一维数据转换成原始的二维数据
print('original shape:',df.shape)
print('transformed shape:',df_pca.shape)
print(df.head(10))
print(df_pca[:10])
print(df_inverse[:10])

plt.scatter(df['X1'],df['X2'], alpha = 0.8, marker = '.') #原始数据散点;
plt.scatter(x_inverse[:,0],x_inverse[:,1], alpha = 0.8, marker = '.',color = 'r') #转换之后的散点,红色的就是最后的特征数据
plt.axis('equal')

2.多维数据降维

 多维数据降维,使用自带的图像数据进行测试。

from sklearn.datasets import load_digits
digits = load_digits()
print(type(digits))
print(digits.data[:2])
print('数据长度为:%i条' % len(digits['data']))
print('数据形状为:',digits.data.shape) #总共1797条数据,每条数据有64个变量
print('字段:',digits.keys())
print('分类(数值):',digits.target)
print('分类(名称):',digits.target_names)

 

将上述数据由64维降为2维,降维后的2个维度肯定都是主成分。

pca = PCA(n_components=2)  #降为2维
projected = pca.fit_transform(digits.data)  #相当于先fit构建模型,再transform进行转换
projected[:2]
print('original shape:',digits.data.shape)
print('transformed shape:',projected.shape)
print('特征值',pca.explained_variance_)  #2个特征值
print('特征向量',pca.components_.shape) #2个成分,每个成分都有64个特征向量# original shape: (1797, 64)
# transformed shape: (1797, 2)
# 特征值 [179.0069301  163.71774688]
# 特征向量 (2, 64)
plt.scatter(projected[:,0],projected[:,1],s = 10,c = digits.target, cmap='Reds',edgecolor = 'none',alpha = 0.5)
plt.colorbar()

 

将上述数据降为10维,并求主要成分。

pca = PCA(n_components=10)  #降为10维
projected = pca.fit_transform(digits.data)  #相当于先fit构建模型,再transform进行转换
projected[:2]
print('original shape:',digits.data.shape)
print('transformed shape:',projected.shape)
print(pca.explained_variance_)  # 输出特征值 ;10个特征值
print(pca.components_.shape)  # 输出特征向量形状

s = pca.explained_variance_
c_s = pd.DataFrame({'x':s,'x_cumsum':s.cumsum()/s.sum()})
print(c_s)
c_s['x_cumsum'].plot(style = '--ko', figsize = (10,4))
plt.axhline(0.85,color='r',linestyle="--",alpha=0.8)  
plt.text(6,c_s['x_cumsum'].iloc[6]-0.1,'第7个成分累计贡献率超过85%',color = 'r')
plt.grid()

   

 

三、K-means聚类的python实现方法

K-means聚类是最常用的机器学习聚类算法,且为典型的基于距离的聚类算法。主要步骤为:

kmeans = KMeans(n_clusters=4) #创建模型

kmeans.fit(x) #导入数据

y_kmeans = kmeans.predict(x) #预测每个数据属于哪个类

centroids = kmeans.cluster_centers_ #每个类的中心点

 先使用sklearn自带的生成器生成数据

from sklearn.datasets.samples_generator import make_blobs  # make_blobs聚类数据生成器
x,y_true = make_blobs(n_samples=300,centers=4,cluster_std=0.5,random_state=0)
print(x[:5])
print(y_true[:5])# n_samples 生成的样本总数
# centers 类别数
# cluster_std 每个类别的方差,如果多类数据不同方差可设置为[std1,std2,...stdn]
# random_state 随机数种子
# x 生成的数据,y 数据对应的类别
# n_features 每个样本的特征数

plt.scatter(x[:,0],x[:,1],s=10,alpha=0.8)

   

通过sklearn的KMeans进行聚类分析

from sklearn.cluster import KMeans
kmeans = KMeans(n_clusters=4)  #创建模型
kmeans.fit(x)  #导入数据
y_kmeans = kmeans.predict(x)  #预测每个数据属于哪个类
centroids = kmeans.cluster_centers_ #每个类的中心点
plt.scatter(x[:,0],x[:,1],s=30,c=y_kmeans,cmap = 'Dark2',alpha=0.5,marker='x')
plt.scatter(centroids[:,0],centroids[:,1],s=70,c=[0,1,2,3],cmap = 'Dark2',marker='o')
plt.title('K-means 300 points')
plt.xlabel('value1')
plt.ylabel('value2')

 

转载于:https://www.cnblogs.com/Forever77/p/11386031.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/391594.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

struts实现分页_在TensorFlow中实现点Struts

struts实现分页If you want to get started on 3D Object Detection and more specifically on Point Pillars, I have a series of posts written on it just for that purpose. Here’s the link. Also, going through the Point Pillars paper directly will be really help…

封装jQuery下载文件组件

使用jQuery导出文档文件 jQuery添加download组件 jQuery.download function(url, data, method){if( url && data ){data typeof data string ? data : paramEdit(data);     function paramEdit(obj){        var temStr "",tempStr"…

7.13. parallel - build and execute shell command lines from standard input in parallel

并行执行shell命令 $ sudo apt-get install parallel 例 7.5. parallel - build and execute shell command lines from standard input in parallel $ cat *.csv | parallel --pipe grep 13113 设置块大小 $ cat *.csv | parallel --block 10M --pipe grep 131136688 原…

MySQL-InnoDB索引实现

联合索引提高查询效率的原理 MySQL会为InnoDB的每个表建立聚簇索引,如果表有索引会建立二级索引。聚簇索引以主键建立索引,如果没有主键以表中的唯一键建立,唯一键也没会以隐式的创建一个自增的列来建立。聚簇索引和二级索引都是一个b树&…

Go语言-基本的http请求操作

Go发起GET请求 基本的GET请求 //基本的GET请求 package mainimport ("fmt""io/ioutil""net/http" )func main() {resp, err : http.Get("http://www.hao123.com")if err ! nil {fmt.Println(err)return}defer resp.Body.Close()body, …

钉钉设置jira机器人_这是当您机器学习JIRA票证时发生的事情

钉钉设置jira机器人For software developers, one of the most-debated and maybe even most-hated questions is “…and how long will it take?”. I’ve experienced those discussions myself, which oftentimes lacked precise information on the requirements. What I…

python的赋值与参数传递(python和linux切换)

1,python模式切回成linux模式------exit() linux模式切换成python模式------python 2,在linux里运行python的复合语句(得在linux创建.py文件) touch le.py vim le.py----在le文件里输入python语句 #!/usr/bin/python …

vscode 标准库位置_如何在VSCode中使用标准

vscode 标准库位置I use Visual Studio Code as my text editor. When I write JavaScript, I follow JavaScript Standard Style.Theres an easy way to integrate Standard in VS Code—with the vscode-standardjs plugin. I made a video for this some time ago if youre …

leetcode 1603. 设计停车系统

请你给一个停车场设计一个停车系统。停车场总共有三种不同大小的车位:大,中和小,每种尺寸分别有固定数目的车位。 请你实现 ParkingSystem 类: ParkingSystem(int big, int medium, int small) 初始化 ParkingSystem 类&#xf…

IBM量子计算新突破:成功构建50个量子比特原型机

本文来自AI新媒体量子位(QbitAI)IBM去年开始以云计算服务的形式提供量子计算能力。当时,IBM发布了包含5个量子比特的计算机。在短短18个月之后,IBM周五宣布,将发布包含20个量子比特的计算机。 IBM还宣布,该…

ChromeDriver与chrome对应关系

http://chromedriver.storage.googleapis.com/index.html 转载于:https://www.cnblogs.com/gcgc/p/11387605.html

快速排序和快速选择(quickSort and quickSelect)算法

排序算法:快速排序(quicksort)递归与非递归算法 TopK问题:快速选择(quickSelect)算法 import java.util.*; import java.lang.*;public class Demo {// 非递归 using stackpublic static void quickSortStack(int[] nums, int left, int right) {if (lef…

小程序点击地图气泡获取气泡_气泡上的气泡

小程序点击地图气泡获取气泡Combining two colors that are two steps apart on the Color Wheel creates a Diad Color Harmony. This Color Harmony is one of the lesser used ones. I decided to cover it here to add variety to your options for colorizing visualizati…

leetcode 150. 逆波兰表达式求值(栈)

根据 逆波兰表示法,求表达式的值。 有效的算符包括 、-、*、/ 。每个运算对象可以是整数,也可以是另一个逆波兰表达式。 说明: 整数除法只保留整数部分。 给定逆波兰表达式总是有效的。换句话说,表达式总会得出有效数值且不存在…

WebLogic常见问题

myeclipseweblogic10的配置,配置成功 运行中可能失败,由于weblogic10不稳定,重启机器后可以使用了 web工程使用到hibernate3时可能出现问题 ClassNotFoundException: org.hibernate.hql.ast.HqlToken 参考http://blog.chinajavaworld.com/ent…

PopTheBubble —测量媒体偏差的产品创意

产品管理 (Product Management) A couple of months ago, I decided to try something new. The MVP Lab by Mozilla is an 8-week incubator for pre-startup teams to explore product concepts and, over the 8 weeks of the program, ship a minimum viable product that p…

linux-Centos7安装nginx

首先配置linux环境,我这里是刚刚装好linux,所以一次性安装了一系列我需要到的环境; yum install pcre pcre-devel zlib zlib-devel openssl openssl-devel gd gd-devel libjpeg libjpeg-devel libpng libpng-devel freetype freetype-devel e…

javascript原型_JavaScript原型初学者指南

javascript原型You cant get very far in JavaScript without dealing with objects. Theyre foundational to almost every aspect of the JavaScript programming language. In fact, learning how to create objects is probably one of the first things you studied when …

leetcode 73. 矩阵置零

给定一个 m x n 的矩阵,如果一个元素为 0 ,则将其所在行和列的所有元素都设为 0 。请使用 原地 算法。 进阶: 一个直观的解决方案是使用 O(mn) 的额外空间,但这并不是一个好的解决方案。 一个简单的改进方案是使用 O(m n) 的额…

elasticsearch,elasticsearch-service安装

在Windows上安装Elasticsearch.zip 1 安装条件 安装需具备java 8或更高版本;官方的Oracle发行版,只需安装JDKElasticsearch的ZIP安装包——安装包地址 2 如何安装 Elasticsearch 傻瓜式的点下一步即可, java 注意环境变量配置 3 如何判断安装…