1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
| import numpy as np
np.set_printoptions(precision=2)
def MaxNormalization(a): """ 采用最大值规格化法将数据规格化为 """ c = np.zeros_like(a, dtype=float) for j in range(c.shape[1]): for i in range(c.shape[0]): c[i, j] = a[i, j]/np.max(a[:, j]) return c
def FuzzySimilarMatrix(a): """ 用最大最小法构造得到模糊相似矩阵 """ a = MaxNormalization(a) c = np.zeros((a.shape[0], a.shape[0]), dtype=float) mmax = [] mmin = [] for i in range(c.shape[0]): for j in range(c.shape[0]): mmax.extend([np.fmax(a[i, :], a[j, :])]) mmin.extend([np.fmin(a[i, :], a[j, :])]) for i in range(len(mmax)): mmax[i] = np.sum(mmax[i]) mmin[i] = np.sum(mmin[i]) mmax = np.array(mmax).reshape(c.shape[0], c.shape[1]) mmin = np.array(mmin).reshape(c.shape[0], c.shape[1]) for i in range(c.shape[0]): for j in range(c.shape[1]): c[i, j] = mmin[i, j]/mmax[i, j] return c
def MatrixComposition(a, b): """ 合成模糊矩阵a和模糊矩阵b """ a, b = np.array(a), np.array(b) c = np.zeros_like(a.dot(b)) for i in range(a.shape[0]): for j in range(b.shape[1]): empty = [] for k in range(a.shape[1]): empty.append(min(a[i, k], b[k, j])) c[i, j] = max(empty) return c
def TransitiveClosure(a): """ 平方法合成传递闭包 """ a = FuzzySimilarMatrix(a) c = a while True: m = c c = MatrixComposition(MatrixComposition(a, c), MatrixComposition(a, c)) if (c == m).all(): return np.around(c, decimals=2) break else: continue
def CutSet(a): """ 水平截集 """ a = TransitiveClosure(a)
return np.sort(np.unique(a).reshape(-1))[::-1]
def get_classes(temp_pairs): lists = []
for item1 in temp_pairs: temp_list = [] for item2 in temp_pairs: if item1[0] == item2[1]: temp_list.append(item2[0]) lists.append(list(set(temp_list)))
return(list(np.unique(lists)))
def Result(a): """ 模糊聚类结果 """ lambdas = CutSet(a) a = TransitiveClosure(a)
classes = []
for lam in lambdas: if lam == lambdas[0]: classes.append([[a] for a in range(len(a))]) else: pairs = np.argwhere(a >= lam) classes.append(get_classes(pairs)) return classes
def main(): """ 特性指标矩阵 """ input = np.array([[17, 15, 14, 15, 16], [18, 16, 13, 14, 12], [18, 18, 19, 17, 18], [16, 18, 16, 15, 18]])
print("特性指标矩阵\n", input) print("\n采用最大值规格化法将数据规格化为\n", MaxNormalization(input)) print("\n用最大最小法构造得到模糊相似矩阵\n", FuzzySimilarMatrix(input)) print("\n平方法合成传递闭包\n", TransitiveClosure(input)) print("\n水平截集为\n", CutSet(input)) print("\n模糊聚类结果\n", Result(input))
if __name__ == "__main__": main()
|