python - Multivariate_normal - 选择正确的输入子集
问题描述
这类似于已经提出的问题,但是,在该问题中选择的解决方案无法按预期工作。
任务是将一个包含 48 个数据点的测试集分类为三个具有标签 (1,2,3) 的类。
pi[j]: the class weight
mu[j,:]: the mean, a 13-dimensional vector
sigma[j,:,:]: the 13x13 covariance matrix
首先,我们定义了一个将高斯模型拟合到数据的函数:
def fit_generative_model(x,y):
k = 3 # labels 1,2,...,k
d = (x.shape)[1] # number of features
mu = np.zeros((k+1,d))
sigma = np.zeros((k+1,d,d))
pi = np.zeros(k+1)
for label in range(1,k+1):
indices = (y == label)
mu[label] = np.mean(x[indices,:], axis=0)
sigma[label] = np.cov(x[indices,:], rowvar=0, bias=1)
pi[label] = float(sum(indices))/float(len(y))
return mu, sigma, pi
mu, sigma, pi = fit_generative_model(trainx,trainy)
然后我尝试编写一个函数,该函数返回前一个函数在测试数据上产生的错误数,当限制为指定的特性时。
(提示:限制对特征子集的关注是通过选择完整的 13 维均值的相应坐标和完整的 13x13 协方差矩阵的适当子矩阵)。
我的 test_model 函数定义如下:
def test_model(mu, sigma, pi, features, tx, ty):
mu, sigma, pi = fit_generative_model(trainx,trainy)
k = 3 # Labels 1,2,...,k
nt = len(testy)
score = np.zeros((nt,k+1))
for i in range(0,nt):
for label in range(1,k+1):
score[i,label] = np.log(pi[label]) + \
multivariate_normal.logpdf(testx[i,features], \
mean=mu[label,features], cov=sigma[label,features,features])
predictions = np.argmax(score[:,1:4], axis=1) + 1
errors = np.sum(predictions != testy)
return errors
现在这不适用于 3 个输入给出错误数量的错误,例如
test_model(mu, sigma, pi, [0,2,6], testx, testy)
我不明白为什么。我是否正确定义了完整协方差矩阵 cov 的适当子矩阵?
解决方案
推荐阅读
- matlab - 将阶 (NxN) 矩阵的值转换为阶 (NxN, 1) 向量
- python - 如何用自己模拟一个函数?
- firebase - 如何在 Flutter 中不使用 strembuilder 或 futurebuilder 获取单个数据表单 Firebase
- c++ - 简单的 Lua corotine 测试在第一次运行时崩溃
- python - 为什么日期时间之间的差异不对称?
- ios - 如何将文本聊天添加到 opentok 视频聊天
- wordpress - 在 Slider Revolution 6 中嵌入受密码保护的 vimeo 视频
- spring-boot - 从 Springboot 中过滤掉 Hibernate 引起的特殊错误日志
- python - 模糊逻辑:小费问题 - 输出永远不会超过阈值?
- node.js - promise-sftp 在“放置”后挂起