第一个文件(FCMTEST.py)
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif']=['SimHei']
plt.rcParams['axes.unicode_minus']=False
iter_num=20
m=2
class FCM:
def __init__(self, data, clust_num):
self.data = data
self.cnum = clust_num
self.sample_num=data.shape[0]
self.dim = data.shape[-1]
Jlist=[]
U = self.Initial_U(self.sample_num, self.cnum)
for i in range(0, iter_num):
C = self.Cen_Iter(self.data, U, self.cnum)
U = self.U_Iter(U, C)
print("第%d次迭代" %(i+1) ,end="")
J = self.J_calcu(self.data, U, C)
Jlist = np.append(Jlist, J)
self.label = np.argmax(U, axis=0)
self.Clast = C
self.Jlist = Jlist
def Initial_U(self, sample_num, cluster_n):
U = np.random.rand(sample_num, cluster_n)
row_sum = np.sum(U, axis=1)
row_sum = 1 / row_sum
U = np.multiply(U.T, row_sum)
return U
def Cen_Iter(self, data, U, cluster_n):
c_new = np.empty(shape=[0, self.dim])
for i in range(0, cluster_n):
u_ij_m = U[i, :] ** m
sum_u = np.sum(u_ij_m)
ux = np.dot(u_ij_m, data)
ux = np.reshape(ux, (1, self.dim))
c_new = np.append(c_new, ux / sum_u, axis=0)
return c_new
def U_Iter(self, U, c):
for i in range(0, self.cnum):
for j in range(0, self.sample_num):
sum = 0
for k in range(0, self.cnum):
temp = (np.linalg.norm(self.data[j, :] - c[i, :]) /
np.linalg.norm(self.data[j, :] - c[k, :])) ** (
2 / (m - 1))
sum = temp + sum
U[i, j] = 1 / sum
return U
def J_calcu(self, data, U, c):
temp1 = np.zeros(U.shape)
for i in range(0, U.shape[0]):
for j in range(0, U.shape[1]):
temp1[i, j] = (np.linalg.norm(data[j, :] - c[i, :])) ** 2 * U[i, j] ** m
J = np.sum(np.sum(temp1))
print("目标函数值:%.2f" %J)
return J
def plot(self):
mark = ['or', 'xb', '^g', 'vk', 'sm', '+y', '3c']
if self.dim == 2:
plt.subplot(221)
plt.plot(self.data[:, 0], self.data[:, 1],'ob',markersize=5)
plt.title('未聚类前散点图')
plt.subplot(222)
j = 0
plt.plot(self.Clast[:, 0], self.Clast[:, 1],'k*',label='聚类中心',markersize=8)
for i in self.label:
plt.plot(self.data[j:j + 1, 0], self.data[j:j + 1, 1], mark[i],
markersize=5)
j += 1
plt.legend()
plt.title("聚类后结果")
plt.subplot(212)
plt.plot(self.Jlist, 'g-', )
plt.title("目标函数变化图",)
plt.show()
elif self.dim==1:
plt.subplot(221)
plt.title("聚类前散点图")
for j in range(0, self.data.shape[0]):
plt.plot(self.data[j, 0], 'ob',markersize=3)
plt.subplot(222)
j = 0
for i in self.label:
plt.plot(self.data[j:j + 1, 0], mark[i], markersize=3)
j += 1
plt.plot(self.Clast[:, 0], 'k*',label='聚类中心')
plt.title("聚类后结果图")
plt.legend()
plt.subplot(212)
plt.plot(self.Jlist, 'g-', )
plt.title("目标函数变化图", )
plt.show()
elif self.dim==3:
fig = plt.figure()
ax1 = fig.add_subplot(221, projection='3d')
ax1.scatter(self.data[:, 0], self.data[:, 1],self.data[:,2], "b")
ax1.set_xlabel("X 轴")
ax1.set_ylabel("Y 轴")
ax1.set_zlabel("Z 轴")
plt.title("未聚类前的图")
ax2 = fig.add_subplot(222, projection='3d')
j = 0
ax2.plot(self.Clast[:, 0], self.Clast[:, 1],self.Clast[:,2] ,'k*', label='聚类中心', markersize=8)
plt.legend()
for i in self.label:
ax2.plot(self.data[j:j+1, 0], self.data[j:j+1, 1],self.data[j:j+1,2], mark[i],markersize=5)
j += 1
ax2.set_xlabel("X 轴")
ax2.set_ylabel("Y 轴")
ax2.set_zlabel("Z 轴")
plt.title("聚类后结果")
plt.subplot(212)
plt.plot(self.Jlist, 'g-', )
plt.title("目标函数变化图", )
plt.show()
def example1():
x1 = np.zeros((10, 1))
x2 = np.zeros((10, 1))
for i in range(0, 10):
x1[i] = np.random.rand() * 5
x2[i] = np.random.rand() * 5 + 5
x = np.append(x1, x2, axis=0)
a = FCM(x, 2)
a.plot()
def example2():
x1 = np.zeros((10, 1))
y1 = np.zeros((10, 1))
x2 = np.zeros((10, 1))
y2 = np.zeros((10, 1))
x3 = np.zeros((10, 1))
y3 = np.zeros((10, 1))
for i in range(0, 10):
x1[i] = np.random.rand() * 5
y1[i] = np.random.rand() * 5
x2[i] = np.random.rand() * 5 + 5
y2[i] = np.random.rand() * 5 + 5
x3[i] = np.random.rand() * 0.5 + 1
y3[i] = np.random.rand() * 0.5 + 1
x = np.append(x1, x2, axis=0)
x = np.append(x, x3, axis=0)
y = np.append(y1, y2, axis=0)
y = np.append(y, y3, axis=0)
data = np.append(x, y, axis=1)
a = FCM(data, 3)
a.plot()
def example3():
x1 = np.zeros((10, 1))
y1 = np.zeros((10, 1))
z1= np.zeros((10, 1))
x2 = np.zeros((10, 1))
y2 = np.zeros((10, 1))
z2 = np.zeros((10, 1))
x3 = np.zeros((10, 1))
y3 = np.zeros((10, 1))
z3 = np.zeros((10, 1))
for i in range(0, 10):
x1[i] = np.random.rand() * 5
y1[i] = np.random.rand() * 5
z3[i] = np.random.rand() * 5
x2[i] = np.random.rand() * 5 + 5
y2[i] = np.random.rand() * 5 + 5
z2[i] = np.random.rand() * 5+5
x3[i] = np.random.rand() * 0.5 + 1
y3[i] = np.random.rand() * 0.5 + 1
z3[i] = np.random.rand() * 0.5 + 3
x = np.append(x1, x2, axis=0)
x = np.append(x, x3, axis=0)
y = np.append(y1, y2, axis=0)
y = np.append(y, y3, axis=0)
z = np.append(z1, z2, axis=0)
z = np.append(z, z3, axis=0)
data = np.append(x, y, axis=1)
print(data.shape)
data=np.append(data,z,axis=1)
a = FCM(data, 3)
a.plot()
第二个文件(img_segTest.py)
import FCMTEST
from FCMTEST import FCM
from PIL import Image
import numpy as np
def imgtoarr(imgpath):
img = Image.open(imgpath)
img =img.convert('L')
row = img.size[0]
col = img.size[1]
data = []
for i in range(row):
for j in range(col):
x = img.getpixel((i, j))
data = np.append(data, [x])
data = data.reshape(data.shape[0], 1)
return data, row, col
def test1():
data, row, col = imgtoarr('Mai_sakurajima.jpg')
print("图片转矩阵成功,开始聚类")
a = FCM(data, 2)
print("开始聚类生成结果图")
a.plot()
print("开始生成图片")
label = a.label
label = label.reshape([row, col])
pic_new = Image.new("L", (row, col))
for i in range(row):
for j in range(col):
pic_new.putpixel((i, j), int(256 / (label[i][j] + 1)))
pic_new.show()
pic_new.save('1.jpg')
if __name__ == '__main__':
test1()