首页 > 解决方案 > 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 的适当子矩阵?

标签: pythoncovariancegaussian

解决方案


推荐阅读