前言
我是一個完全沒用過python的人,所以,想寫機器學習,就得從語法入手。
首先上W3cSchool去學習基礎語法。
基礎語法都差不多,重點看一下函數,模塊,面向對象。
函數的寫法稍有不同,格式上類似yml的寫法;模塊會介紹import的相關信息;面向對象會介紹類的相關信息。
參考網站:
https://www.w3cschool.cn/python3/
https://www.w3cschool.cn/python3/python3-eam72ylh.html
理論上,2~3個小時就能學完。
K-means機器學習
我這裏使用VSCode進行開發,隨便打開一個文件夾,然後創建一個KmeansTest.py的文件,然後點運行(右上角的三角),然後系統會提示安裝python。
因爲我電腦是Window11,所以會彈窗提示我安裝python3的包,點擊安裝即可;如果不是window11,就自己下個python包,配置一下環境變量,這個過程不復雜。
然後,因爲我是完全沒有python經驗的,所以我也不知道要安裝什麼插件,所以我就打開擴展窗口,輸入python搜索,隨便按幾個最上面的插件。
然後,先在終端裏執行下面代碼:
pip install scikit-learn
pip install matplotlib
scikit-learn是做機器學習的,matplotlib是一個繪圖的庫。
然後我們定義個數組做爲學習的源數據.
X1 = [
[0.0,0.0],
[0.0,0.3],
[0.3,0.0],
[9.0,0.0],
[9.0,0.6],
[9.6,0.0]]
然後編寫代碼:
from sklearn.cluster import KMeans
# 按F2可以重命名
xList = [
[0.0,0.0],
[0.0,0.3],
[0.3,0.0],
[9.0,0.0],
[9.0,0.6],
[9.6,0.0]]
n_clusters = 2
cluster = KMeans(n_clusters=n_clusters, random_state=0).fit(xList)
xLable = cluster.labels_
# xlable 是上面那個集合,每個元素的所屬分組
print ("xLable",xLable)
xListGroup1 =[]
xListGroup2 =[]
# 使用range時,循環的是索引,python裏叫序列
for index in range(len(xList)) :
cluster = xLable[index]
if(cluster==1):
xListGroup1.append( xList[index])
if(cluster==0):
xListGroup2.append( xList[index])
print ("xListGroup1",xListGroup1)
print ("xListGroup2",xListGroup2)
調試得到結果:
如我們期待的一樣,前3個數據比較接近,後三個比較接近,所以,分兩組的話,就是前3個一組,後3個一組。
經驗
調試時,刪除終端再建一個,不然有時候會出現莫名奇妙的異常,而實際上,代碼並沒有錯誤,這個非常耽誤時間。
使用matplotlib
使用matplotlib的make_blobs函數,生成一個大一點的數據源測試,代碼如下:
from sklearn.datasets import make_blobs
from sklearn.cluster import KMeans
xList, y = make_blobs(n_samples=500,n_features=2,centers=4,random_state=1)
n_clusters = 2
cluster = KMeans(n_clusters=n_clusters, random_state=0).fit(xList)
xLable = cluster.labels_
# xlable 是上面那個集合,每個元素的所屬分組
print ("xLable",xLable)
xListGroup1 =[]
xListGroup2 =[]
# 使用range時,循環的是索引,python裏叫序列
for index in range(len(xList)) :
cluster = xLable[index]
if(cluster==1):
xListGroup1.append( xList[index])
if(cluster==0):
xListGroup2.append( xList[index])
print ("xListGroup1",xListGroup1)
print ("xListGroup2",xListGroup2)
結語
通過上面代碼,我們簡簡單單的實現了一個機器學習。
如果想讓這個功能跟項目溝通,那就學習一下網絡編程,寫一個http監聽,然後接一組數據,用上面代碼處理完,返回一組數據即可。
同理,上面的代碼可以換成opencv的,可以換成TensorFlow的。
注:此文章爲原創,任何形式的轉載都請聯繫作者獲得授權並註明出處!
若您覺得這篇文章還不錯,請點擊下方的【推薦】,非常感謝!