SciPy is an open-source software for mathematics, science, and engineering.
聚类实例:
import numpy as np
from scipy.cluster.vq import vq, kmeans, whiten
import matplotlib.pyplot as pltfe=np.array([[1.9,2.0],[1.7,2.5],[1.6,3.1],[0.1,0.1],[0.8,0.3],[0.4,0.3],[0.22,0.1],[0.4, 0.3],[0.4,0.5],[1.8,1.9]]) book=np.array((fe[0],fe[1]))
print(type(book))
print("book:n",book)codebook,distortion=kmeans(fe,book)
#可以写kmeans(wf,2),2表示两个质心,同时启用iter参数
print("codebook:",codebook) #codebook聚类中心
print("distortion: ", distortion) #distortion控制方差大小plt.scatter(fe[:,0], fe[:,1], c='g') #scatter提供散点图
plt.scatter(codebook[:, 0], codebook[:, 1], c='r')
plt.show()
运行结果:红色的为聚类中心
import os
from PIL import Image
import matplotlib.pyplot as pltos.chdir(r'D:pythonAds2021')
im=np.array(Image.open('girl.png'))#用缩略图聚类
def colorz(filename,n=3):img=Image.open(filename)imgate(-90)img.thumbnail((200,200))w,h=img.sizeprint(w,h)print('w*h=',w*h)plt.axis('off')plt.imshow(img)plt.show()points=[]for count,color lors(w*h): points.append(color)return points
colorz('girl.png',3)
import numpy as np
from scipy.cluster.vq import vq, kmeans, whiten
import matplotlib.pyplot as pltpoints=colorz('girl.jpg',3)
print(points[0:10])fe = np.array(points,dtype=float) #聚类需要是Float或者Double
print(fe[0:10])
book =np.array((fe[100],fe[1],fe[8],fe[8])) #聚类中心,初始值
print(type(book))
print("book: n",book)#codebook, distortion = kmeans(fe,book)
codebook, distortion = kmeans(fe,7) #7是聚类中心个数
# 可以写kmeans(wf,2), 2表示两个质心,同时启用iter参数print("codebook:", codebook) #聚类中心
centers=np.array(codebook,dtype=int) #色彩的均值计算出来一般是浮点数,需要转化为整数int
print(centers)
print("distortion: ", distortion)fe=np.array(points)
plt.scatter(fe[:,0], fe[:,2], c='b')
plt.scatter(codebook[:, 0], codebook[:,2], c='r') #聚类中心
plt.show()
运行结果:如下7个聚类中心
本文发布于:2024-01-28 19:37:05,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/17064418299782.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |