1 Star 0 Fork 0

娄维尧/k-means-clustering-defect-inspection

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
kmeans.py 1.27 KB
一键复制 编辑 原始数据 按行查看 历史
Xunfei Zhou 提交于 2018-10-08 17:49 . Implementation of k-means
import numpy as np
from matplotlib import pyplot as plt
# Set three centers, the model should predict similar results
center_1 = np.array([1,1])
center_2 = np.array([5,5])
center_3 = np.array([8,1])
# Generate random data and center it to the three centers
data_1 = np.random.randn(200, 2) + center_1
data_2 = np.random.randn(200,2) + center_2
data_3 = np.random.randn(200,2) + center_3
data = np.concatenate((data_1, data_2, data_3), axis = 0)
def kmeans(data, k):
#assume 2d data
[m, n] = data.shape
c_old = np.zeros((k,2))
c_new = np.zeros((k,2))
for i in range(2):
mean = np.mean(data, axis = 1)[i]
std = np.std(data, axis = 1)[i]
c_old[:,[i]] = std * np.random.rand(3,1) + mean
distances = np.zeros((m, k))
#print (distances.shape)
clusters = np.zeros(m)
error = 1e6
ite = 0
while error > 1e-6 and ite <=10000:
for i in range(k):
distances[:,i] = np.linalg.norm(data - c_old[i,:], axis = 1)
clusters = np.argmin(distances, axis = 1)
for i in range(k):
c_new[i,:] =np.mean(data[clusters == i], axis = 0)
error = np.linalg.norm(c_new-c_old)
c_old = c_new
return clusters
xxx = kmeans(data, 3)
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/lou_wei_yao/k-means-clustering-defect-inspection.git
git@gitee.com:lou_wei_yao/k-means-clustering-defect-inspection.git
lou_wei_yao
k-means-clustering-defect-inspection
k-means-clustering-defect-inspection
master

搜索帮助