python实现对Iris数据和Sonar数据的fisher线性判别分类
def Fisher(X1,X2,n,c):# 计算三类样本的类均值向量 m1=(np.mean(X1,axis = 0))m2=(np.mean(X2,axis = 0))m1 = m1.reshape(n,1) # 将行向量转换为列向量以便于计算 m2 = m2.reshape(n,1)#计算类内离散度矩阵 S1 = np.zeros((n,n)) # m1 = within_class_scatter_matrix1 S2 = np.zeros((n,n)) # m2 = within_class_scatter_matrix2 if c == 0: # 第一种情况 for i in range(0,96):S1 = (X1[i].reshape(n,1)-m1).dot((X1[i].reshape(n,1)-m1).T)for i in range(0,111):S2 = (X2[i].reshape(n,1)-m2).dot((X2[i].reshape(n,1)-m2).T)if c == 1:for i in range(0,97):S1 = (X1[i].reshape(n,1)-m1).dot((X1[i].reshape(n,1)-m1).T)for i in range(0,110):S2 = (X2[i].reshape(n,1)-m2).dot((X2[i].reshape(n,1)-m2).T)#计算总类内离散度矩阵S_w S_w = S1 S2 #计算最优投影方向 W W = np.linalg.inv(S_w).dot(m1 - m2)#在投影后的一维空间求两类的均值 m_1 = (W.T).dot(m1)m_2 = (W.T).dot(m2)#计算分类阈值 W0(为一个列向量) W0 = -0.5*(m_1 m_2)return W,W0
评论