無監督學習-主成分分析和聚類分析

聚類分析(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.pswp.cn/news/391594.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/391594.shtml
英文地址,請注明出處:http://en.pswp.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 如何判斷安裝…