Python: list iteration only returns last value

末鹿安然 提交于 2020-01-05 17:45:14

问题


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 the ones with 3 mixture components, or whatever 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 someone help please? Many thanks in advance!


回答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)) for covar_type in covs for num in 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(...)


来源:https://stackoverflow.com/questions/20398242/python-list-iteration-only-returns-last-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!