Skip to content Skip to sidebar Skip to footer

Python: List Iteration Only Returns Last Value

I'm using scikit-learn for GMM training and am trying to vary the number of mixture components by looping over a list of integers. But when I print my resulting models I only get t

Solution 1:

This happens because in the expression:

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

You are using the same covar_type as key over all iterations, thus rewriting the same element.

If we write the code in a more readable way, this is what it's happening:

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(...)

If you want to keep all the values you should use a list of values instead of a single value or change the key.

For the list of values:

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

For different keys:

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

Post a Comment for "Python: List Iteration Only Returns Last Value"