简体   繁体   English

Python:list iteration只返回最后一个值

[英]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. 我正在使用scikit-learn进行GMM训练,并试图通过循环遍历整数列表来改变混合成分的数量。 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. 但是当我打印出我生成的模型时,我只会得到3个混合组件,或者我列出的最后一项。

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! 提前谢谢了!

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. 您在所有迭代中使用相同的covar_type作为键,从而重写相同的元素。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM