python实现类内类间散度矩阵,并计算其商J
1 类内类间散度矩阵的数学定义
参考博客:https://blog.csdn.net/weixin_38313518/article/details/76623744
2 类内距离的理解
参考博客:https://blog.csdn.net/ycheng_sjtu/article/details/25343043
matlab代码理解:https://blog.csdn.net/ttxzszxy/article/details/52921101
3 python实现
import numpy as np
def compute_J(encode_images, test_y):
"""
compute the sb、 sw and J .
:param encode_images: the images after encoding
:param test_y: the label.
:return:trace(sw) 、 trace(sb) and J
"""
# 获取行数row(样本数)和列数column(类别数)
_ , n_feature = encode_images.shape
row,column=test_y.shape
test=np.zeros(shape=(column,100,n_feature))
P=np.zeros(shape=(column,))
m=np.zeros(shape=(column,n_feature))
index=np.argmax(test_y,axis=1)
sw=0
# 类内散度矩阵sw+各类的均值m
for i in range(column):
test[i] = encode_images[index==i]
P[i]=len(test[i])/row
m[i]=np.mean(test[i],axis=0)
sw=sw+P[i]*np.cov(test[i],rowvar=0) #改成以行为独立的变量
# 类间散度矩阵sb
for i in range(column):
m[i]=P[i]*m[i] #每个类的均值乘类的比列
# 总体的均值m0
m0=np.sum(m,axis=0)
sb=0
for i in range(column):
t1=(m[i]-m0).reshape(1,n_feature)
t2 =(m[i]-m0).reshape(n_feature,1)
sb=sb+P[i]*np.dot(t2,t1)
J=np.trace(sb)/np.trace(sw)
return J
备注:
①因为我的模型输入和提取的特征都是一行为一个样本,所以行数代表样本数,列数表示特征数;
②标签的列数代表类别数;
③我的数据是6个种类,每个类有100个样本。
相关函数参考:
np.cov()、np.argmax()
若转载请注明出处,谢谢!