Python: list iteration returns only the last value

I use scikit-learn to train GMM and try to change the number of components in the mixture by going through the list of integers. But when I print my resulting models, I get only those that have 3 components of the mixture or something that I put as the last item in my list.

This is my code:

from sklearn.mixture import GMM

class_names = ['name1','name2','name3']
covs =  ['spherical', 'diagonal', 'tied', 'full']
num_comp = [1,2,3]

models = {}
for c in class_names:
    models[c] = dict((covar_type,GMM(n_components=num,
                covariance_type=covar_type, init_params='wmc',n_init=1, n_iter=10)) for covar_type in covs for num in num_comp)
print models

Can anybody help? Thank you very much in advance!

0
source share
1 answer

This is because in the expression:

dict((covar_type,GMM(n_components=num,
                covariance_type=covar_type, init_params='wmc',n_init=1, n_iter=10)) for covar_type in covs for num in num_comp)

You use the same key covar_typefor all iterations, thereby rewriting the same element.

If we write the code in a more readable way, this is what happens:

data = dict()
for covar_type in covs:
    for num in num_comp:
        # covar_type is the same for all iterations of this loop
        # hence only the last one "survives"
        data[covar_type] = GMM(...)

, .

:

data = dict()
for covar_type in covs:
    data[covar_type] = values = []
    for num in num_comp:
        values.append(GMM(...))

:

data = dict()
for covar_type in covs:
    for num in num_comp:
        data[(covar_type, num)] = GMM(...)
+2

All Articles