.有以下三类样本,根据Fisher线性判决的原理,以每两类样本为1组,对样本进行分类,样本为w1=[],w2=[],w3=[],并测试xx1(-0.7,0.58,0.089)和xx2(0.047,-0.4,1.04)属于哪一类。请生成代码
时间: 2024-05-27 09:13:49 浏览: 161
import numpy as np
# 三类样本
w1 = np.array([[0.42, 0.88, 0.01], [0.1, 0.63, 0.55], [0.67, 0.27, 0.1], [0.87, 0.78, 0.94], [0.34, 0.51, 0.25]])
w2 = np.array([[0.14, 0.75, 0.45], [0.93, 0.96, 0.96], [0.87, 0.84, 0.48], [0.53, 0.53, 0.6], [0.11, 0.28, 0.83]])
w3 = np.array([[0.32, 0.25, 0.6], [0.35, 0.01, 0.33], [0.12, 0.02, 0.8], [0.74, 0.84, 0.16], [0.31, 0.99, 0.6]])
# 每两类样本为1组,进行分类
w12 = np.concatenate((w1, w2))
w23 = np.concatenate((w2, w3))
w31 = np.concatenate((w3, w1))
# 计算每组样本的均值向量
m12 = np.mean(w12, axis=0)
m23 = np.mean(w23, axis=0)
m31 = np.mean(w31, axis=0)
# 计算每组样本的散布矩阵
S12 = np.cov(w12, rowvar=False)
S23 = np.cov(w23, rowvar=False)
S31 = np.cov(w31, rowvar=False)
# 计算总散布矩阵
Sw = S12 + S23 + S31
# 计算权重向量
w = np.dot(np.linalg.inv(Sw), (m12 - m23))
# 对样本进行分类
def classify(x):
g1 = np.dot(w, x) - np.dot(w, (m12 + m23) / 2)
g2 = np.dot(w, x) - np.dot(w, (m23 + m31) / 2)
g3 = np.dot(w, x) - np.dot(w, (m31 + m12) / 2)
if g1 > 0 and g3 > 0:
return "w1"
elif g1 < 0 and g2 > 0:
return "w2"
else:
return "w3"
# 测试样本
xx1 = np.array([-0.7, 0.58, 0.089])
xx2 = np.array([0.047, -0.4, 1.04])
# 分类
print("xx1属于类别:", classify(xx1))
print("xx2属于类别:", classify(xx2))
阅读全文