gpt4 book ai didi

python - 使用 GridSearch 选择 GaussianMixture 的模型

转载 作者:行者123 更新时间:2023-12-02 03:11:14 25 4
gpt4 key购买 nike

我想使用 scikit-learn 的 GaussianMixture 函数,我必须执行模型选择。
我想通过使用 GridSearchCV 来做到这一点,我想使用 BIC 和 AIC 进行选择。
这两个值都在 GaussianMixture() 中实现,但我不知道如何将它们插入到我的自定义计分器的定义中,因为函数

make_scorer(score_func, greater_is_better=True, needs_proba=False, needs_threshold=False, **kwargs)

我用来创建我的自定义记分器的函数 score_funct 作为输入,必须定义为
score_func(y, y_pred, **kwargs)

有人能帮我吗?

最佳答案

使用 BIC/AIC 是使用交叉验证的替代方法。 GridSearchCV使用交叉验证选择模型。要使用 BIC/AIC 执行模型选择,我们必须做一些不同的事情。让我们举一个例子,我们从两个高斯中生成样本,然后尝试使用 scikit-learn 拟合它们。

import numpy as np
X1 = np.random.multivariate_normal([0.,0.],[[1.,0.],[0.,1.]],10000)
X2 = np.random.multivariate_normal([10.,10.],[[1.,0.],[0.,1.]],10000)
X = np.vstack((X1,X2))
np.random.shuffle(X)

enter image description here

方法一:交叉验证

Cross validation涉及将数据分成几部分。然后将模型拟合到一些部分(“训练”)并测试它在其余部分上的表现(“验证”)。这可以防止过度拟合。在这里,我们将使用双重交叉验证,将数据分成两半。
from sklearn.mixture import GaussianMixture
from sklearn.model_selection import GridSearchCV
import matplotlib.pyplot as plt

#check 1->4 components
tuned_parameters = {'n_components': np.array([1,2,3,4])}
#construct grid search object that uses 2 fold cross validation
clf = GridSearchCV(GaussianMixture(),tuned_parameters,cv=2)
#fit the data
clf.fit(X)
#plot the number of Gaussians against their rank
plt.scatter(clf.cv_results_['param_n_components'],\
clf.cv_results_['rank_test_score'])

我们可以看到,正如我们预期的那样,2 折交叉验证有利于两个高斯分量。

enter image description here

方法二:BIC/AIC

我们可以不使用交叉验证,而是评估 BIC使用给定每个高斯数的最佳拟合模型。然后我们选择具有最低 BIC 的模型。如果使用 AIC,该过程将是相同的(尽管它是不同的统计数据,并且可以提供不同的答案:但您的代码结构将与下面相同)。
bic = np.zeros(4)
n = np.arange(1,5)
models = []
#loop through each number of Gaussians and compute the BIC, and save the model
for i,j in enumerate(n):
#create mixture model with j components
gmm = GaussianMixture(n_components=j)
#fit it to the data
gmm.fit(X)
#compute the BIC for this model
bic[i] = gmm.bic(X)
#add the best-fit model with j components to the list of models
models.append(gmm)

执行此程序后,我们可以根据 BIC 绘制高斯数。
plt.plot(n,bic)

enter image description here

所以我们可以看到 BIC 对于两个高斯被最小化,所以最好的模型
根据这种方法也有两个组成部分。

因为我从两个分离得很好的高斯(即它们中心之间的距离远大于它们的任何一个分散体)中提取了 10000 个样本,所以答案非常明确。情况并非总是如此,通常这些方法都不会自信地告诉您要使用的高斯数量,而是一些合理的范围。

关于python - 使用 GridSearch 选择 GaussianMixture 的模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39920862/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com