更多信息在Github上:https://github.com/Shadow-Hunter-X
無(wú)督導(dǎo)學(xué)習(xí)
前面介紹的幾種機(jī)器學(xué)習(xí)算法都是監(jiān)督機(jī)器的學(xué)習(xí),在已知目標(biāo)變量或標(biāo)簽的位置,我們?cè)噲D預(yù)測(cè)基于輸入特性的輸出。
無(wú)監(jiān)督學(xué)習(xí)是不同的一種沒(méi)有標(biāo)記數(shù)據(jù)的感覺(jué),我們不會(huì)試圖預(yù)測(cè)任何輸出因此,但試圖找到有趣的模式,并提出
數(shù)據(jù)中的組,類(lèi)似的值被組合在一起。
主要的方法
- 量化觀察對(duì)象,使用一個(gè)向量進(jìn)行表示,如可以用年齡,身高,體重表示一個(gè)人
| 年齡 | 薪水 | 體重 | 身高 |
|---|---|---|---|
| 30 | 15k | 62 | 172 |
| 40 | 25k | 75 | 170 |
- 計(jì)算兩個(gè)對(duì)象間的距離,通過(guò)用歐幾里德法來(lái)測(cè)量距離,直截了當(dāng)

=√((30-40)2 + (15-25)2 + (62-75)2 + (172-170)2)
=√(100+100+169+4)
=19.3
還要其他計(jì)算距離的算法: Manhattan 距離 ; Mahalanobis距離 ;Chebyshev 距離等。
計(jì)算得到上述兩個(gè)對(duì)象間的距離為19.3
K-Means算法
K代表數(shù)據(jù)集中劃分類(lèi)別的個(gè)數(shù),現(xiàn)在對(duì)K-Menas算法中的一些概念的說(shuō)明。
- Centroid-圖心
圖心指的是中心的數(shù)據(jù)點(diǎn),在一個(gè)集群的中心或一個(gè)組。它也是集群中最具有代表性的點(diǎn),最大距離等距點(diǎn)到集群中的其他點(diǎn)。
每個(gè)集群或組包含不同數(shù)量的數(shù)據(jù)點(diǎn)到圖心的質(zhì)心最近

聚類(lèi)的整個(gè)想法是最小化內(nèi)光距離,這是集群的圖心的數(shù)據(jù)點(diǎn)的內(nèi)部距離最大限度的相互聚系距離,即兩個(gè)之間的圖心之間不同分類(lèi)
- Variance-方差
方差是圖心所在數(shù)據(jù)集中的數(shù)據(jù)點(diǎn)距離的總和。

示例代碼
用的測(cè)試數(shù)據(jù)是 iris data(鳶尾科話(huà))數(shù)據(jù),由于這份數(shù)據(jù)在統(tǒng)計(jì)計(jì)算測(cè)試中經(jīng)常用到,所以在網(wǎng)絡(luò)上搜索下,就可以找到。
from pyspark.sql import SparkSession
import pyspark
from pyspark.sql.functions import *
from pyspark.sql.types import *
from pyspark.sql.functions import rand, randn
from pyspark.ml.clustering import KMeans
spark = SparkSession.builder.appName('k_means').getOrCreate() # 創(chuàng)建SparkSession對(duì)象
print("------------------讀取數(shù)據(jù)-----------------")
df=spark.read.csv('iris_dataset.csv',inferSchema=True,header=True) # 讀取數(shù)據(jù)
print("------------------查看分析數(shù)據(jù)-----------------")
print((df.count(),len(df.columns))) # 查看數(shù)據(jù)規(guī)模
# 查看列信息
df.printSchema()
df.columns
df.orderBy(rand()).show(10,False) # 查看數(shù)據(jù),隨機(jī)的方式
df.groupBy('species').count().orderBy('count',ascending=False).show(10,False) # 匯總查看數(shù)據(jù)
print("-----------------數(shù)據(jù)轉(zhuǎn)換-------------------")
from pyspark.ml.linalg import Vectors
from pyspark.ml.feature import VectorAssembler # 導(dǎo)入VerctorAssembler 將多個(gè)列合并成向量列的特征轉(zhuǎn)換器,即將表中各列用一個(gè)類(lèi)似list表示,輸出預(yù)測(cè)列為單獨(dú)一列。
input_cols=['sepal_length', 'sepal_width', 'petal_length', 'petal_width']
# 將所有的屬性轉(zhuǎn)換為轉(zhuǎn)化為一個(gè)vector
vec_assembler = VectorAssembler(inputCols = input_cols, outputCol='features')
final_data = vec_assembler.transform(df)
print("------------設(shè)定不同的K值,進(jìn)行分類(lèi),計(jì)算平方誤差之和------------")
errors=[]
for k in range(2,10):
kmeans = KMeans(featuresCol='features',k=k)
model = kmeans.fit(final_data)
intra_distance = model.computeCost(final_data)
errors.append(intra_distance)
print("With K={}".format(k))
print("Within Set Sum of Squared Errors = " + str(errors))
print('--'*30)
print("-----------使用mathplot計(jì)算,匯總不同K值-----------------")
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
cluster_number = range(2,10)
plt.scatter(cluster_number,errors)
plt.xlabel('Number of Clusters (K)')
plt.ylabel('SSE')
plt.show()
# 通過(guò)圖形,查看k=4時(shí)較為合適
kmeans = KMeans(featuresCol='features',k=4,)
model = kmeans.fit(final_data)
predictions=model.transform(final_data)
predictions.groupBy('species','prediction').count().show() # 查看分類(lèi)的數(shù)據(jù)
print("---------將數(shù)據(jù)轉(zhuǎn)換為panda結(jié)構(gòu),并查看空間3d圖心-----------")
pandas_df = predictions.toPandas()
pandas_df.sample(5)
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
cluster_vis = plt.figure(figsize=(15,10)).gca(projection='3d')
cluster_vis.scatter(pandas_df.sepal_length, pandas_df.sepal_width, pandas_df.petal_length, c=pandas_df.prediction,depthshade=False)
plt.show()




